问:
Syntax error on simple if condition (if partychoice = R:)
New programmer, working in python 2.7.

With this code, I get a syntax error in the line 'if partychoice = R, stating the '=' is invalid syntax. How come it won;t let me assign the variable.

Also, I'm sure there are tons of other errors, but I have to start somewhere.

```<code>print "Welcome to 'Pass the Bill', where you will take on the role of a professional lobbyist trying to guide a bill through Congress and get it signed into law by the President!"
start = raw_input(str ('Press Y to continue:'))
print 'Great, lets get started!'
partychoice = raw_input (str("Would you like to be a Republican or Democrat? Type 'R' for Republican or 'D' for Democrat."))
if partychoice = R:
    print 'Ah, the Grand old Party of Lincoln and Reagan. Great Choice!'
    replegchoice = raw_input (str("What type of bill what you like congress to introduce? Restrictions on abortions, lower income taxes, easier access to automatic weapons, private health plans, or stricter immigration laws? ( A = abortion restrictions, L = lower taxes, AW = automatic weapons, H = private health plans, S = stricter immigration laws'))
    if replegchoice = A or a
            print 'A controversial choice, despite support of most Republicans, you are sure to face opposition from Democrats in Congress!'
    if replegchoice = L or l
            print 'A popular idea, Republicans in Congress are sure to support this idea, as will many American voters!'
    if replegchoice = AW, aw, Aw, or AW
            print 'Rural, midwest, and small town voters will love this, as will most Republicans in Congress. Democrats and voters in urban cities will surely be less supportive.'
    if replegchoice = H or h
            print 'Eimination of Medicare, Medicaid, and Obamacare! Republicans generally like the idea of making each person responsible for paying their own health care costs'
    if replegchoice = S or s
            print 'a popular idea supported by president Trump, this is sure face strong opposition from democrats and many voters.'
</code>```

Thanks everyone.

答:
There are several issues with the code:

You are using the assignment operator, =, instead of the comparative operator, ==.

You need to remember to use ' when containing and comparing strings, currently you are comparing them with the variable R instead of the letter 'R'

I removed the superfulous str() conversion inside the raw_input function.  This isn't needed as "" defines a string.

You should simply call the .lower() function on the results that way you only have to check the lower case version of the string.  It will save you a lot of time.

```<code>print "Welcome to 'Pass the Bill', where you will take on the role of a professional lobbyist trying to guide a bill through Congress and get it signed into law by the President!"
start = raw_input('Press Y to continue:')
print 'Great, lets get started!'
partychoice = raw_input("Would you like to be a Republican or Democrat? Type 'R' for Republican or 'D' for Democrat.").lower()
if partychoice == 'r':
    print 'Ah, the Grand old Party of Lincoln and Reagan. Great Choice!'
    replegchoice = raw_input ("What type of bill what you like congress to introduce? Restrictions on abortions, lower income taxes, easier access to automatic weapons, private health plans, or stricter immigration laws? ( A = abortion restrictions, L = lower taxes, AW = automatic weapons, H = private health plans, S = stricter immigration laws")
    if replegchoice == 'a':
            print 'A controversial choice, despite support of most Republicans, you are sure to face opposition from Democrats in Congress!'
    if replegchoice == 'l':
            print 'A popular idea, Republicans in Congress are sure to support this idea, as will many American voters!'
    if replegchoice == 'aw':
            print 'Rural, midwest, and small town voters will love this, as will most Republicans in Congress. Democrats and voters in urban cities will surely be less supportive.'
    if replegchoice == 'h':
            print 'Eimination of Medicare, Medicaid, and Obamacare! Republicans generally like the idea of making each person responsible for paying their own health care costs'
    if replegchoice == 's':
            print 'a popular idea supported by president Trump, this is sure face strong opposition from democrats and many voters.'
</code>```

Body:
There are several issues with the code:

You are using the assignment operator, =, instead of the comparative operator, ==.

You need to remember to use ' when containing and comparing strings, currently you are comparing them with the variable R instead of the letter 'R'

I removed the superfulous str() conversion inside the raw_input function.  This isn't needed as "" defines a string.

You should simply call the .lower() function on the results that way you only have to check the lower case version of the string.  It will save you a lot of time.

print "Welcome to 'Pass the Bill', where you will take on the role of a professional lobbyist trying to guide a bill through Congress and get it signed into law by the President!"
start = raw_input('Press Y to continue:')
print 'Great, lets get started!'
partychoice = raw_input("Would you like to be a Republican or Democrat? Type 'R' for Republican or 'D' for Democrat.").lower()
if partychoice == 'r':
    print 'Ah, the Grand old Party of Lincoln and Reagan. Great Choice!'
    replegchoice = raw_input ("What type of bill what you like congress to introduce? Restrictions on abortions, lower income taxes, easier access to automatic weapons, private health plans, or stricter immigration laws? ( A = abortion restrictions, L = lower taxes, AW = automatic weapons, H = private health plans, S = stricter immigration laws")
    if replegchoice == 'a':
            print 'A controversial choice, despite support of most Republicans, you are sure to face opposition from Democrats in Congress!'
    if replegchoice == 'l':
            print 'A popular idea, Republicans in Congress are sure to support this idea, as will many American voters!'
    if replegchoice == 'aw':
            print 'Rural, midwest, and small town voters will love this, as will most Republicans in Congress. Democrats and voters in urban cities will surely be less supportive.'
    if replegchoice == 'h':
            print 'Eimination of Medicare, Medicaid, and Obamacare! Republicans generally like the idea of making each person responsible for paying their own health care costs'
    if replegchoice == 's':
            print 'a popular idea supported by president Trump, this is sure face strong opposition from democrats and many voters.'


来源: stackexchange

问:
Editing properties of an SKSpriteNode custom class?
In my custom SKSpriteNode class, I want to be able to change properties such as anchorPoint, posistion, etc. within the custom class so I don't need to elsewhere.

```<code>import Foundation
import SpriteKit

open class Crank:SKSpriteNode {

init() {
    super.init(texture: SKTexture(imageNamed: "crank"), color:
        NSColor.white, size: CGSize(width: 155.0, height: 188.0))

    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

How would I edit other properties?

答:
Another way to do it would be to create a protocol and apply it to the standard SpriteKit classes that you are subclassing (or their ancestor).

For example:

```<code>protocol CustomSKNode
{
    var position:CGFloat  { get set }
    var zRotation:CGFloat { get set }
    // ...
}
extension SKNode: CustomSKNode {}
</code>```

Once you've done this somewhere in your project, you'll be able to access these properties of on any of your custom SKNode or SKSpriteNode without having to import SpriteKit.

ContentLicense: CC BY-SA 3.0

Body:
In my custom SKSpriteNode class, I want to be able to change properties such as anchorPoint, posistion, etc. within the custom class so I don't need to elsewhere.

import Foundation
import SpriteKit

open class Crank:SKSpriteNode {

init() {
    super.init(texture: SKTexture(imageNamed: "crank"), color:
        NSColor.white, size: CGSize(width: 155.0, height: 188.0))

    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

How would I edit other properties?

Body:
Another way to do it would be to create a protocol and apply it to the standard SpriteKit classes that you are subclassing (or their ancestor).

For example:

protocol CustomSKNode
{
    var position:CGFloat  { get set }
    var zRotation:CGFloat { get set }
    // ...
}
extension SKNode: CustomSKNode {}

Once you've done this somewhere in your project, you'll be able to access these properties of on any of your custom SKNode or SKSpriteNode without having to import SpriteKit.


问:
Inject bean into DataFetcher of GraphQL
I'm using Spring & graphql-java (graphql-java-annotation) in my project.
For retrieving data part, i'm using a DataFetcher to get data from a service (from database).

The weird thing is that: myService is always null. Anyone know the reason?

DataFetcher

```<code>@Component
public class MyDataFetcher implements DataFetcher {

    // get data from database
    @Autowired
    private MyService myService;

    @Override
    public Object get(DataFetchingEnvironment environment) {
        return myService.getData();
    }
}
</code>```

Schema

```<code>@Component
@GraphQLName("Query")
public class MyGraphSchema {

    @GraphQLField
    @GraphQLDataFetcher(MyDataFetcher.class)
    public Data getData() {
        return null;
    }
}
</code>```

MyService

```<code>@Service
public class MyService {

    @Autowired
    private MyRepository myRepo;

    @Transactional(readOnly = true)
    public Data getData() {
        return myRepo.getData();
    }
}
</code>```

Main test

```<code>@Bean
public String testGraphql(){
    GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);
    GraphQLSchema schema = newSchema().query(object).build();
    GraphQL graphql = new GraphQL(schema);

    ExecutionResult result = graphql.execute("{getData {id name desc}}");;
    Map<String, Object> v = (Map<String, Object>) result.getData();
    System.out.println(v);
    return v.toString();
}
</code>```

答:
Though @Nir's approach works (and I often use it inside JPA Event Listeners), the DataFetcher objects are Singletons, so injecting via static properties is a little hacky.

However, GraphQL's execute method allows you to pass in an object as a context, which will then be available in your DataFetchingEnvironment object inside of your DataFetcher (see the graphql.execute() line below):

```<code>@Component
public class GraphQLService {

    @Autowired
    MyService myService;

    public Object getGraphQLResult() {
        GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);
        GraphQLSchema schema = newSchema().query(object).build();
        GraphQL graphql = new GraphQL(schema);

        ExecutionResult result = graphql.execute("{getData {id name desc}}", myService);

        return result.getData();
    }
}

public class MyDataFetcher implements DataFetcher {

    @Override
    public Object get(DataFetchingEnvironment environment) {
        MyService myService = (MyService) environment.getContext();

        return myService.getData();
    }
}
</code>```

Title: Inject bean into DataFetcher of GraphQL

Body:
I'm using Spring & graphql-java (graphql-java-annotation) in my project.
For retrieving data part, i'm using a DataFetcher to get data from a service (from database).

The weird thing is that: myService is always null. Anyone know the reason?

DataFetcher

@Component
public class MyDataFetcher implements DataFetcher {

    // get data from database
    @Autowired
    private MyService myService;

    @Override
    public Object get(DataFetchingEnvironment environment) {
        return myService.getData();
    }
}

Schema

@Component
@GraphQLName("Query")
public class MyGraphSchema {

    @GraphQLField
    @GraphQLDataFetcher(MyDataFetcher.class)
    public Data getData() {
        return null;
    }
}

MyService

@Service
public class MyService {

    @Autowired
    private MyRepository myRepo;

    @Transactional(readOnly = true)
    public Data getData() {
        return myRepo.getData();
    }
}

Main test

@Bean
public String testGraphql(){
    GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);
    GraphQLSchema schema = newSchema().query(object).build();
    GraphQL graphql = new GraphQL(schema);

    ExecutionResult result = graphql.execute("{getData {id name desc}}");;
    Map<String, Object> v = (Map<String, Object>) result.getData();
    System.out.println(v);
    return v.toString();
}

Body:
Though @Nir's approach works (and I often use it inside JPA Event Listeners), the DataFetcher objects are Singletons, so injecting via static properties is a little hacky.

However, GraphQL's execute method allows you to pass in an object as a context, which will then be available in your DataFetchingEnvironment object inside of your DataFetcher (see the graphql.execute() line below):

@Component
public class GraphQLService {

    @Autowired
    MyService myService;

    public Object getGraphQLResult() {
        GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);
        GraphQLSchema schema = newSchema().query(object).build();
        GraphQL graphql = new GraphQL(schema);

        ExecutionResult result = graphql.execute("{getData {id name desc}}", myService);

        return result.getData();
    }
}

public class MyDataFetcher implements DataFetcher {

    @Override
    public Object get(DataFetchingEnvironment environment) {
        MyService myService = (MyService) environment.getContext();

        return myService.getData();
    }
}


问:
Don't understand how this code is scaling a bmp image
The following code was given to me by my instructor. I just don't understand how this is scaling a bmp image. I know the basics about bmp images (the info on wikipedia). I know that this method is supposed to multiply the rows and cols of the new image by whatever scale is. I tried to run the code by hand but it confused me even more. Any help will be much appreciated. Thanks!

```<code>int enlarge(PIXEL* original, int rows, int cols, int scale,
        PIXEL** new, int* newrows, int* newcols)
{
    //scaling the new rows & cols
    *newcols = cols * scale;
    *newrows = rows * scale;

    //memory allocated for enlaged bmp
    *new = (PIXEL*)malloc(*newrows * *newcols * sizeof(PIXEL));

    int row, col, sx, sy;

    //transverse through every row
    for (row = 0; row < rows; row++ )
    //transvere through every col
    for (col = 0; col < cols; col++ ){
        //im unsure what this is for
        PIXEL* o = original + (row * cols) + col;
    for(sy = 0; sy < scale; sy++ )
    for(sx = 0; sx < scale; sx++ )
          {
              //im unsure what this is for
              PIXEL* n = *new + (scale * row) * *newcols + (scale * col) + (sy * *newcols) + sx;
              *n = *o;
          }
    }
    return 0;
}
</code>```

Here is the struct for PIXEL.

```<code>typedef struct {
  unsigned char r;
  unsigned char g;
  unsigned char b;
} PIXEL;
</code>```

There is additional code but I do not think that is needed for this question.

答:
```<code>    PIXEL* o = original + (row * cols) + col;
</code>```

Here he is retrieving a pointer to the source pixel in the original image; it's just trivial pointer arithmetic, based on the fact that the rows in the bitmap are consecutive in memory. In general, in a C-style matrix width-wide the address of the element (x, y) is beginning + (y * width) + x.

Then, he loops over a square scale x scale wide in the target image.

```<code>for(sy = 0; sy < scale; sy++ )
for(sx = 0; sx < scale; sx++ )
      {
          //im unsure what this is for
          PIXEL* n = *new + (scale * row) * *newcols + (scale * col) + (sy * *newcols) + sx;
</code>```

The n pointer points to the target pixel in the destination image; if you match the formula above from the source image and rearrange a bit the terms, you'll see he is accessing the new image, at position

```<code>(scale * col + sx, scale * row + sy)
</code>```

(remember that the new image is *newcols wide).

```<code>          *n = *o;
</code>```

Here he's just copying the source pixel to the target pixel.

In practice, he's "expanding" each source pixel into a scale x scale square in the target image.

Body:
The following code was given to me by my instructor. I just don't understand how this is scaling a bmp image. I know the basics about bmp images (the info on wikipedia). I know that this method is supposed to multiply the rows and cols of the new image by whatever scale is. I tried to run the code by hand but it confused me even more. Any help will be much appreciated. Thanks!

int enlarge(PIXEL* original, int rows, int cols, int scale,
        PIXEL** new, int* newrows, int* newcols)
{
    //scaling the new rows & cols
    *newcols = cols * scale;
    *newrows = rows * scale;

    //memory allocated for enlaged bmp
    *new = (PIXEL*)malloc(*newrows * *newcols * sizeof(PIXEL));

    int row, col, sx, sy;

    //transverse through every row
    for (row = 0; row < rows; row++ )
    //transvere through every col
    for (col = 0; col < cols; col++ ){
        //im unsure what this is for
        PIXEL* o = original + (row * cols) + col;
    for(sy = 0; sy < scale; sy++ )
    for(sx = 0; sx < scale; sx++ )
          {
              //im unsure what this is for
              PIXEL* n = *new + (scale * row) * *newcols + (scale * col) + (sy * *newcols) + sx;
              *n = *o;
          }
    }
    return 0;
}

Here is the struct for PIXEL.

typedef struct {
  unsigned char r;
  unsigned char g;
  unsigned char b;
} PIXEL;

There is additional code but I do not think that is needed for this question.

Body:
    PIXEL* o = original + (row * cols) + col;

Here he is retrieving a pointer to the source pixel in the original image; it's just trivial pointer arithmetic, based on the fact that the rows in the bitmap are consecutive in memory. In general, in a C-style matrix width-wide the address of the element (x, y) is beginning + (y * width) + x.

Then, he loops over a square scale x scale wide in the target image.

for(sy = 0; sy < scale; sy++ )
for(sx = 0; sx < scale; sx++ )
      {
          //im unsure what this is for
          PIXEL* n = *new + (scale * row) * *newcols + (scale * col) + (sy * *newcols) + sx;

The n pointer points to the target pixel in the destination image; if you match the formula above from the source image and rearrange a bit the terms, you'll see he is accessing the new image, at position

(scale * col + sx, scale * row + sy)

(remember that the new image is *newcols wide).

          *n = *o;

Here he's just copying the source pixel to the target pixel.

In practice, he's "expanding" each source pixel into a scale x scale square in the target image.


问:
Bash join command outputs only one line
On an AIX system this command:

```<code>    join installed_versions.csv apps_status.csv
</code>```

With the following input files:

installed_versions.csv

```<code>app installed_version
appA 3.5
appB 3.5
appC 3.5
appD 4.3
appE 5.4
</code>```

apps_status.csv

```<code>app status
appA Running
appB Running
appC Running
appD Running
appF Check
</code>```

Gives me only one line of output:

```<code>    app installed_version status
</code>```

And I expect to obtain the following output:

```<code>app installed_version status
appA 3.5 Running
appB 3.5 Running
appC 3.5 Running
appD 4.3 Running
</code>```

答: I get exactly the desired output on my AIX machine,</p>

Title: Bash join command outputs only one line

Body:
On an AIX system this command:

    join installed_versions.csv apps_status.csv

With the following input files:

installed_versions.csv

app installed_version
appA 3.5
appB 3.5
appC 3.5
appD 4.3
appE 5.4

apps_status.csv

app status
appA Running
appB Running
appC Running
appD Running
appF Check

Gives me only one line of output:

    app installed_version status

And I expect to obtain the following output:

app installed_version status
appA 3.5 Running
appB 3.5 Running
appC 3.5 Running
appD 4.3 Running


问:
ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory
I am trying to use tensorflow-gpu on my system. I have re-installed it many times, it gives the error give below. But when I use tensorflow-cpu it works fine. I have cuda 8.0 toolkit installed and cudnn 5.1.</p>

```<code>  Traceback (most recent call last):
  File "finetune.py", line 17, in <module>
    import tensorflow as tf
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 61, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

答:
The problem is that you don't have environment variable CUDA_HOME set. If you think you have CUDA installed, then you need to make sure that the above environment variable is set prob=perly and contains address of the CUDA installation directory where all share libraries are located.

```<code>export CUDA_HOME=/CUDA/installation/path
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$CUDA_HOME/lib64:$CUDA_HOME/extras/CUPTI/lib64"
</code>```

Body:
I am trying to use tensorflow-gpu on my system. I have re-installed it many times, it gives the error give below. But when I use tensorflow-cpu it works fine. I have cuda 8.0 toolkit installed and cudnn 5.1.

  Traceback (most recent call last):
  File "finetune.py", line 17, in <module>
    import tensorflow as tf
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 61, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Body:
The problem is that you don't have environment variable CUDA_HOME set. If you think you have CUDA installed, then you need to make sure that the above environment variable is set prob=perly and contains address of the CUDA installation directory where all share libraries are located.

export CUDA_HOME=/CUDA/installation/path
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$CUDA_HOME/lib64:$CUDA_HOME/extras/CUPTI/lib64"


问:
Can you define your own template variables in Eclipse
In Eclipse there are templates that help you by automatically inserting some code or comments. You can edit these templates yourself via Preferences > Java > Editor > Templates. There are so-called "template variables" that you can use to make these templates a little smarter.

For instance, there is the ${see_to_overridden} variable that inserts "@see my.package.name.SpuerclassName#methodName(int, my.other.package.SomeType, ...)" into a javadoc comment. It would be really great if I could define my own variables, so that I could obtain Superclassname, SomeType etc. without having the "@see" thing prepended to it so that I could for instance link to the appropriate method. There appear to exist no template variables for this, so I was wondering if there was any way to create your own template variables.

答:
According to this Blog post (alternative link) by the eclipse team, you can.

Extend org.eclipse.ui.editors.templates, add a org.eclipse.jface.text.templates.TemplateVariableResolver and fill in the values required by the system. They should be self explanatory if you ever defined your own template.

Then implement the resolver, replacing your variable with a appropriate string.

The Blog post holds more details and screenshots.

OwnerDisplayName: Jordi

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Urs Reupke

LastEditorDisplayName: Urs Reupke


问:
How to create a sub menu from an ImageMap
I have a Nav bar that I created and it is 1 image with multiple image maps... is it possible to make sub menus from the image maps in the image/Nav Bar?</p>

答: try having a look at jQuery you might be able to attach a click event to an areas id which activates a hidden div with the sub menu items. www.jquery.com</p>


问:
Unzip string in JS
I am pulling down objects from s3. the objects are zipped, and I need to be able to unzip them and compare the contents with some strings. My problem is that I can't seem to get them properly unzipped. This is what I am seeing happen: s3 zipped -> over the wire -> to me as JS Buffer -> ???

I am unsure of what I can do next. I have seemingly tried everything, such as pako, and lzutf8 to decompress the strings, but no dice.

here is an attempt with lzutf8:

```<code>lzutf8.decompress(buffer,{outputEncoding: "String"}, (result, error) => {
    if (err) console.log(err);
    if (data) console.log(data);
});
</code>```

Here is an attempt with pako:

```<code>pako.ungzip(buffer,{to: "string"}, (result, error) => {
    if (error) console.log(err);
    if (result) console.log(data);
})
</code>```

pako throws an "incorrect header check", and lzutf8 silently does nothing.

I am not married to these libraries, so if there is anything else that will do the job, I am happy to try anything. I am guessing that my problem might have something to do with the encoding types? Not sure though.

Here is what the relevant part of my code looks like:

```<code>let pako = require('pako');
let streamBuffers = require('stream-buffers');

let ws = fs.createWriteStream(process.cwd() + 'path-to-file');
let rs = new streamBuffers.ReadableStreamBuffer();
objects.forEach((obj) => {
    console.log(obj);
    rs.on("data", (data) => {
        ws.write(pako.ungzip);
    })
    rs.push(obj);
})
</code>```

答:
You can create a readable stream from an object in S3 with the AWS SDK's createReadStream method and then pipe that through a zlib.Gunzip transform stream:

```<code>var zlib = require('zlib');
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {Bucket: <bucket>, Key: <key>};
var file = require('fs').createWriteStream(<path/to/file>);
s3.getObject(params).createReadStream().pipe(zlib.createGunzip()).pipe(file);
</code>```

Title: Unzip string in JS

Body:
I am pulling down objects from s3. the objects are zipped, and I need to be able to unzip them and compare the contents with some strings. My problem is that I can't seem to get them properly unzipped. This is what I am seeing happen: s3 zipped -> over the wire -> to me as JS Buffer -> ???

I am unsure of what I can do next. I have seemingly tried everything, such as pako, and lzutf8 to decompress the strings, but no dice.

here is an attempt with lzutf8:

lzutf8.decompress(buffer,{outputEncoding: "String"}, (result, error) => {
    if (err) console.log(err);
    if (data) console.log(data);
});

Here is an attempt with pako:

pako.ungzip(buffer,{to: "string"}, (result, error) => {
    if (error) console.log(err);
    if (result) console.log(data);
})

pako throws an "incorrect header check", and lzutf8 silently does nothing.

I am not married to these libraries, so if there is anything else that will do the job, I am happy to try anything. I am guessing that my problem might have something to do with the encoding types? Not sure though.

Here is what the relevant part of my code looks like:

let pako = require('pako');
let streamBuffers = require('stream-buffers');

let ws = fs.createWriteStream(process.cwd() + 'path-to-file');
let rs = new streamBuffers.ReadableStreamBuffer();
objects.forEach((obj) => {
    console.log(obj);
    rs.on("data", (data) => {
        ws.write(pako.ungzip);
    })
    rs.push(obj);
})

Body:
You can create a readable stream from an object in S3 with the AWS SDK's createReadStream method and then pipe that through a zlib.Gunzip transform stream:

var zlib = require('zlib');
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {Bucket: <bucket>, Key: <key>};
var file = require('fs').createWriteStream(<path/to/file>);
s3.getObject(params).createReadStream().pipe(zlib.createGunzip()).pipe(file);


问:
How to have curl or httpie access subdomains locally with Rails 5
I'm building an API with Rails 5 and trying to test post requests locally on the command line with either curl or httpie.

However, I'm using constraints subdomain: 'api' in my routes and both curl and httpie don't like that. If I open Chrome and go to http://api.localhost:3000/v1/users, I receive a valid response. However, with httpie I get this error:

```<code>    http: error: ConnectionError: HTTPConnectionPool(host='api.localhost', port=3000):
Max retries exceeded with url: /v1/users (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection
object at 0x105732550>: Failed to establish a new connection: [Errno 8]
nodename nor servname provided, or not known',)) while doing GET request to
URL: http://api.localhost:3000/v1/users
</code>```

I'm almost certin this is due to the subdomain but I can't find any documentation anywhere that refers to using subdomains with curl or httpie. How can I do this?

答:
I figured it out! Here's what I did:

Since I'm using a linux environment, I went to /etc/hosts and added a custom local host name called api.stevenlocal.com.

In my Rails app in environments/development.rb I made sure the following line was set to 1:

```<code> # Allow constraint subdomain for routes
  config.action_dispatch.tld_length = 1
</code>```

Setting it 1 tells rails that the top-level domain is going to be after one period (in this case, stevenlocal is the top-level domain and it is after .com). This is important because then Rails knows to look for my subdomain essentially after two periods (subdomain(first-period)top-level-domain(second-period)com). Rails by default has this line set to 1 but I had previously changed it.

Now on the command line, when I try http api.stevenlocal.com:3000/v1/users, it works as expected. Note that http is a curl like command used with the httpie command line tool

Body:
I'm building an API with Rails 5 and trying to test post requests locally on the command line with either curl or httpie.

However, I'm using constraints subdomain: 'api' in my routes and both curl and httpie don't like that. If I open Chrome and go to http://api.localhost:3000/v1/users, I receive a valid response. However, with httpie I get this error:

    http: error: ConnectionError: HTTPConnectionPool(host='api.localhost', port=3000):
Max retries exceeded with url: /v1/users (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection
object at 0x105732550>: Failed to establish a new connection: [Errno 8]
nodename nor servname provided, or not known',)) while doing GET request to
URL: http://api.localhost:3000/v1/users

I'm almost certin this is due to the subdomain but I can't find any documentation anywhere that refers to using subdomains with curl or httpie. How can I do this?

Body:
I figured it out! Here's what I did:

Since I'm using a linux environment, I went to /etc/hosts and added a custom local host name called api.stevenlocal.com.

In my Rails app in environments/development.rb I made sure the following line was set to 1:

 # Allow constraint subdomain for routes
  config.action_dispatch.tld_length = 1

Setting it 1 tells rails that the top-level domain is going to be after one period (in this case, stevenlocal is the top-level domain and it is after .com). This is important because then Rails knows to look for my subdomain essentially after two periods (subdomain(first-period)top-level-domain(second-period)com). Rails by default has this line set to 1 but I had previously changed it.

Now on the command line, when I try http api.stevenlocal.com:3000/v1/users, it works as expected. Note that http is a curl like command used with the httpie command line tool


问:
Having trouble with flexboxes and animation
I'm trying to animate the search bar on a website (that is still a project) the animation works, but the search input just teleports himself when the animation starts like this:

I'm using jQuery for the animation, just because I would like to do other things when I click on it, like hiding the logo and stuff like this. Here is my code:

$(".search-field").focus(function () {
    $(this).animate({ "width": "100%" }, "slow" );

    // $(".logo").fadeOut();
});
$(".search-field").focusout(function () {
    $(this).animate({ "width": "130px" }, "slow" );
    // $(".logo").fadeIn();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto+Slab');
/*! HTML5 Boilerplate v5.3.0 | MIT License | https://html5boilerplate.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
    z-index: 1;
}

/*
 * Remove text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between audio, canvas, iframes,
 * images, videos and the bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Hide visually and from screen readers
 */

.hidden {
    display: none !important;
}

/*
 * Hide only visually, but have it available for screen readers:
 * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element
 * to be focusable when navigated to via the keyboard:
 * https://www.drupal.org/node/897638
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screen readers, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 1.25dppx),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid the additional HTTP request:
   http://www.phpied.com/delay-loading-your-print-css/
   ========================================================================== */

@media print {
    *,
    *:before,
    *:after,
    *:first-letter,
    *:first-line {
        background: transparent !important;
        color: #000 !important; /* Black prints faster:
                                   http://www.sanbeiji.com/archives/953 */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links that are fragment identifiers,
     * or use the `javascript:` pseudo protocol
     */

    a[href^="#"]:after,
    a[href^="javascript:"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    /*
     * Printing Tables:
     * http://css-discuss.incutio.com/wiki/Printing_Tables
     */

    thead {
        display: table-header-group;
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}
/* ==========================================================================
   Real CSS
   ========================================================================== */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    font-size: 14px;
    line-height: 1.5;
}
.top {
    position: fixed;
    height: 50px;
    /*padding: 12px;*/
    width: 100vw;
    background-color: #24292e;
    color: rgba(255, 255, 255, 0.75);
    z-index: 10;
}
.container {
    padding-top: 2px;
    width: 980px;
    margin-right: auto;
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.nav {
    list-style: none;
    padding-left: 0;
    margin-top: 0;
    margin-bottom: 0
}
.nav-item {
    padding: 12px;
    float: left;
    list-style: none;
}
.logo {
    flex: unset;
}
.header-item {
    display: flex;
    flex-direction: row;
}
.nav-item1 {
    width: 300px;
    justify-content: space-around;
}
.nav-item3 {
    width: 300px;
    justify-content: space-between;
}
.search-field {
    width: 130px;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.3);
    background-image: url('https://cdn.rawgit.com/encharm/Font-Awesome-SVG-PNG/b7f74631/black/png/24/search.png');
    background-position: 3px 3px;
    background-repeat: no-repeat;
    padding: 6px 20px 6px 40px;
    transition: width 0.4s ease-in-out;
}

.sign {
    display: flex;
    flex-direction: row;
}
.sign-in {
    margin-left: auto;
    padding: 5px;
    border: 3px solid rgba(255, 255, 255, 0.75);
    border-right-width: 0px;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
}
.sign-up {
    margin-left: auto;
    padding: 5px;
    border: 3px solid rgba(255, 255, 255, 0.75);
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
}

.div-title {
    width: 50vw;
    position: absolute;
    margin-left: 20vw;
    margin-top: 75px;
    color: grey;
}
.posts {
    width: 50vw;
    position: absolute;
    margin-left: 20vw;
    margin-top: 125px;
}
.post {
    width: 100%;
    height: 25vh;
    border: 1px solid #F2F2F2;
    margin-bottom: 20px;
    /*box-shadow: 0px 0px 5px #888888;*/
}
.post > .profile {
    z-index: 2;
    position: absolute;
    margin-top: 7vh;
    margin-left: 20px;
}
.post > .title {
    font-family: 'Roboto Slab', serif;
    font-size: 1.5em;
    margin-left: 100px;
    margin-top: 15px;
}
.post > .content {
    margin-left: 100px;
    margin-top: 10px;
}</code>```

Logo

                        <input type="text" class="search-field" name="search" placeholder="Search...">

New

Home

Explore

Sign In

Sign Up

```

Could you help me by giving me a solution to cancel the "teleportation" or by giving me a trick to make it look smoother?

答:
The easiest way to animate width is to set the width to 100% and then animate the max-width instead.

Also it's a good idea to addClass / removeClass instead of animating with jQuery directly

Here's what I changed/added in the CSS. Then the javascript only adds the .expand

```<code>.search-field {
    width:100%;
    max-width:130px;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.3);
    background-image: url('https://cdn.rawgit.com/encharm/Font-Awesome-SVG-PNG/b7f74631/black/png/24/search.png');
    background-position: 3px 3px;
    background-repeat: no-repeat;
    padding: 6px 20px 6px 40px;
    transition: max-width 0.4s ease-in-out;
}

.search-field.expand{
    max-width:500px;
}
</code>```

Take a look at this snippet:

$(".search-field").focus(function () {
    $(this).addClass('expand');
});
$(".search-field").focusout(function () {
    $(this).removeClass('expand');
    // $(".logo").fadeIn();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto+Slab');
/*! HTML5 Boilerplate v5.3.0 | MIT License | https://html5boilerplate.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
    z-index: 1;
}

/*
 * Remove text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between audio, canvas, iframes,
 * images, videos and the bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Hide visually and from screen readers
 */

.hidden {
    display: none !important;
}

/*
 * Hide only visually, but have it available for screen readers:
 * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element
 * to be focusable when navigated to via the keyboard:
 * https://www.drupal.org/node/897638
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screen readers, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 1.25dppx),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid the additional HTTP request:
   http://www.phpied.com/delay-loading-your-print-css/
   ========================================================================== */

@media print {
    *,
    *:before,
    *:after,
    *:first-letter,
    *:first-line {
        background: transparent !important;
        color: #000 !important; /* Black prints faster:
                                   http://www.sanbeiji.com/archives/953 */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links that are fragment identifiers,
     * or use the `javascript:` pseudo protocol
     */

    a[href^="#"]:after,
    a[href^="javascript:"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    /*
     * Printing Tables:
     * http://css-discuss.incutio.com/wiki/Printing_Tables
     */

    thead {
        display: table-header-group;
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}
/* ==========================================================================
   Real CSS
   ========================================================================== */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    font-size: 14px;
    line-height: 1.5;
}
.top {
    position: fixed;
    height: 50px;
    /*padding: 12px;*/
    width: 100vw;
    background-color: #24292e;
    color: rgba(255, 255, 255, 0.75);
    z-index: 10;
}
.container {
    padding-top: 2px;
    width: 980px;
    margin-right: auto;
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.nav {
    list-style: none;
    padding-left: 0;
    margin-top: 0;
    margin-bottom: 0
}
.nav-item {
    padding: 12px;
    float: left;
    list-style: none;
}
.logo {
    flex: unset;
}
.header-item {
    display: flex;
    flex-direction: row;
}
.nav-item1 {
    width: 300px;
    justify-content: space-around;
}
.nav-item3 {
    width: 300px;
    justify-content: space-between;
}
.search-field {
    width:100%;
    max-width:130px;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.3);
    background-image: url('https://cdn.rawgit.com/encharm/Font-Awesome-SVG-PNG/b7f74631/black/png/24/search.png');
    background-position: 3px 3px;
    background-repeat: no-repeat;
    padding: 6px 20px 6px 40px;
    transition: max-width 0.4s ease-in-out;
}

.search-field.expand{
    max-width:500px;
}

.sign {
    display: flex;
    flex-direction: row;
}
.sign-in {
    margin-left: auto;
    padding: 5px;
    border: 3px solid rgba(255, 255, 255, 0.75);
    border-right-width: 0px;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
}
.sign-up {
    margin-left: auto;
    padding: 5px;
    border: 3px solid rgba(255, 255, 255, 0.75);
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
}

.div-title {
    width: 50vw;
    position: absolute;
    margin-left: 20vw;
    margin-top: 75px;
    color: grey;
}
.posts {
    width: 50vw;
    position: absolute;
    margin-left: 20vw;
    margin-top: 125px;
}
.post {
    width: 100%;
    height: 25vh;
    border: 1px solid #F2F2F2;
    margin-bottom: 20px;
    /*box-shadow: 0px 0px 5px #888888;*/
}
.post > .profile {
    z-index: 2;
    position: absolute;
    margin-top: 7vh;
    margin-left: 20px;
}
.post > .title {
    font-family: 'Roboto Slab', serif;
    font-size: 1.5em;
    margin-left: 100px;
    margin-top: 15px;
}
.post > .content {
    margin-left: 100px;
    margin-top: 10px;
}</code>```

Logo

                        <input type="text" class="search-field" name="search" placeholder="Search...">

New

Home

Explore

Sign In

Sign Up

```

Body:
I'm trying to animate the search bar on a website (that is still a project) the animation works, but the search input just teleports himself when the animation starts like this:

I'm using jQuery for the animation, just because I would like to do other things when I click on it, like hiding the logo and stuff like this. Here is my code:

$(".search-field").focus(function () {
    $(this).animate({ "width": "100%" }, "slow" );

    // $(".logo").fadeOut();
});
$(".search-field").focusout(function () {
    $(this).animate({ "width": "130px" }, "slow" );
    // $(".logo").fadeIn();
});

@import url('https://fonts.googleapis.com/css?family=Roboto+Slab');
/*! HTML5 Boilerplate v5.3.0 | MIT License | https://html5boilerplate.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
    z-index: 1;
}

/*
 * Remove text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between audio, canvas, iframes,
 * images, videos and the bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Hide visually and from screen readers
 */

.hidden {
    display: none !important;
}

/*
 * Hide only visually, but have it available for screen readers:
 * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element
 * to be focusable when navigated to via the keyboard:
 * https://www.drupal.org/node/897638
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screen readers, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 1.25dppx),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid the additional HTTP request:
   http://www.phpied.com/delay-loading-your-print-css/
   ========================================================================== */

@media print {
    *,
    *:before,
    *:after,
    *:first-letter,
    *:first-line {
        background: transparent !important;
        color: #000 !important; /* Black prints faster:
                                   http://www.sanbeiji.com/archives/953 */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links that are fragment identifiers,
     * or use the `javascript:` pseudo protocol
     */

    a[href^="#"]:after,
    a[href^="javascript:"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    /*
     * Printing Tables:
     * http://css-discuss.incutio.com/wiki/Printing_Tables
     */

    thead {
        display: table-header-group;
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}
/* ==========================================================================
   Real CSS
   ========================================================================== */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    font-size: 14px;
    line-height: 1.5;
}
.top {
    position: fixed;
    height: 50px;
    /*padding: 12px;*/
    width: 100vw;
    background-color: #24292e;
    color: rgba(255, 255, 255, 0.75);
    z-index: 10;
}
.container {
    padding-top: 2px;
    width: 980px;
    margin-right: auto;
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.nav {
    list-style: none;
    padding-left: 0;
    margin-top: 0;
    margin-bottom: 0
}
.nav-item {
    padding: 12px;
    float: left;
    list-style: none;
}
.logo {
    flex: unset;
}
.header-item {
    display: flex;
    flex-direction: row;
}
.nav-item1 {
    width: 300px;
    justify-content: space-around;
}
.nav-item3 {
    width: 300px;
    justify-content: space-between;
}
.search-field {
    width: 130px;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.3);
    background-image: url('https://cdn.rawgit.com/encharm/Font-Awesome-SVG-PNG/b7f74631/black/png/24/search.png');
    background-position: 3px 3px;
    background-repeat: no-repeat;
    padding: 6px 20px 6px 40px;
    transition: width 0.4s ease-in-out;
}

.sign {
    display: flex;
    flex-direction: row;
}
.sign-in {
    margin-left: auto;
    padding: 5px;
    border: 3px solid rgba(255, 255, 255, 0.75);
    border-right-width: 0px;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
}
.sign-up {
    margin-left: auto;
    padding: 5px;
    border: 3px solid rgba(255, 255, 255, 0.75);
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
}

.div-title {
    width: 50vw;
    position: absolute;
    margin-left: 20vw;
    margin-top: 75px;
    color: grey;
}
.posts {
    width: 50vw;
    position: absolute;
    margin-left: 20vw;
    margin-top: 125px;
}
.post {
    width: 100%;
    height: 25vh;
    border: 1px solid #F2F2F2;
    margin-bottom: 20px;
    /*box-shadow: 0px 0px 5px #888888;*/
}
.post > .profile {
    z-index: 2;
    position: absolute;
    margin-top: 7vh;
    margin-left: 20px;
}
.post > .title {
    font-family: 'Roboto Slab', serif;
    font-size: 1.5em;
    margin-left: 100px;
    margin-top: 15px;
}
.post > .content {
    margin-left: 100px;
    margin-top: 10px;
}

Logo

                        <input type="text" class="search-field" name="search" placeholder="Search...">

New

Home

Explore

Sign In

Sign Up

Could you help me by giving me a solution to cancel the "teleportation" or by giving me a trick to make it look smoother?

Body:
The easiest way to animate width is to set the width to 100% and then animate the max-width instead.

Also it's a good idea to addClass / removeClass instead of animating with jQuery directly

Here's what I changed/added in the CSS. Then the javascript only adds the .expand

.search-field {
    width:100%;
    max-width:130px;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.3);
    background-image: url('https://cdn.rawgit.com/encharm/Font-Awesome-SVG-PNG/b7f74631/black/png/24/search.png');
    background-position: 3px 3px;
    background-repeat: no-repeat;
    padding: 6px 20px 6px 40px;
    transition: max-width 0.4s ease-in-out;
}

.search-field.expand{
    max-width:500px;
}

Take a look at this snippet:

$(".search-field").focus(function () {
    $(this).addClass('expand');
});
$(".search-field").focusout(function () {
    $(this).removeClass('expand');
    // $(".logo").fadeIn();
});

@import url('https://fonts.googleapis.com/css?family=Roboto+Slab');
/*! HTML5 Boilerplate v5.3.0 | MIT License | https://html5boilerplate.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
    z-index: 1;
}

/*
 * Remove text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between audio, canvas, iframes,
 * images, videos and the bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Hide visually and from screen readers
 */

.hidden {
    display: none !important;
}

/*
 * Hide only visually, but have it available for screen readers:
 * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element
 * to be focusable when navigated to via the keyboard:
 * https://www.drupal.org/node/897638
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screen readers, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 1.25dppx),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid the additional HTTP request:
   http://www.phpied.com/delay-loading-your-print-css/
   ========================================================================== */

@media print {
    *,
    *:before,
    *:after,
    *:first-letter,
    *:first-line {
        background: transparent !important;
        color: #000 !important; /* Black prints faster:
                                   http://www.sanbeiji.com/archives/953 */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links that are fragment identifiers,
     * or use the `javascript:` pseudo protocol
     */

    a[href^="#"]:after,
    a[href^="javascript:"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    /*
     * Printing Tables:
     * http://css-discuss.incutio.com/wiki/Printing_Tables
     */

    thead {
        display: table-header-group;
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}
/* ==========================================================================
   Real CSS
   ========================================================================== */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    font-size: 14px;
    line-height: 1.5;
}
.top {
    position: fixed;
    height: 50px;
    /*padding: 12px;*/
    width: 100vw;
    background-color: #24292e;
    color: rgba(255, 255, 255, 0.75);
    z-index: 10;
}
.container {
    padding-top: 2px;
    width: 980px;
    margin-right: auto;
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.nav {
    list-style: none;
    padding-left: 0;
    margin-top: 0;
    margin-bottom: 0
}
.nav-item {
    padding: 12px;
    float: left;
    list-style: none;
}
.logo {
    flex: unset;
}
.header-item {
    display: flex;
    flex-direction: row;
}
.nav-item1 {
    width: 300px;
    justify-content: space-around;
}
.nav-item3 {
    width: 300px;
    justify-content: space-between;
}
.search-field {
    width:100%;
    max-width:130px;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.3);
    background-image: url('https://cdn.rawgit.com/encharm/Font-Awesome-SVG-PNG/b7f74631/black/png/24/search.png');
    background-position: 3px 3px;
    background-repeat: no-repeat;
    padding: 6px 20px 6px 40px;
    transition: max-width 0.4s ease-in-out;
}

.search-field.expand{
    max-width:500px;
}

.sign {
    display: flex;
    flex-direction: row;
}
.sign-in {
    margin-left: auto;
    padding: 5px;
    border: 3px solid rgba(255, 255, 255, 0.75);
    border-right-width: 0px;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
}
.sign-up {
    margin-left: auto;
    padding: 5px;
    border: 3px solid rgba(255, 255, 255, 0.75);
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
}

.div-title {
    width: 50vw;
    position: absolute;
    margin-left: 20vw;
    margin-top: 75px;
    color: grey;
}
.posts {
    width: 50vw;
    position: absolute;
    margin-left: 20vw;
    margin-top: 125px;
}
.post {
    width: 100%;
    height: 25vh;
    border: 1px solid #F2F2F2;
    margin-bottom: 20px;
    /*box-shadow: 0px 0px 5px #888888;*/
}
.post > .profile {
    z-index: 2;
    position: absolute;
    margin-top: 7vh;
    margin-left: 20px;
}
.post > .title {
    font-family: 'Roboto Slab', serif;
    font-size: 1.5em;
    margin-left: 100px;
    margin-top: 15px;
}
.post > .content {
    margin-left: 100px;
    margin-top: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top" role="banner">
            <div class="container">
                <div class="nav-item1 header-item">
                    <div class="logo">Logo</div>
                    <div class="search">
                        <input type="text" class="search-field" name="search" placeholder="Search...">
                    </div>
                </div>
                <div class="nav-item2 header-item">
                    <ul class="nav">
                        <li class="nav-item">New</li>
                        <li class="nav-item">Home</li>
                        <li class="nav-item">Explore</li>
                    </ul>
                </div>
                <div class="nav-item3 header-item">
                    <div class="sign">
                        <div class="sign-in">Sign In</div>
                        <div class="sign-up">Sign Up</div>
                    </div>
                </div>

            </div>
        </div>


问:
Styling a:visited links
I'm looking to style a:visited links in an article list. Currently this works fine with applying a color in my CSS to a:visited links, however, I am after something a little more. I'd like to add a small dot next to the article title when visited.

I've done some research and looks like anything other than applying a color to a:visited links don't work (background/background-images support has been removed due to privacy issues??) so I'm wondering if anyone has any tips or ideas? jQuery?

答:
First, the reason you should change your approach to notifying users that a link has already been visited: https://stackoverflow.com/a/10320628/2943403

Because the greater browser industry has taken specific steps to combat security holes by limiting the ways that visited links are modified/styled, if you roll your own javascript implementation it may serve to raise user suspicions of dodginess on your page/site.

Additionally, so long as your "unvisited" text color isn't grey, I think styling visited links as grey should be rather intuitive.  For this reason, I would urge you (and future SO readers) to apply this simple pure-css solution and abandon any ideas to style differently.

a{color:red;}

a:visited{color:grey;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>run snippet & click link to see effect</code>```

Title: Styling a:visited links

Body:
First, the reason you should change your approach to notifying users that a link has already been visited: https://stackoverflow.com/a/10320628/2943403

Because the greater browser industry has taken specific steps to combat security holes by limiting the ways that visited links are modified/styled, if you roll your own javascript implementation it may serve to raise user suspicions of dodginess on your page/site.

Additionally, so long as your "unvisited" text color isn't grey, I think styling visited links as grey should be rather intuitive.  For this reason, I would urge you (and future SO readers) to apply this simple pure-css solution and abandon any ideas to style differently.

a{color:red;}

a:visited{color:grey;}

<a href="#">run snippet & click link to see effect</a>


问:
C++ -& CRTP . Type erasure vs polymorphism
OK here we go. I'm trying to use the CRTP template in order to remove the need of polymorphism from my app. I use an aproach like the one bellow

```<code>template <RealType> class Base
{

    void doSomething()
    {
         static_cast<RealType>(this)->doSomethingImpl()
    }

class Derived1 : public Base
{
    void doSomethingImpl()
    {
        /* do something, for real */
    }
}

class Derived2 : public Base
{
    void doSomethingImpl()
    {
        /* do something else */
    }
}
</code>```

This aproach, if I understood correctly, allows my classes to have no vtable, so function calls are direct and don't require the extra indirection.

Now imagine I want to store all my Derived# classes in a container. Let's say a vector.

First approach : I can create a non-template SuperBase class from which Base inherits and store that in the container.

However it seems to me that if I want to do that, I will have to make doSomething virtual, in SuperBase. And my goal is mainly not to have a vtable.

Second approach : I use type erasure, i.e. something like boost::any to store my elements in the Vector.
But then, I don't see a way I can iterate over the elements and call doSomething on them, because to "use" boost::any, I need to know the real type of the object when iterating.

Do you think what I want to do is even possible ?

Seems to me that it is because doSomething() is part of Base  but except using inheritance, I can't see a way to do it ....

答:
And my goal is mainly not to have a vtable.

If you want this, then, unless you implement your own virtual dispatch system (which would likely be inferior to what the compiler does), you're stuck with templates, a.k.a. compile-time polymorphism. And as the name says, in order to use this, everything must be known at compile-time. If you need to make decisions based on runtime events (like, e.g., user input), you want runtime polymorphism.

I can't help but have to ask: Why do you want to avoid vtables? (And if you're so determined, why aren't you programming in C?)

Body:
OK here we go. I'm trying to use the CRTP template in order to remove the need of polymorphism from my app. I use an aproach like the one bellow

template <RealType> class Base
{

    void doSomething()
    {
         static_cast<RealType>(this)->doSomethingImpl()
    }

class Derived1 : public Base
{
    void doSomethingImpl()
    {
        /* do something, for real */
    }
}

class Derived2 : public Base
{
    void doSomethingImpl()
    {
        /* do something else */
    }
}

This aproach, if I understood correctly, allows my classes to have no vtable, so function calls are direct and don't require the extra indirection.

Now imagine I want to store all my Derived# classes in a container. Let's say a vector.

First approach : I can create a non-template SuperBase class from which Base inherits and store that in the container.

However it seems to me that if I want to do that, I will have to make doSomething virtual, in SuperBase. And my goal is mainly not to have a vtable.

Second approach : I use type erasure, i.e. something like boost::any to store my elements in the Vector.
But then, I don't see a way I can iterate over the elements and call doSomething on them, because to "use" boost::any, I need to know the real type of the object when iterating.

Do you think what I want to do is even possible ?

Seems to me that it is because doSomething() is part of Base  but except using inheritance, I can't see a way to do it ....


问:
open failed: EACCES (Permission denied)
I am having a very weird problem with storage accessing on some devices. The app works on my testing devices (Nexus 4 & 7, Samsung GS5). All my devices running Android 4.4.2. But I received many emails from users saying that the app can not write to the storage (neither the internal storage nor the sd card). From the log file received from user feedback, I can see the problem is the following code:

```<code>try {
    if (fStream == null) {
    fStream = new FileOutputStream(filename, true);
}
    fStream.write(data, 0, bytes);
    return;
} catch (IOException ex) {
    ex.printStackTrace();
}
</code>```

It throws exception at the line fStream = new FileOutputStream(filename, true); when creating FileOutputStream.

The stack log is:

```<code>W/System.err( 8147): Caused by: java.io.FileNotFoundException: /storage/emulated/0/my_folder/test_file_name.png: open failed: EACCES (Permission denied)
w/System.err( 8147):    at libcore.io.IoBridge.open(IoBridge.java:409)
W/System.err( 8147):    at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
W/System.err( 8147):    at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
W/System.err( 8147):    at myapp.save(SourceFile:515)
W/System.err( 8147):    ... 8 more
W/System.err( 8147): Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
W/System.err( 8147):    at libcore.io.Posix.open(Native Method)
W/System.err( 8147):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
W/System.err( 8147):    at libcore.io.IoBridge.open(IoBridge.java:393)
W/System.err( 8147):    ... 11 more
</code>```

In the AndroidManifest.xml I have the following permissions declared:

```<code> <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19"/>
    <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code>```

I've confirmed that the users are using the correct app's private on the SD card. And what's more weird is that it fails to write to internal storage as well. How can this happen if I have both read & write permissions? The users say they are not connecting their devices to the PC at that time.

Update

It turns out I am calling open and close FileOutputStream too frequently, which throws the FileNotFoundException at some point. Sounds more like a threading issue.

答:
I ran into the same problem and found that I have to request the permissions at run time, even if I have declared it in the manifest. Just as stated as Justin Fiedler's answer.

The official documentation about this are here: https://developer.android.com/training/permissions/requesting.html

My implementation is slightly different from Justin Fiedler's answer that it also implement v4 fragment's onRequestPermissionsResult method to handle the permissions request response.

```<code>public static final int REQUEST_EXTERNAL_PERMISSION_CODE = 666;

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static final String[] PERMISSIONS_EXTERNAL_STORAGE = {
        READ_EXTERNAL_STORAGE,
        WRITE_EXTERNAL_STORAGE
};

public boolean checkExternalStoragePermission(Activity activity) {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        return true;
    }

    int readStoragePermissionState = ContextCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE);
    int writeStoragePermissionState = ContextCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE);
    boolean externalStoragePermissionGranted = readStoragePermissionState == PackageManager.PERMISSION_GRANTED &&
            writeStoragePermissionState == PackageManager.PERMISSION_GRANTED;
    if (!externalStoragePermissionGranted) {
        requestPermissions(PERMISSIONS_EXTERNAL_STORAGE, REQUEST_EXTERNAL_PERMISSION_CODE);
    }

    return externalStoragePermissionGranted;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        if (requestCode == REQUEST_EXTERNAL_PERMISSION_CODE) {
            if (checkExternalStoragePermission(getActivity())) {
                // Continue with your action after permission request succeed
            }
        }
    }
}
</code>```

Title: open failed: EACCES (Permission denied)

Body:
I am having a very weird problem with storage accessing on some devices. The app works on my testing devices (Nexus 4 & 7, Samsung GS5). All my devices running Android 4.4.2. But I received many emails from users saying that the app can not write to the storage (neither the internal storage nor the sd card). From the log file received from user feedback, I can see the problem is the following code:

try {
    if (fStream == null) {
    fStream = new FileOutputStream(filename, true);
}
    fStream.write(data, 0, bytes);
    return;
} catch (IOException ex) {
    ex.printStackTrace();
}

It throws exception at the line fStream = new FileOutputStream(filename, true); when creating FileOutputStream.

The stack log is:

W/System.err( 8147): Caused by: java.io.FileNotFoundException: /storage/emulated/0/my_folder/test_file_name.png: open failed: EACCES (Permission denied)
w/System.err( 8147):    at libcore.io.IoBridge.open(IoBridge.java:409)
W/System.err( 8147):    at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
W/System.err( 8147):    at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
W/System.err( 8147):    at myapp.save(SourceFile:515)
W/System.err( 8147):    ... 8 more
W/System.err( 8147): Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
W/System.err( 8147):    at libcore.io.Posix.open(Native Method)
W/System.err( 8147):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
W/System.err( 8147):    at libcore.io.IoBridge.open(IoBridge.java:393)
W/System.err( 8147):    ... 11 more

In the AndroidManifest.xml I have the following permissions declared:

 <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19"/>
    <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

I've confirmed that the users are using the correct app's private on the SD card. And what's more weird is that it fails to write to internal storage as well. How can this happen if I have both read & write permissions? The users say they are not connecting their devices to the PC at that time.

Update

It turns out I am calling open and close FileOutputStream too frequently, which throws the FileNotFoundException at some point. Sounds more like a threading issue.

Body:
I ran into the same problem and found that I have to request the permissions at run time, even if I have declared it in the manifest. Just as stated as Justin Fiedler's answer.

The official documentation about this are here: https://developer.android.com/training/permissions/requesting.html

My implementation is slightly different from Justin Fiedler's answer that it also implement v4 fragment's onRequestPermissionsResult method to handle the permissions request response.

public static final int REQUEST_EXTERNAL_PERMISSION_CODE = 666;

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static final String[] PERMISSIONS_EXTERNAL_STORAGE = {
        READ_EXTERNAL_STORAGE,
        WRITE_EXTERNAL_STORAGE
};

public boolean checkExternalStoragePermission(Activity activity) {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        return true;
    }

    int readStoragePermissionState = ContextCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE);
    int writeStoragePermissionState = ContextCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE);
    boolean externalStoragePermissionGranted = readStoragePermissionState == PackageManager.PERMISSION_GRANTED &&
            writeStoragePermissionState == PackageManager.PERMISSION_GRANTED;
    if (!externalStoragePermissionGranted) {
        requestPermissions(PERMISSIONS_EXTERNAL_STORAGE, REQUEST_EXTERNAL_PERMISSION_CODE);
    }

    return externalStoragePermissionGranted;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        if (requestCode == REQUEST_EXTERNAL_PERMISSION_CODE) {
            if (checkExternalStoragePermission(getActivity())) {
                // Continue with your action after permission request succeed
            }
        }
    }
}


问:
Interaction with updated/entered elements
I wonder how to solve this problem in D3.js. This code below enters, updates or exits every 5 seconds and show up or disappear a random number of name elements that are part in the array dataset. This array also contains id elements. Now i want to click on a updated element that appears on screen, for example "foo" and want it's id (that means 1) shows up after I clicked that "foo"element. The name of the function is called testfunction, but i think something is not right with that function. The problem is, that the original name texts all disappear after click on it and the new id text appear. But i want them to be both on screen after using the clickfunction Hope some of you guys can help. Thanks

```<code>  var svg = d3.select("body").append("svg");

  var dataset = [{
  name: "foo", id: "1"
}, {
  name: "bar",  id: "2"
}, {
  name: "baz", id: "3"
}, ];

        print(dataset);

        setInterval(() => {
          var data = dataset.slice(Math.random() * 6);
          print(data);
        }, 7000);

        function print(data) {

            var texts = svg.selectAll(".texts")
                .data(data);

            textsExit = texts.exit().remove();

            textsEnter = texts.enter()
                .append("text")
                .attr("class", "texts");

            textsUpdate = texts.merge(textsEnter)
                .attr("x", 10)
                .attr("y", (d, i) => 20 + i * 16)
                .text((d,i) => "TextNumber" + (i+1) + ", name: " + d.name)
                .on("click", testfunction);

    function testfunction(){

                    textsUpdate
                    .attr("x", 200)
                    .attr("y", function(d, i) { return (490 + i * 28)})
                    .text(function(d, i) { return "IDNumber" + (i+1) + ", Name: "+ d.id})

                    };

        }
</code>```

答:
If I understood your problem correctly, the issue here is that you're changing your textsUpdate attributes, which will of course change textsUpdate's text positions (they don't disappear, though).

A solution is creating another text element:

var svg = d3.select("body").append("svg");

var dataset = [{
  name: "foo",
  id: "1"
}, {
  name: "bar",
  id: "2"
}, {
  name: "baz",
  id: "3"
}, ];

var testText = svg.append("text")
    .attr("x", 100)
    .attr("y", 100);

print(dataset);

setInterval(() => {
  var data = dataset.slice(Math.random() * 6);
  print(data);
}, 7000);

function print(data) {

   testText.text("");

  var texts = svg.selectAll(".texts")
    .data(data);

  textsExit = texts.exit().remove();

  textsEnter = texts.enter()
    .append("text")
    .attr("class", "texts");

  textsUpdate = texts.merge(textsEnter)
    .attr("x", 10)
    .attr("y", (d, i) => 20 + i * 16)
    .attr("cursor", "pointer")
    .text((d, i) => "TextNumber" + (i + 1) + ", name: " + d.name)
    .on("click", function(d, i) {
      testfunction(d, i);
    });

  function testfunction(data, index) {

    testText.text(function() {
        return "IDNumber" + (index + 1) + ", Name: " + data.id
      })

  };

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script></code>```

Body:
I wonder how to solve this problem in D3.js. This code below enters, updates or exits every 5 seconds and show up or disappear a random number of name elements that are part in the array dataset. This array also contains id elements. Now i want to click on a updated element that appears on screen, for example "foo" and want it's id (that means 1) shows up after I clicked that "foo"element. The name of the function is called testfunction, but i think something is not right with that function. The problem is, that the original name texts all disappear after click on it and the new id text appear. But i want them to be both on screen after using the clickfunction Hope some of you guys can help. Thanks

  var svg = d3.select("body").append("svg");

  var dataset = [{
  name: "foo", id: "1"
}, {
  name: "bar",  id: "2"
}, {
  name: "baz", id: "3"
}, ];

        print(dataset);

        setInterval(() => {
          var data = dataset.slice(Math.random() * 6);
          print(data);
        }, 7000);

        function print(data) {

            var texts = svg.selectAll(".texts")
                .data(data);

            textsExit = texts.exit().remove();

            textsEnter = texts.enter()
                .append("text")
                .attr("class", "texts");

            textsUpdate = texts.merge(textsEnter)
                .attr("x", 10)
                .attr("y", (d, i) => 20 + i * 16)
                .text((d,i) => "TextNumber" + (i+1) + ", name: " + d.name)
                .on("click", testfunction);

    function testfunction(){

                    textsUpdate
                    .attr("x", 200)
                    .attr("y", function(d, i) { return (490 + i * 28)})
                    .text(function(d, i) { return "IDNumber" + (i+1) + ", Name: "+ d.id})

                    };

        }

Body:
If I understood your problem correctly, the issue here is that you're changing your textsUpdate attributes, which will of course change textsUpdate's text positions (they don't disappear, though).

A solution is creating another text element:

var svg = d3.select("body").append("svg");

var dataset = [{
  name: "foo",
  id: "1"
}, {
  name: "bar",
  id: "2"
}, {
  name: "baz",
  id: "3"
}, ];

var testText = svg.append("text")
    .attr("x", 100)
    .attr("y", 100);

print(dataset);

setInterval(() => {
  var data = dataset.slice(Math.random() * 6);
  print(data);
}, 7000);

function print(data) {

   testText.text("");

  var texts = svg.selectAll(".texts")
    .data(data);

  textsExit = texts.exit().remove();

  textsEnter = texts.enter()
    .append("text")
    .attr("class", "texts");

  textsUpdate = texts.merge(textsEnter)
    .attr("x", 10)
    .attr("y", (d, i) => 20 + i * 16)
    .attr("cursor", "pointer")
    .text((d, i) => "TextNumber" + (i + 1) + ", name: " + d.name)
    .on("click", function(d, i) {
      testfunction(d, i);
    });

  function testfunction(data, index) {

    testText.text(function() {
        return "IDNumber" + (index + 1) + ", Name: " + data.id
      })

  };

}

<script src="https://d3js.org/d3.v4.js"></script>


问:
How do I keep a CSS container the same size?
I have 6 images next to each other in two rows. I used a CSS container to center it (couldn't use padding). However, when I shrink the screen, since the margin is set to auto, the container shrinks opposed to the blank space around the container. You can see this here . The blue is just there to show the container. The images need to stay in that order until it becomes physically impossible for them to stay there. Any help would be appreciated! Thank you in advanced!</p>

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Featured Industries</title>
</head>
<style>
.center {
    margin: auto;
    width: 66%;
    height: 625px;
    border: 3px solid #0026E3;
    padding: 0px;
}
.img {
    float: left;
}
a:hover img {
    position: relative;
    z-index: 1;
    transition: -webkit-box-shadow 0.3s ease-in-out;
    -webkit-box-shadow: 0px 3px 31px -6px rgba(0,0,0,0.75);
    -moz-box-shadow: 0px 3px 31px -6px rgba(0,0,0,0.75);
    box-shadow: 0px 3px 31px -6px rgba(0,0,0,0.75);
}
</style>
</code>```

答:
You have the container size in %, which means, in this case, it will always be 66% of the document width that matches the window's width. That's why, it shrinks when you change the window size. If you set the container width to double the width of the images, it will not shrink.

So, according to your example, this will work:

```<code>.center {
    margin: auto;
    width: 622px; /* (311 x 2) */
    height: 625px;
    border: 3px solid #0026E3;
    padding: 0px;
}
</code>```

Now you have to solve another problem when they don't fit in the windows, like in mobile phones for example. Then you can use CSS Media Queries. So now let's add another rule for when there is no space for the 2 images column.

```<code>/* This is the default behavior (mobile first) */
.center {
    margin: auto;
    width: 311px; /* 1 column by default */
    height: 625px;
    border: 3px solid #0026E3;
    padding: 0px;
}

/* Let's now modify the container size when there is space */
/* for 2 image columns */
@media screen and (min-width: 622px) {
    .center {
        width: 622px; /* 1 column by default */
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 6 images next to each other in two rows. I used a CSS container to center it (couldn't use padding). However, when I shrink the screen, since the margin is set to auto, the container shrinks opposed to the blank space around the container. You can see this here . The blue is just there to show the container. The images need to stay in that order until it becomes physically impossible for them to stay there. Any help would be appreciated! Thank you in advanced!

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Featured Industries</title>

Body:
You have the container size in %, which means, in this case, it will always be 66% of the document width that matches the window's width. That's why, it shrinks when you change the window size. If you set the container width to double the width of the images, it will not shrink.

So, according to your example, this will work:

.center {
    margin: auto;
    width: 622px; /* (311 x 2) */
    height: 625px;
    border: 3px solid #0026E3;
    padding: 0px;
}

Now you have to solve another problem when they don't fit in the windows, like in mobile phones for example. Then you can use CSS Media Queries. So now let's add another rule for when there is no space for the 2 images column.

/* This is the default behavior (mobile first) */
.center {
    margin: auto;
    width: 311px; /* 1 column by default */
    height: 625px;
    border: 3px solid #0026E3;
    padding: 0px;
}

/* Let's now modify the container size when there is space */
/* for 2 image columns */
@media screen and (min-width: 622px) {
    .center {
        width: 622px; /* 1 column by default */
    }
}