问:
PHP Traits: How to circumvenient constructors or force them to be called?
Have a look at the following trait:

```<code>trait PrimaryModelRest {

    use RestController;

    protected $primaryModel;

    public function __construct() {
        $mc = $this->getPrimaryModelClass();

        try {
            $this->primaryModel = new $mc();
            if(!($this->primaryModel instanceof Model)) {
                throw new ClassNotFoundException("Primary Model fatal exception: The given Class is not an instance of Illuminate\Database\Eloquent\Model");
            }
        } catch (Exception $e) {
            throw new WrongImplementationException("Primary Model Exception: Class not found.");
        }
    }

    /**
     * @return string: Classname of the primary model.
     */
    public abstract function getPrimaryModelClass();

    // various functions here

}
</code>```

As you can see the trait makes sure that the using class holds a certain model instance and it implements certain methods. This works as long as the implementing class does not override the constructor.

So here is my question: I want to make sure that either the constructor is called or a better solution, such that I can instantiate this model on initialization.

Please make in answer which respects Multiple inheritance as well es Multi-Level inheritance.

答:
Use a base class, this will let you handle the trait as a parent.

```<code><?php

trait StorageTrait
{
    public function __construct()
    {
        echo "Storage Trait";
    }
}

class StorageAttempt
{
    use StorageTrait;

    public function __construct()
    {
        parent::__construct();
        echo " - Storage Attempt";
    }
}

abstract class StorageBase
{
    use StorageTrait;
}

class MyStorage extends StorageBase
{
    public function __construct()
    {
        parent::__construct();
        echo ' - My Storage';
    }
}

new StorageAttempt(); // won't work - will trigger error
new MyStorage(); // will display "Storage Trait - My Storage"
</code>```

Also if you are using traits you can also work with properties and getters & setters.

Example: A Storage trait involves that a Storage Engine will be used. You can add the storageEngine property and its getters and setters. (with or without Type Hinting)

```<code>interface StorageEngineInterface{}

trait StorageTrait
{
    /**
     * @var StorageEngineInterface
     */
    protected $storageEngine;

    /**
     * @return StorageEngineInterface
     */
    public function getStorageEngine(): StorageEngineInterface
    {
        return $this->storageEngine;
    }

    /**
     * @param StorageEngineInterface $storageEngine
     */
    public function setStorageEngine(StorageEngineInterface $storageEngine)
    {
        $this->storageEngine = $storageEngine;
        return $this;
    }
}
</code>```

Note: this is just an explanation so you can better understand how Traits work

UPDATE

To avoid conflict you can use aliases for trait methods. This way you can use both constructors (from trait and from extended class) you can do the following

```<code>class DifferentStorage
{
    public function __construct()
    {
        echo ' diff ';
    }
}

class MyDifferentStorage extends DifferentStorage
{
    use StorageTrait {
        StorageTrait::__construct as otherConstructor;
    }

    public function __construct()
    {
        parent::__construct();
        self::otherConstructor();
    }
}
</code>```

Body:
Have a look at the following trait:

trait PrimaryModelRest {

    use RestController;

    protected $primaryModel;

    public function __construct() {
        $mc = $this->getPrimaryModelClass();

        try {
            $this->primaryModel = new $mc();
            if(!($this->primaryModel instanceof Model)) {
                throw new ClassNotFoundException("Primary Model fatal exception: The given Class is not an instance of Illuminate\Database\Eloquent\Model");
            }
        } catch (Exception $e) {
            throw new WrongImplementationException("Primary Model Exception: Class not found.");
        }
    }

    /**
     * @return string: Classname of the primary model.
     */
    public abstract function getPrimaryModelClass();

    // various functions here

}

As you can see the trait makes sure that the using class holds a certain model instance and it implements certain methods. This works as long as the implementing class does not override the constructor.

So here is my question: I want to make sure that either the constructor is called or a better solution, such that I can instantiate this model on initialization.

Please make in answer which respects Multiple inheritance as well es Multi-Level inheritance.

Body:
Use a base class, this will let you handle the trait as a parent.

<?php

trait StorageTrait
{
    public function __construct()
    {
        echo "Storage Trait";
    }
}

class StorageAttempt
{
    use StorageTrait;

    public function __construct()
    {
        parent::__construct();
        echo " - Storage Attempt";
    }
}

abstract class StorageBase
{
    use StorageTrait;
}

class MyStorage extends StorageBase
{
    public function __construct()
    {
        parent::__construct();
        echo ' - My Storage';
    }
}

new StorageAttempt(); // won't work - will trigger error
new MyStorage(); // will display "Storage Trait - My Storage"

Also if you are using traits you can also work with properties and getters & setters.

Example: A Storage trait involves that a Storage Engine will be used. You can add the storageEngine property and its getters and setters. (with or without Type Hinting)

interface StorageEngineInterface{}

trait StorageTrait
{
    /**
     * @var StorageEngineInterface
     */
    protected $storageEngine;

    /**
     * @return StorageEngineInterface
     */
    public function getStorageEngine(): StorageEngineInterface
    {
        return $this->storageEngine;
    }

    /**
     * @param StorageEngineInterface $storageEngine
     */
    public function setStorageEngine(StorageEngineInterface $storageEngine)
    {
        $this->storageEngine = $storageEngine;
        return $this;
    }
}

Note: this is just an explanation so you can better understand how Traits work

UPDATE

To avoid conflict you can use aliases for trait methods. This way you can use both constructors (from trait and from extended class) you can do the following

class DifferentStorage
{
    public function __construct()
    {
        echo ' diff ';
    }
}

class MyDifferentStorage extends DifferentStorage
{
    use StorageTrait {
        StorageTrait::__construct as otherConstructor;
    }

    public function __construct()
    {
        parent::__construct();
        self::otherConstructor();
    }
}


来源: stackexchange

问:
Property not set when using Task.Run
Vendors is bound to a combobox

```<code>//This works, Vendor is set
LoadVendors();
Vendor = Vendors.FirstOrDefault();
</code>```

I would like LoadVendors() to Run in a separate thread, however Vendor is not set. Can somebody help?

```<code>//Doesn't work, Vendor is not set!
System.Threading.Tasks.Task.Run(() => LoadVendors()).ContinueWith((t) => Vendor = Vendors.FirstOrDefault());
</code>```

Vendors

```<code>public ObservableCollection<Vendor> Vendors
    {
        get
        {
            return _vendors;
        }

        set
        {
            if (_vendors != value)
            {
                var oldVendors = new ObservableCollection<Vendor>(_vendors);
                _vendors = value;
                RaisePropertyChanged(nameof(Vendors), oldVendors, Vendors, true);
            }

        }
    }
</code>```

LoadVendors

```<code>private void LoadVendors()
    {

            var vendors = DataHelper.GetVendors()
            DispatcherHelper.CheckBeginInvokeOnUI(() => Vendors.Clear());
            vendors.ForEach(dcpV =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() => Vendors.Add(vendor));
            });
            RaisePropertyChanged(nameof(Vendors));

    }
</code>```

答:
Call the DataHelper.GetVendors method on the background thread and do everything else back on the UI thread:

```<code>Task.Factory.StartNew(()=> DataHelper.GetVendors())
    .ContinueWith(task =>
    {
        Vendors.Clear();
        foreach (var vendor in task.Result)
            Vendors.Add(vendor);
        RaisePropertyChanged(nameof(Vendors));
        Vendor = Vendors.FirstOrDefault();
    }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
</code>```

ContentLicense: CC BY-SA 3.0

Title: Property not set when using Task.Run

Body:
Vendors is bound to a combobox

//This works, Vendor is set
LoadVendors();
Vendor = Vendors.FirstOrDefault();

I would like LoadVendors() to Run in a separate thread, however Vendor is not set. Can somebody help?

//Doesn't work, Vendor is not set!
System.Threading.Tasks.Task.Run(() => LoadVendors()).ContinueWith((t) => Vendor = Vendors.FirstOrDefault());

Vendors

public ObservableCollection<Vendor> Vendors
    {
        get
        {
            return _vendors;
        }

        set
        {
            if (_vendors != value)
            {
                var oldVendors = new ObservableCollection<Vendor>(_vendors);
                _vendors = value;
                RaisePropertyChanged(nameof(Vendors), oldVendors, Vendors, true);
            }

        }
    }

LoadVendors

private void LoadVendors()
    {

            var vendors = DataHelper.GetVendors()
            DispatcherHelper.CheckBeginInvokeOnUI(() => Vendors.Clear());
            vendors.ForEach(dcpV =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() => Vendors.Add(vendor));
            });
            RaisePropertyChanged(nameof(Vendors));

    }

Body:
Call the DataHelper.GetVendors method on the background thread and do everything else back on the UI thread:

Task.Factory.StartNew(()=> DataHelper.GetVendors())
    .ContinueWith(task =>
    {
        Vendors.Clear();
        foreach (var vendor in task.Result)
            Vendors.Add(vendor);
        RaisePropertyChanged(nameof(Vendors));
        Vendor = Vendors.FirstOrDefault();
    }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());


问:
Does postgres "SELECT FOR UPDATE" restrict to create new foreign key references ?
There are two tables, one is referenced by another with foreign key constraint.

```<code>CREATE TABLE record
(
  id                    UUID PRIMARY KEY  NOT NULL
);

CREATE TABLE task
(
  id                    UUID PRIMARY KEY  NOT NULL,
  record_id       UUID,
  CONSTRAINT fk_task_record_id FOREIGN KEY (record_id)
  REFERENCES record (id)
);
</code>```

The question is : if lock on record row is aquired by

```<code>SELECT * FROM record where id = 'A' FOR UPDATE OF record
</code>```

Could I create new foreign key in task table and reference this very record row
?

```<code>INSERT INTO task VALUES ('someId', 'A');
</code>```

Does Postgres prevent creating new foreign key references on  tables locked by SELECT FOR UPDATE OF?

答:
No, it does not.

select .. for update only blocks changes (update, delete) to that row.

It does not prevent other transactions from reading that row and that's what is required to insert a row referencing the locked row.

Body:
There are two tables, one is referenced by another with foreign key constraint.

CREATE TABLE record
(
  id                    UUID PRIMARY KEY  NOT NULL
);

CREATE TABLE task
(
  id                    UUID PRIMARY KEY  NOT NULL,
  record_id       UUID,
  CONSTRAINT fk_task_record_id FOREIGN KEY (record_id)
  REFERENCES record (id)
);

The question is : if lock on record row is aquired by

SELECT * FROM record where id = 'A' FOR UPDATE OF record

Could I create new foreign key in task table and reference this very record row
?

INSERT INTO task VALUES ('someId', 'A');

Does Postgres prevent creating new foreign key references on  tables locked by SELECT FOR UPDATE OF?


问:
How to pass a PHP variable to Vue component instance in Laravel blade?
How can I pass a value of a PHP variable to a Vue component in Laravel blade files?

In my example, I have an inline template client-details, I get this view from Laravel so now I want to pass the id which comes with the url /client/1 to my Vue instance.

My component, which is loaded by Laravel, looks like:

```<code><client-details inline-template>
    <div id="client-details" class="">
          My HTML stuff
    </div>
</client-details>
</code>```

and mounted by:

```<code>Vue.component('client-details', {
    data(){
        return {
            clientId: null
        }
    },
);
</code>```

I already tried like

```<code>:clientId="{{ $client->id }"
</code>```

but it does not work.

答:
I had to pass some server data to my Vue component, I ended up creating a $server_data variable in the controller and passing it in a json script tag.

In the controller:

$server_data = json_encode([
    "some-data" => SomeObject::all()
]);

return View::make('myview', compact('server_data'));
```

<p>In the template:</p>

<pre class="lang-php prettyprint-override"><code><script type="application/json" name="server-data">
    {{ $server_data }}
</script>
<!-- Inserts server data into window.server_data -->
<script>
    var json = document.getElementsByName("server-data")[0].innerHTML;
    var server_data = JSON.parse(json);
</script>
</code>```

In the vue initialisation, I put a computed property:

computed: {
    'server_data': function(){
        return window.server_data;
    }
}
```

Then, the data is accessible in the component template with server_data.some_object.

This allows to pass a lot of structured data without needing many html attributes. Another benefit is that the data is escaped by the the json encoding. This avoids potential bugs with variables that contain double quotes ("), which would mess up the dom.

ContentLicense: CC BY-SA 4.0

Body:
How can I pass a value of a PHP variable to a Vue component in Laravel blade files?

In my example, I have an inline template client-details, I get this view from Laravel so now I want to pass the id which comes with the url /client/1 to my Vue instance.

My component, which is loaded by Laravel, looks like:

<client-details inline-template>

          My HTML stuff

</client-details>

and mounted by:

Vue.component('client-details', {
    data(){
        return {
            clientId: null
        }
    },
);

I already tried like

:clientId="{{ $client->id }"

but it does not work.

Body:
I had to pass some server data to my Vue component, I ended up creating a $server_data variable in the controller and passing it in a json script tag.

In the controller:

$server_data = json_encode([
    "some-data" => SomeObject::all()
]);

return View::make('myview', compact('server_data'));

In the template:

<script type="application/json" name="server-data">
    {{ $server_data }}
</script>
<!-- Inserts server data into window.server_data -->
<script>
    var json = document.getElementsByName("server-data")[0].innerHTML;
    var server_data = JSON.parse(json);
</script>

In the vue initialisation, I put a computed property:

computed: {
    'server_data': function(){
        return window.server_data;
    }
}

Then, the data is accessible in the component template with server_data.some_object.

This allows to pass a lot of structured data without needing many html attributes. Another benefit is that the data is escaped by the the json encoding. This avoids potential bugs with variables that contain double quotes ("), which would mess up the dom.


问:
What is a unix command for deleting the first N characters of a line?
For example, I might want to:

```<code>tail -f logfile | grep org.springframework | <command to remove first N characters>
</code>```

I was thinking that tr might have the ability to do this but I'm not sure.

答:
Here is simple function, tested in bash. 1st param of function is string, 2nd param is number of characters to be stripped

function stringStripNCharsFromStart {
    echo ${1:$2:${#1}}
}
```
<p><strong>Usage</strong>:</p>
<pre class="lang-bash prettyprint-override"><code>$ stringStripNCharsFromStart "12abcdefgh-" 2
# 2abcdefgh-
</code>```

Screenshot:

Body:
For example, I might want to:

tail -f logfile | grep org.springframework | <command to remove first N characters>

I was thinking that tr might have the ability to do this but I'm not sure.

Body:
Here is simple function, tested in bash. 1st param of function is string, 2nd param is number of characters to be stripped

function stringStripNCharsFromStart {
    echo ${1:$2:${#1}}
}

Usage:

$ stringStripNCharsFromStart "12abcdefgh-" 2
# 2abcdefgh-

Screenshot:


问:
How to use a Pandas series as a lookup for another series
For two series: one with numeric identifiers and another that is a lookup associating those identifiers to names, how can I join them?  Example:

Series with numeric IDs:

```<code>data_series = pd.Series(np.random.randint(0,100,5),
                        index = ["id_"+i for i in np.arange(5).astype('str')])
print(data_series)

id_0    38
id_1    35
id_2    36
id_3    32
id_4    94
dtype: int64
</code>```

Series with names to look up:

```<code>name_lookup_series = pd.Series(['Google','YouTube','Facebook','Baidu','Wikipedia'],
                        index=["id_"+i for i in np.arange(5).astype('str')])
print(name_lookup_series)

id_0       Google
id_1      YouTube
id_2     Facebook
id_3        Baidu
id_4    Wikipedia
dtype: object
</code>```

Desired data frame:

```<code>Google       38
YouTube      35
Facebook     36
Baidu        32
Wikipedia    94
dtype: int64
</code>```

I am able to do this by hacking away with Pandas-fu, but this such a common join-looking operation I assume there is a more idiomatic way to do it.  My current method:

```<code>data_series.index = data_series.index.map(lambda x: name_lookup_series.loc[x])
</code>```

Is there another way to do this, preferably with cleaner code and in one line?

答:
Use rename only - because working with index:

```<code>s = data_series.rename(name_lookup_series)
#it is same as
#s = data_series.rename(index=name_lookup_series)
print (s)
Google       29
YouTube      57
Facebook     48
Baidu        16
Wikipedia    14
dtype: int32
</code>```

Another solution - a bit complicated - is convert to Series and map:

```<code>data_series.index = data_series.index.to_series().map(name_lookup_series)
print (data_series)
Google       29
YouTube      57
Facebook     48
Baidu        16
Wikipedia    14
dtype: int32
</code>```

Body:
For two series: one with numeric identifiers and another that is a lookup associating those identifiers to names, how can I join them?  Example:

Series with numeric IDs:

data_series = pd.Series(np.random.randint(0,100,5),
                        index = ["id_"+i for i in np.arange(5).astype('str')])
print(data_series)

id_0    38
id_1    35
id_2    36
id_3    32
id_4    94
dtype: int64

Series with names to look up:

name_lookup_series = pd.Series(['Google','YouTube','Facebook','Baidu','Wikipedia'],
                        index=["id_"+i for i in np.arange(5).astype('str')])
print(name_lookup_series)

id_0       Google
id_1      YouTube
id_2     Facebook
id_3        Baidu
id_4    Wikipedia
dtype: object

Desired data frame:

Google       38
YouTube      35
Facebook     36
Baidu        32
Wikipedia    94
dtype: int64

I am able to do this by hacking away with Pandas-fu, but this such a common join-looking operation I assume there is a more idiomatic way to do it.  My current method:

data_series.index = data_series.index.map(lambda x: name_lookup_series.loc[x])

Is there another way to do this, preferably with cleaner code and in one line?

Body:
Use rename only - because working with index:

s = data_series.rename(name_lookup_series)
#it is same as
#s = data_series.rename(index=name_lookup_series)
print (s)
Google       29
YouTube      57
Facebook     48
Baidu        16
Wikipedia    14
dtype: int32

Another solution - a bit complicated - is convert to Series and map:

data_series.index = data_series.index.to_series().map(name_lookup_series)
print (data_series)
Google       29
YouTube      57
Facebook     48
Baidu        16
Wikipedia    14
dtype: int32


问:
File not uploaded to s3 bucket
I am trying to upload file to aws-s3 bucket using spring mvc rest api. Here is my credentials format  to access s3 bucket

```<code>[default]
aws_access_key_id = Access key id
aws_secret_access_key = secret access key
</code>```

Here is my Java code:

```<code>@RestController
public class UploadController {

private static String bucketName= "mp4-upload-1";
private static String keyName= "secret access key";
public static final Logger logger=LogManager.getLogger(UploadController.class);

@RequestMapping(value="/uploadVideo", method = RequestMethod.POST, consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadVideo(@RequestParam("file") MultipartFile file) throws IOException {

    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
    try {
        System.out.println("Uploading a new object to S3 from a file\n");

        InputStream is=file.getInputStream();

        s3client.putObject(new PutObjectRequest(bucketName, keyName,is,new ObjectMetadata()).withCannedAcl(CannedAccessControlList.PublicRead));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which " +
                "means your request made it " +
                "to Amazon S3, but was rejected with an error response" +
                " for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " +
                "means the client encountered " +
                "an internal error while trying to " +
                "communicate with S3, " +
                "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
    return new ResponseEntity<>(HttpStatus.OK);

}
</code>```

}

The problem is I am not getting any error but file is not uploading to s3-bucket. am I missing anything here? Thanks in advance

答:
The content length should be specified on the request when the stream is uploaded directly to S3.

```<code>ObjectMetadata objMetadata = new ObjectMetadata()
objMetadata.setContentLength(20L);
</code>```

When uploading directly from an input stream, content length must be
  specified before data can be uploaded to Amazon S3. If not provided,
  the library will have to buffer the contents of the input stream in
  order to calculate it. Amazon S3 explicitly requires that the content
  length be sent in the request headers before any of the data is sent.

Refer this for content length calculation

Alternate Approach:-

Use org.springframework.util.FileCopyUtils.copyToByteArray() to convert the stream to byte[] and upload the byte array to S3.

Title: File not uploaded to s3 bucket

Body:
I am trying to upload file to aws-s3 bucket using spring mvc rest api. Here is my credentials format  to access s3 bucket

[default]
aws_access_key_id = Access key id
aws_secret_access_key = secret access key

Here is my Java code:

@RestController
public class UploadController {

private static String bucketName= "mp4-upload-1";
private static String keyName= "secret access key";
public static final Logger logger=LogManager.getLogger(UploadController.class);

@RequestMapping(value="/uploadVideo", method = RequestMethod.POST, consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadVideo(@RequestParam("file") MultipartFile file) throws IOException {

    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
    try {
        System.out.println("Uploading a new object to S3 from a file\n");

        InputStream is=file.getInputStream();

        s3client.putObject(new PutObjectRequest(bucketName, keyName,is,new ObjectMetadata()).withCannedAcl(CannedAccessControlList.PublicRead));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which " +
                "means your request made it " +
                "to Amazon S3, but was rejected with an error response" +
                " for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " +
                "means the client encountered " +
                "an internal error while trying to " +
                "communicate with S3, " +
                "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
    return new ResponseEntity<>(HttpStatus.OK);

}

}

The problem is I am not getting any error but file is not uploading to s3-bucket. am I missing anything here? Thanks in advance

Body:
The content length should be specified on the request when the stream is uploaded directly to S3.

ObjectMetadata objMetadata = new ObjectMetadata()
objMetadata.setContentLength(20L);

When uploading directly from an input stream, content length must be
  specified before data can be uploaded to Amazon S3. If not provided,
  the library will have to buffer the contents of the input stream in
  order to calculate it. Amazon S3 explicitly requires that the content
  length be sent in the request headers before any of the data is sent.

Refer this for content length calculation

Alternate Approach:-

Use org.springframework.util.FileCopyUtils.copyToByteArray() to convert the stream to byte[] and upload the byte array to S3.


问:
Docker, multiple MySQL containers on same network - intermittent connection problems
Fairly new to docker, but I have 2 projects - project-a and project-b, I would like to develop on them both locally using docker, with an nginx-proxy container to route between them.

So far I have:

1) Create a new docker network called 'my-network' in bridge mode.
2) Started up nginx-proxy container, and configured dnsmasq to route '.dev' domains to individual containers (this all works fine)
3) Starting up project-a with the following docker-compose.yml file

```<code>version: '3.2'

services:
  web:
    image: brettt89/silverstripe-web
    working_dir: /var/www
    restart: unless-stopped
    volumes:
      - .:/var/www/html
    environment:
      - VIRTUAL_HOST=project-a.dev

  db:
    image: mysql
    volumes:
      - db-data:/var/lib/mysql
    restart: unless-stopped
    environment:
      MYSQL_ROOT_PASSWORD: password

volumes:
  db-data:

networks:
  default:
    external:
      name: my-network
</code>```

This all works as expected with nginx-proxy routing requests for project-a.dev through to this container. MySQL queries work as expected.

However, once I start project-b with the same docker-compose file (except changing the VIRTUAL_HOST env variable to project-b.dev) the problems begin. I can successfully navigate to project-b.dev, however I get intermittent database connection errors across page loads and refreshes - the same errors also start to occur on project-a.dev

Does anyone have any ideas what I'm doing wrong?

答:
As you use the same docker compose, you have 2 database containers, 1 for each project. But they use the same volume. I think it can be a problem. Try to modify the volume name for tour project B (db-data-b for example).

*EDIT for the good answer: *
Try not to use the bridged network or inspect containers to avoid IP conflicts.

Body:
Fairly new to docker, but I have 2 projects - project-a and project-b, I would like to develop on them both locally using docker, with an nginx-proxy container to route between them.

So far I have:

1) Create a new docker network called 'my-network' in bridge mode.
2) Started up nginx-proxy container, and configured dnsmasq to route '.dev' domains to individual containers (this all works fine)
3) Starting up project-a with the following docker-compose.yml file

version: '3.2'

services:
  web:
    image: brettt89/silverstripe-web
    working_dir: /var/www
    restart: unless-stopped
    volumes:
      - .:/var/www/html
    environment:
      - VIRTUAL_HOST=project-a.dev

  db:
    image: mysql
    volumes:
      - db-data:/var/lib/mysql
    restart: unless-stopped
    environment:
      MYSQL_ROOT_PASSWORD: password

volumes:
  db-data:

networks:
  default:
    external:
      name: my-network

This all works as expected with nginx-proxy routing requests for project-a.dev through to this container. MySQL queries work as expected.

However, once I start project-b with the same docker-compose file (except changing the VIRTUAL_HOST env variable to project-b.dev) the problems begin. I can successfully navigate to project-b.dev, however I get intermittent database connection errors across page loads and refreshes - the same errors also start to occur on project-a.dev

Does anyone have any ideas what I'm doing wrong?


问:
Goroutines and messages de-duplicatioin
So I have some kind of event queues and several goroutines which are getting the events from their corresponding queues in an infinite loop, process them, and send results into a channel. Different queues may give you the same event, so I need to make sure that each event is sent to channel exactly once, and any occurence of that message in another queue will be ignored. I believe that's more of an architectural issue but I can't figure out how to handle this properly.

Simplified version of my current code is below.

Goroutines that get and handle incoming events look somewhat like this:

```<code>func (q *Queue) ProcessEvents(handler Handler) {
   lastEvent = 0
   for {
       events = getEvents(lastEvent)
       for _, e := range events {
           if e.ID > lastEvent  {
                lastEvent = event.ID
           }
           handler.Handle(e)
       }
   }
}
</code>```

Handler:

```<code>type Handler struct {
    c chan Event
}

func (h *Handler) Handle(event *Event) {
    //event processing omitted
    h.c <- event //Now it just sends a processed event into the channel no matter what.
}
</code>```

And in main() I do

```<code>func main() {
    msgc := make(chan Event)
    for _, q := range queues {
        go func(queue Queue) {
            queue.ProcessEvents(&Handler{msgc})
        }
    }
}
</code>```

答:
So you represent your current architecture as follows:

With this type of solution the Generators need to check a shared resource to see if an event was already emitted. This might look something like this:

```<code>var hasEmmited map[string]bool
var lock sync.Mutex

func HasEmitted(event e) bool {
   lock.Lock()
   defer lock.Unlock()
   e,ok := hasEmmited[e.ID]
   return e && ok
}

func SetEmmited(event e) {
   lock.Lock()
   defer lock.Unlock()
   hasEmmited[e.ID] = true
}

</code>```

This requires locking/unlocking, which even in the best case scenario with no contention is till a great over-head considering the small amount of work being done in the critical section.

With a small change in the architecture, like in the second diagram, it would be possible for one go-routine to to do the filtering without any locking.

Some commenters have said that designing solutions using go-routines is the same as designing for single-threaded applications. I do not believe this is the case.
I would suggest looking at:

Golang related messaging: https://blog.golang.org/pipelines

Some message handling design patterns: http://www.enterpriseintegrationpatterns.com/

The enterprise integration patterns might look out of place here, but it covers a lot of message passing patters that also applies in go.

Title: Goroutines and messages de-duplicatioin

Body:
So I have some kind of event queues and several goroutines which are getting the events from their corresponding queues in an infinite loop, process them, and send results into a channel. Different queues may give you the same event, so I need to make sure that each event is sent to channel exactly once, and any occurence of that message in another queue will be ignored. I believe that's more of an architectural issue but I can't figure out how to handle this properly.

Simplified version of my current code is below.

Goroutines that get and handle incoming events look somewhat like this:

func (q *Queue) ProcessEvents(handler Handler) {
   lastEvent = 0
   for {
       events = getEvents(lastEvent)
       for _, e := range events {
           if e.ID > lastEvent  {
                lastEvent = event.ID
           }
           handler.Handle(e)
       }
   }
}

Handler:

type Handler struct {
    c chan Event
}

func (h *Handler) Handle(event *Event) {
    //event processing omitted
    h.c <- event //Now it just sends a processed event into the channel no matter what.
}

And in main() I do

func main() {
    msgc := make(chan Event)
    for _, q := range queues {
        go func(queue Queue) {
            queue.ProcessEvents(&Handler{msgc})
        }
    }
}

Body:
So you represent your current architecture as follows:

With this type of solution the Generators need to check a shared resource to see if an event was already emitted. This might look something like this:

var hasEmmited map[string]bool
var lock sync.Mutex

func HasEmitted(event e) bool {
   lock.Lock()
   defer lock.Unlock()
   e,ok := hasEmmited[e.ID]
   return e && ok
}

func SetEmmited(event e) {
   lock.Lock()
   defer lock.Unlock()
   hasEmmited[e.ID] = true
}

This requires locking/unlocking, which even in the best case scenario with no contention is till a great over-head considering the small amount of work being done in the critical section.

With a small change in the architecture, like in the second diagram, it would be possible for one go-routine to to do the filtering without any locking.

Some commenters have said that designing solutions using go-routines is the same as designing for single-threaded applications. I do not believe this is the case.
I would suggest looking at:

Golang related messaging: https://blog.golang.org/pipelines

Some message handling design patterns: http://www.enterpriseintegrationpatterns.com/

The enterprise integration patterns might look out of place here, but it covers a lot of message passing patters that also applies in go.


问:
How to force GCC to warn about usage of a class function?
Using GCC 4.8.*, when the warning -Wfloat-equal is activated, the compiler warns about strict comparisons between floting point number, like in the following example:

```<code>double x = 3.14159;
double y = 1.11111;
if(x == y) // <-- this induces a warning
{ /* ... */ }
</code>```

Now, imagine I want a class containing double variables and defining the equality operator:

```<code>class Complex // (it's only an example)
{
  private:
    double re;
    double im;
  public:
    bool operator == (Complex const& z) const;
};
bool Complex::operator == (Complex const& z) const
{
  return (this->re == z.re) && (this->im == z.im);
}
</code>```

This does exactly what I expect. Of course, it induces a warning when I compile the class. In order to avoid it (because I understand the warning, thanks to the compiler, but I want to do that, and I don't want to continue to see the warning), I inform the compiler by this way:

```<code>#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
bool Complex::operator == (Complex const& z) const
{
  return (this->re == z.re) && (this->im == z.im);
}
#pragma GCC diagnostic pop
</code>```

Okay, I don't have the warning when I compile my Complex.cpp file. But it's still dangerous to use the operator == on complex numbers, exaclty like it's dangerous to use operator == on double numbers (it's the reason for the existence of the option -Wfloat-equal). Then, my question:

Is it possible to have a GCC warning (activated by -Wfloat-equal) where the operator == on complex numbers is used ? It's not the existence of the operator I want to warn, but the usage.

Note: I defined the symmetric operator as a class member, but I'm open to have a class function bool equals(...) const called by a bool operator == (Complex const&,Complex const&) if it can simplify my expected behavior.

Note: I don't use C++11 for compatibility reasons.

答:
How about using an Exactly wrapper type that expresses the intent clearly?

```<code>template<typename T>
struct Exactly : T
{
    explicit Exactly(T const& value) : T(value) {}
};

class Complex
{
    double re;
    double im;

public:
    Complex(double re, double im) : re(re), im(im) {}

    // Non-members require either friend access or public getters.
    double real() const { return re; }
    double imag() const { return im; }
};

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
bool operator == (Complex const& a, Exactly<Complex> const& b)
{
    return (a.real() == b.real()) && (a.imag() == b.imag());
}
// two more overloads for completeness
bool operator == (Exactly<Complex> const& a, Complex const& b)
{
    return (a.real() == b.real()) && (a.imag() == b.imag());
}
bool operator == (Exactly<Complex> const& a, Exactly<Complex> const& b)
{
    return (a.real() == b.real()) && (a.imag() == b.imag());
}
#pragma GCC diagnostic pop
</code>```

You can then also predefine constants like this (e.g. locally or in a namespace):

```<code>Exactly<Complex> exactlyOne(Complex(1.0, 0.0));
</code>```

And add a "maker" function so that you don't have to repeat the type name such as Complex:

```<code>template<typename T>
Exactly<T> exactly(T const& value)
{
    return Exactly<T>(value);
}
</code>```

operator != left as an exercise to the reader.

Minor update: If you want to allow operator == without Exactly, but with a warning, then you need to add another overload operator ==(Complex const& a, Complex const& b) with the attribute mentioned by Massimiliano Janes. Seems unnecessary though.

Demo

Body:
Using GCC 4.8.*, when the warning -Wfloat-equal is activated, the compiler warns about strict comparisons between floting point number, like in the following example:

double x = 3.14159;
double y = 1.11111;
if(x == y) // <-- this induces a warning
{ /* ... */ }

Now, imagine I want a class containing double variables and defining the equality operator:

class Complex // (it's only an example)
{
  private:
    double re;
    double im;
  public:
    bool operator == (Complex const& z) const;
};
bool Complex::operator == (Complex const& z) const
{
  return (this->re == z.re) && (this->im == z.im);
}

This does exactly what I expect. Of course, it induces a warning when I compile the class. In order to avoid it (because I understand the warning, thanks to the compiler, but I want to do that, and I don't want to continue to see the warning), I inform the compiler by this way:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
bool Complex::operator == (Complex const& z) const
{
  return (this->re == z.re) && (this->im == z.im);
}
#pragma GCC diagnostic pop

Okay, I don't have the warning when I compile my Complex.cpp file. But it's still dangerous to use the operator == on complex numbers, exaclty like it's dangerous to use operator == on double numbers (it's the reason for the existence of the option -Wfloat-equal). Then, my question:

Is it possible to have a GCC warning (activated by -Wfloat-equal) where the operator == on complex numbers is used ? It's not the existence of the operator I want to warn, but the usage.

Note: I defined the symmetric operator as a class member, but I'm open to have a class function bool equals(...) const called by a bool operator == (Complex const&,Complex const&) if it can simplify my expected behavior.

Note: I don't use C++11 for compatibility reasons.

Body:
How about using an Exactly wrapper type that expresses the intent clearly?

template<typename T>
struct Exactly : T
{
    explicit Exactly(T const& value) : T(value) {}
};

class Complex
{
    double re;
    double im;

public:
    Complex(double re, double im) : re(re), im(im) {}

    // Non-members require either friend access or public getters.
    double real() const { return re; }
    double imag() const { return im; }
};

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
bool operator == (Complex const& a, Exactly<Complex> const& b)
{
    return (a.real() == b.real()) && (a.imag() == b.imag());
}
// two more overloads for completeness
bool operator == (Exactly<Complex> const& a, Complex const& b)
{
    return (a.real() == b.real()) && (a.imag() == b.imag());
}
bool operator == (Exactly<Complex> const& a, Exactly<Complex> const& b)
{
    return (a.real() == b.real()) && (a.imag() == b.imag());
}
#pragma GCC diagnostic pop

You can then also predefine constants like this (e.g. locally or in a namespace):

Exactly<Complex> exactlyOne(Complex(1.0, 0.0));

And add a "maker" function so that you don't have to repeat the type name such as Complex:

template<typename T>
Exactly<T> exactly(T const& value)
{
    return Exactly<T>(value);
}

operator != left as an exercise to the reader.

Minor update: If you want to allow operator == without Exactly, but with a warning, then you need to add another overload operator ==(Complex const& a, Complex const& b) with the attribute mentioned by Massimiliano Janes. Seems unnecessary though.

Demo


问:
RSA with ISO/IEC 9796-2 scheme 2 in PKCS11
Is there a way to create RSA signature with ISO-9796 scheme 2 using PKCS11 interface? I know there is proper mechanism listed among definitions (or at least I think so):
CKM_RSA_9796  0x00000002

But according to ISO Descrption schema 2 requires parameters (i.e salt and trailer), which seems to be conflicting with

6.1.11    ISO/IEC 9796 RSA The ISO/IEC 9796 RSA mechanism, denoted CKM_RSA_9796, is a mechanism for single-part signatures and
  verification with and without message recovery based on the RSA
  public-key cryptosystem and the block formats defined in ISO/IEC 9796
  and its annex A.

This mechanism does not have a parameter.

I tried to create such signature with (PKCS11 exception is thrown) and without parameters (does not seem to be valid) using PKCS11Interop C# class and HSM simulator. Any help would be appreciated.

EDIT

Code I'm using:

```<code>using (Session session = slot[slotIndex].OpenSession(SessionType.ReadOnly))
                    {
                        session.Login(CKU.CKU_USER, callback.GetPassword());

                        List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
                        objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));

                        var prm = new Net.Pkcs11Interop.HighLevelAPI.MechanismParams.CkRsaPkcsPssParams(Convert.ToUInt32(CKM.CKM_SHA256), Convert.ToUInt32(CKG.CKG_MGF1_SHA256),Convert.ToUInt32(20));
                        Mechanism mchanism = new Mechanism(CKM.CKM_RSA_9796,prm);
                        List<ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes);
                        if (foundObjects != null && foundObjects.Count > 0)
                        {
                            signature = session.SignRecover(mchanism, foundObjects[0], result);
                        }
                        else
                        {
                            throw new DSException("There was a problem with reading private key from token");
                        }
                        session.Logout();
                    }
</code>```

Exception I'm receiving:

Method C_SignRecoverInit returned CKR_MECHANISM_PARAM_INVALID

Thanks.

答:
Yeah, so I finally figured this out, or at least I think so. Turns out that CKM_RSA_9796 mechanism implements old, not very safe RSA_9796 sign mechanism, which requires message to have length < k/2, where k is private key length. So this was something different that I was looking for. According to fgrieu user commenting on StackExchange:

https://crypto.stackexchange.com/questions/24294/how-do-signrecover-and-verifyrecover-work.

there is NO IMPLEMENTATION of ISO/IEC 9796-2 scheme 2 in PKCS11 at all. I was able to create signature by breaking this process into 2 sub-processes. First one creates MessageRepresentative (as presented in http://www.sarm.am/docs/ISO_IEC_9796-2_2002(E)-Character_PDF_document.pdf) and second one - creating signature using CKM.CKM_RSA_X_509 in PKCS#11 implementation (using MessageRepresentative as input). Hope this will help someone in future.

Thanks for everyone who commented my question.

Body:
Is there a way to create RSA signature with ISO-9796 scheme 2 using PKCS11 interface? I know there is proper mechanism listed among definitions (or at least I think so):
CKM_RSA_9796  0x00000002

But according to ISO Descrption schema 2 requires parameters (i.e salt and trailer), which seems to be conflicting with

6.1.11    ISO/IEC 9796 RSA The ISO/IEC 9796 RSA mechanism, denoted CKM_RSA_9796, is a mechanism for single-part signatures and
  verification with and without message recovery based on the RSA
  public-key cryptosystem and the block formats defined in ISO/IEC 9796
  and its annex A.

This mechanism does not have a parameter.

I tried to create such signature with (PKCS11 exception is thrown) and without parameters (does not seem to be valid) using PKCS11Interop C# class and HSM simulator. Any help would be appreciated.

EDIT

Code I'm using:

using (Session session = slot[slotIndex].OpenSession(SessionType.ReadOnly))
                    {
                        session.Login(CKU.CKU_USER, callback.GetPassword());

                        List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
                        objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));

                        var prm = new Net.Pkcs11Interop.HighLevelAPI.MechanismParams.CkRsaPkcsPssParams(Convert.ToUInt32(CKM.CKM_SHA256), Convert.ToUInt32(CKG.CKG_MGF1_SHA256),Convert.ToUInt32(20));
                        Mechanism mchanism = new Mechanism(CKM.CKM_RSA_9796,prm);
                        List<ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes);
                        if (foundObjects != null && foundObjects.Count > 0)
                        {
                            signature = session.SignRecover(mchanism, foundObjects[0], result);
                        }
                        else
                        {
                            throw new DSException("There was a problem with reading private key from token");
                        }
                        session.Logout();
                    }

Exception I'm receiving:

Method C_SignRecoverInit returned CKR_MECHANISM_PARAM_INVALID

Thanks.


问:
Precise conditions for an optimistic locking failure with Core Data
My understanding from the Core Data Programming Guide is that when a context is saved, for each managed object of that context the Core Data framework compares a snapshot of its values taken when the object was last fetched against the now-current corresponding values in the persistent store.  With the default NSErrorMergePolicy, an attempt to save the context will throw an error if the version numbers associated with these snapshots are different.

However, I am observing that given a background context that has made changes, the context gets a save conflict even if in the meantime another context (the main UI context) has also made changes to one of its managed objects but has not made a call to save those changes to the persistent store.

My question is: while I recognize the obviousness of having writes to both contexts concurrently - how is the background context able to trigger a save conflict when this context is the first to save? The main context has merely written to one of its managed objects - with at most a possible call to processPendingChanges - but no save.

Other details

I should note both contexts in the example above share the same persistent store coordinator. I am wondering if there is some communication at this level I'm not considering. However, I thought that the point is that contexts are 'isolated scratch-pads' that act independently until a call to save commits/merges the changes to the store as a transaction. I also recognise I can solve the problem by changing the merge policy, but it's the lack of that isolation that concerns me. I am also observing objects-did-change and context-did-save notifications on both contexts so I don't think there is a spurious save that I'm not aware of. But what else have I missed?

Finally, It's hard to show the code as the problem is inherently structure / timing related. But any other suggestions to discover exactly when the UI context is touching the PSC/store to increment the version numbering - would be much appreciated, too.

答:
I found the problem, which might be a useful gotcha should anyone else observe similar behaviour.

I believe my assumptions in the question are indeed correct, and on a first pass it may not be immediately obvious that everything runs as expected. However, on a later pass, in my case it was possible that the main UI has made a call to save its context by now, while managed objects in the background context remain at the same state since their first (successful) call to save.  It was this second call to save the background context that threw the save conflict.

An immediate solution to confirm such a problem is to call refreshAllObjects() or refresh(_:mergeChanges:) somewhere near the start a processing block that may have stale objects. This will make sure managed objects in the context are updated with the latest changes from the persistent store, and so provided no saves occur during this block a later call to save should see no conflicts.

I should mention that I don't wish to say this is a good approach to such problem - I just wanted to understand what was happening.


问:
SLF4J varargs interprets first string as marker
When using

```<code>log.trace("with name {}, duration {}, repetitions {}", name, duration, repetitions);
</code>```

SLF4J complains as follows

[javac] sourcefile.java:105: error: incompatible types: String cannot be converted to Marker

  [javac]   log.trace("with name {}, duration {}, repetitions {}",

  [javac]             ^

  [javac] Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output

  [javac] 1 error

Using

```<code>log.trace("with name {}, duration {}, repetitions {}",
      new Object[]{name, duration, repetitions});
</code>```

solves the problem, yet seems kludgey. (Especially since the API allows varargs).

Going by this answer seems to say that upgrading to SLF4J 1.7 would solve the problem, yet the android-slf4j is at 1.6.1.

Is there a way to use the varargs constructor in SLF4J for Android? Is there an alternative?

答:
Seems like a bug in the API.

Varargs are used, but for the Marker methods there are also defined methods with 1, 2 and 3 arguments.

```<code>log.trace(Marker, Object...)
log.trace(Marker, Object)
log.trace(Marker, Object, Object)
log.trace(Marker, **Object**, Object, Object)
</code>```

However the String APIs, only have varargs and 1 and 2 arg methods.

```<code>log.trace(String, Object...)
log.trace(String, Object)
log.trace(String, Object, Object)
</code>```

For me Varargs do work with 1, 2, or 4, arguments.

Its only a problem with 3 arguments.

Its fixed in 1.7 by changing the highlighted Object to a String.

Body:
When using

log.trace("with name {}, duration {}, repetitions {}", name, duration, repetitions);

SLF4J complains as follows

[javac] sourcefile.java:105: error: incompatible types: String cannot be converted to Marker

  [javac]   log.trace("with name {}, duration {}, repetitions {}",

  [javac]             ^

  [javac] Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output

  [javac] 1 error

Using

log.trace("with name {}, duration {}, repetitions {}",
      new Object[]{name, duration, repetitions});

solves the problem, yet seems kludgey. (Especially since the API allows varargs).

Going by this answer seems to say that upgrading to SLF4J 1.7 would solve the problem, yet the android-slf4j is at 1.6.1.

Is there a way to use the varargs constructor in SLF4J for Android? Is there an alternative?

Body:
Seems like a bug in the API.

Varargs are used, but for the Marker methods there are also defined methods with 1, 2 and 3 arguments.

log.trace(Marker, Object...)
log.trace(Marker, Object)
log.trace(Marker, Object, Object)
log.trace(Marker, **Object**, Object, Object)

However the String APIs, only have varargs and 1 and 2 arg methods.

log.trace(String, Object...)
log.trace(String, Object)
log.trace(String, Object, Object)

For me Varargs do work with 1, 2, or 4, arguments.

Its only a problem with 3 arguments.

Its fixed in 1.7 by changing the highlighted Object to a String.


问:
Webkit Transition isnt working in Edge browser
Afternoon, is there a reason as to why the css attribute -webkit-transition: all .8s ease-in-out;isn't doing what it's supposed to?

Browser is MS Edge, my code is below.

Thanks

Todd

.callToActionDefault:hover {
    color: white;
    text-decoration: none;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(20%, #0d89ca), color-stop(100%, #0d89ca));
    background: -webkit-linear-gradient(top, #0d89ca 20%, #0d89ca 100%);
    background: linear-gradient(to bottom, #0d89ca 20%, #0d89ca 100%);
}

.callToActionDefault {
    padding: 8px;
    font-size: 15px;
    margin-top: 20px;
    letter-spacing: 0.5px;
    color: white;
    width: 60%;
    display: block;
    position: relative;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(20%, #219cdd), color-stop(100%, #0d89ca));
    background: -webkit-linear-gradient(top, #219cdd 20%, #0d89ca 100%);
    background: linear-gradient(to bottom, #219cdd 20%, #0d89ca 100%);
    bottom: 0;
    font-weight: 700;
    -webkit-transition: all .8s ease-in-out;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>This is a button</code>```

答:
It doesn't work, because Edge is not a Webkit-based browser. The -webkit- prefix is a feature of old Webkit-based browsers such as Google Chrome.

In order to achieve maximum compatibility with older and newer browsers use the following code:

```<code>-webkit-transition: all .8s ease-in-out;   // Old Chrome, Safari
-moz-transition: all .8s ease-in-out;      // Old Firefox
-ms-transition: all .8s ease-in-out;       // Internet Explorer
-o-transition: all .8s ease-in-out;        // Old Opera
transition: all .8s ease-in-out;           // Newer Browsers
</code>```

Body:
Afternoon, is there a reason as to why the css attribute -webkit-transition: all .8s ease-in-out;isn't doing what it's supposed to?

Browser is MS Edge, my code is below.

Thanks

Todd

.callToActionDefault:hover {
    color: white;
    text-decoration: none;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(20%, #0d89ca), color-stop(100%, #0d89ca));
    background: -webkit-linear-gradient(top, #0d89ca 20%, #0d89ca 100%);
    background: linear-gradient(to bottom, #0d89ca 20%, #0d89ca 100%);
}

.callToActionDefault {
    padding: 8px;
    font-size: 15px;
    margin-top: 20px;
    letter-spacing: 0.5px;
    color: white;
    width: 60%;
    display: block;
    position: relative;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(20%, #219cdd), color-stop(100%, #0d89ca));
    background: -webkit-linear-gradient(top, #219cdd 20%, #0d89ca 100%);
    background: linear-gradient(to bottom, #219cdd 20%, #0d89ca 100%);
    bottom: 0;
    font-weight: 700;
    -webkit-transition: all .8s ease-in-out;
}

This is a button

Body:
It doesn't work, because Edge is not a Webkit-based browser. The -webkit- prefix is a feature of old Webkit-based browsers such as Google Chrome.

In order to achieve maximum compatibility with older and newer browsers use the following code:

-webkit-transition: all .8s ease-in-out;   // Old Chrome, Safari
-moz-transition: all .8s ease-in-out;      // Old Firefox
-ms-transition: all .8s ease-in-out;       // Internet Explorer
-o-transition: all .8s ease-in-out;        // Old Opera
transition: all .8s ease-in-out;           // Newer Browsers


问:
Python comparing two lists and filtering items
I would like to do some word filtering (extracting only items in 'keyword' list that exist in 'whitelist').

Here is my code so far:

```<code>whitelist = ['Cat', 'Dog', 'Cow']
keyword = ['Cat, Cow, Horse', 'Bird, Whale, Dog', 'Pig, Chicken', 'Tiger, Cat']
keyword_filter = []

for word in whitelist:
    for i in range(len(keyword)):
        if word in keyword[i]:
            keyword_filter.append(word)
        else: pass
</code>```

I want to remove every word except for 'Cat', 'Dog', and 'Cow' (which are in the
'whitelist') so that the result ('keyword_filter' list) will look like this:

```<code>['Cat, Cow', 'Dog', '', 'Cat']
</code>```

However, I got the result something like this:

```<code>['Cat', 'Cat', 'Dog', 'Cow']
</code>```

I would sincerely appreciate if you can give some advice.

答:
You need to split the strings in the list and check if word in the split is contained in the whitelist. Then rejoin all words in the whitelist after filtering:

```<code>whitelist = {'Cat', 'Dog', 'Cow'}
filtered = []
for words in keyword:
    filtered.append(', '.join(w for w in words.split(', ') if w in whitelist))

print(filtered)
# ['Cat, Cow', 'Dog', '', 'Cat']
</code>```

Better to make whitelist a set to improve the performance for lookup of each word.

You could also use re.findall to find all parts of each word matching strings contained in the whitelist, and then rejoin after finding the matches:

```<code>import re

pattern = re.compile(',?\s?Cat|,?\s?Dog|,?\s?Cow')
filtered = [''.join(pattern.findall(words))) for words in keyword]
</code>```

Body:
I would like to do some word filtering (extracting only items in 'keyword' list that exist in 'whitelist').

Here is my code so far:

whitelist = ['Cat', 'Dog', 'Cow']
keyword = ['Cat, Cow, Horse', 'Bird, Whale, Dog', 'Pig, Chicken', 'Tiger, Cat']
keyword_filter = []

for word in whitelist:
    for i in range(len(keyword)):
        if word in keyword[i]:
            keyword_filter.append(word)
        else: pass

I want to remove every word except for 'Cat', 'Dog', and 'Cow' (which are in the
'whitelist') so that the result ('keyword_filter' list) will look like this:

['Cat, Cow', 'Dog', '', 'Cat']

However, I got the result something like this:

['Cat', 'Cat', 'Dog', 'Cow']

I would sincerely appreciate if you can give some advice.

Body:
You need to split the strings in the list and check if word in the split is contained in the whitelist. Then rejoin all words in the whitelist after filtering:

whitelist = {'Cat', 'Dog', 'Cow'}
filtered = []
for words in keyword:
    filtered.append(', '.join(w for w in words.split(', ') if w in whitelist))

print(filtered)
# ['Cat, Cow', 'Dog', '', 'Cat']

Better to make whitelist a set to improve the performance for lookup of each word.

You could also use re.findall to find all parts of each word matching strings contained in the whitelist, and then rejoin after finding the matches:

import re

pattern = re.compile(',?\s?Cat|,?\s?Dog|,?\s?Cow')
filtered = [''.join(pattern.findall(words))) for words in keyword]


问:
Having with SMTP error in rails application
I am having the following error in rails while using the normal smtp:

Net::SMTPFatalError (554 Message rejected: Email address is not verified. The following identities failed the check in region US-EAST:
  ):

Is their a way in rails 2 to bypass all smtp errors so that the application does not halt with a blank page?

答:
Inside app/config/production.rb file:</p>

```<code># Disable delivery errors, bad email addresses will be ignored

config.action_mailer.raise_delivery_errors = false
</code>```

Body:
Inside app/config/production.rb file:

# Disable delivery errors, bad email addresses will be ignored

config.action_mailer.raise_delivery_errors = false


问:
Spring hibernate behaviour with multiple threads
I have a requirement wherein a lot of database operations are required. Basically it is a bulk upload which supports 100 000 data operations. I divide the file in chunks and supply that to multiple threads. What i want to achieve is that db operation should be successful only if all threads succeed else it should rollback entire operation.

I have read a lot of stuff where people insist not to use spring hibernate with multiple threads. Is this possible using spring SessionFactory and if yes what are important stuff that needs to be kept in mind.

答:
Finally was able to solve this. Sharing code snippet that might help others

This can be achieved by keeping transaction at thread level. However u would require a shared object between all those threads. This shared object will keep a track of status of all this threads and notify them if either fails. If failure notification is recieved by this threads they themselves can throw an exception and their transaction will be rollbacked.

Example code Code in individual threads

```<code>    @Transactional(rollbackFor = Exception.class)
public void saveData(Product product, ProductStatusObject productStatusObject) throws Exception {
    productDao.persist(product);
    if(product.getId() == 5) {
        productStatusObject.updateCounter(false);
    } else {
        productStatusObject.updateCounter(true);
    }
    if(!productStatusObject.getStatus()) {
        throw new Exception();
    }
}
</code>```

Code in shared class

```<code>private final int totalThreads;

private int executedThreads = 0;
private Boolean finalStatus = true;

public ProductStatusObject(int totalThreads) {
    this.totalThreads = totalThreads;
}

public synchronized void updateCounter(Boolean threadStatus) throws InterruptedException {
    executedThreads ++;
    if(!threadStatus) {
        this.finalStatus = false;
    }
    if(totalThreads == executedThreads) {
        notifyAll();
    } else {
        wait();
    }

}

public synchronized Boolean getStatus() {
    return finalStatus;
}
</code>```

Here the failure condition is if any of thread is saving data with id 5 all threads will rollback their code. Else all will succeed

Body:
Finally was able to solve this. Sharing code snippet that might help others

This can be achieved by keeping transaction at thread level. However u would require a shared object between all those threads. This shared object will keep a track of status of all this threads and notify them if either fails. If failure notification is recieved by this threads they themselves can throw an exception and their transaction will be rollbacked.

Example code Code in individual threads

    @Transactional(rollbackFor = Exception.class)
public void saveData(Product product, ProductStatusObject productStatusObject) throws Exception {
    productDao.persist(product);
    if(product.getId() == 5) {
        productStatusObject.updateCounter(false);
    } else {
        productStatusObject.updateCounter(true);
    }
    if(!productStatusObject.getStatus()) {
        throw new Exception();
    }
}

Code in shared class

private final int totalThreads;

private int executedThreads = 0;
private Boolean finalStatus = true;

public ProductStatusObject(int totalThreads) {
    this.totalThreads = totalThreads;
}

public synchronized void updateCounter(Boolean threadStatus) throws InterruptedException {
    executedThreads ++;
    if(!threadStatus) {
        this.finalStatus = false;
    }
    if(totalThreads == executedThreads) {
        notifyAll();
    } else {
        wait();
    }

}

public synchronized Boolean getStatus() {
    return finalStatus;
}

Here the failure condition is if any of thread is saving data with id 5 all threads will rollback their code. Else all will succeed


问:
Trouble formatting images in my CSS
community!
I am having trouble getting the formatting down for a few images I have.

HTML

```<code><footer>
    <section class="socialmedia">
        <a href=""><img src="facebook.png" class="sm"></a>
        <a href=""><img src="twitter.png" class="sm"></a>
        <a href=""><img src="instagram.png" class="sm"></a>
    </section>
</footer>
</code>```

CSS

```<code>.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}
</code>```

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

答:
What makes it horizontal is display:block

you can use the following code.

the "text-align" will locate the elements in the center.

for spacing use margin or padding.

```<code>.socialmedia {
    width: 100%;
    text-align: center;
}

.sm {
    height: 50px;
    width: 50px;
    margin: 10px;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}
</code>```

Title: Trouble formatting images in my CSS

Body:
community!
I am having trouble getting the formatting down for a few images I have.

HTML

CSS

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

Body:
What makes it horizontal is display:block

you can use the following code.

the "text-align" will locate the elements in the center.

for spacing use margin or padding.

.socialmedia {
    width: 100%;
    text-align: center;
}

.sm {
    height: 50px;
    width: 50px;
    margin: 10px;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}


问:
Subprocess in C# Application pauses unexpected
I'm currently working on a service (well at this point it's still a Console Application, as this is a lot easier to debug). The basic task of this service is to watch a folder for new *.tif Files. As soon as the Application found a .TIF file in the folder it starts another Application with the following code:

```<code>ProcessStartInfo command = new ProcessStartInfo(commandPath, commandParams);
command.RedirectStandardOutput=true;
command.UseShellExecute=false;
command.CreateNoWindow=true;

Process process = new Process();
process.startInfo = command;
process.Start();
process.WaitForExit();
</code>```

This console application then uses IrfanView to split the Multipage-TIF into multiple singlepage-TIF (I use basically the same code as above to do this). After that, I check for a Barcode on the Scanned image (with zxing library). The found Barcode is then compared to the Oracle Database. Afterwards the file is converted to PDF and moved to a specific location, based on the found Barcode.

This console Application works perfectly, when I start it myself, but as soon as the "service" starts it, it will pause after a while and don't do anything until I close the "service"-console application. Then it finishes normally.

What could be the problem?

I tried to disable the Oracle, DB check and it worked. Afterwards I disabled my Logging class and it worked too. So my guess is, that I somehow use too much ressources or something like that. But where to start?

EDIT:
Some additional information. I just debugged the process, as VS is able to attach to a process to debug. The command that hangs is Console.WriteLine (called from within the Console application which is called by my "service" console. Any way that a console in a subprocess can only have a certain amount of lines/chars? can a console-output stream have a deadlock or what is this?

答:
Ok, I found the answer to my problem. I specified that I want to RedirectStandardOutput on my ProcessStartInfo object. The problem is, that I only read the Output at the end of the execution of the console application, which caused a deadlock. It looks like the buffer can only hold 1024 characters (according to this post). As soon as you want to write more into that buffer, the Console.WriteLine waits. If you (like me) only read at the end of the execution of the console application, this buffer will never be cleared, so you got a really nice deadlock ;-)

Hope this helps some other people! cheers

ContentLicense: CC BY-SA 2.5

Body:
I'm currently working on a service (well at this point it's still a Console Application, as this is a lot easier to debug). The basic task of this service is to watch a folder for new *.tif Files. As soon as the Application found a .TIF file in the folder it starts another Application with the following code:

ProcessStartInfo command = new ProcessStartInfo(commandPath, commandParams);
command.RedirectStandardOutput=true;
command.UseShellExecute=false;
command.CreateNoWindow=true;

Process process = new Process();
process.startInfo = command;
process.Start();
process.WaitForExit();

This console application then uses IrfanView to split the Multipage-TIF into multiple singlepage-TIF (I use basically the same code as above to do this). After that, I check for a Barcode on the Scanned image (with zxing library). The found Barcode is then compared to the Oracle Database. Afterwards the file is converted to PDF and moved to a specific location, based on the found Barcode.

This console Application works perfectly, when I start it myself, but as soon as the "service" starts it, it will pause after a while and don't do anything until I close the "service"-console application. Then it finishes normally.

What could be the problem?

I tried to disable the Oracle, DB check and it worked. Afterwards I disabled my Logging class and it worked too. So my guess is, that I somehow use too much ressources or something like that. But where to start?

EDIT:
Some additional information. I just debugged the process, as VS is able to attach to a process to debug. The command that hangs is Console.WriteLine (called from within the Console application which is called by my "service" console. Any way that a console in a subprocess can only have a certain amount of lines/chars? can a console-output stream have a deadlock or what is this?


问:
Php session data wipes after two page redirections
I am making a payment processing system, using a PayPal API, and the issue is, that when I redirect the user to PayPal, I store a 'paypal_hash' inside the session, after information being entered into the PayPal system, the user is then redirected to the webpage, and the 'paypal_hash' is no longer there.
process_payment.php:

```<code>session_start();
$payment->create($api);

//Generate hash
$hash = md5($payment->getId()); // Will encrypt better at a later point
$_SESSION['paypal_hash'] = $hash;

//Prepare and execute transacting storage
$store = $db->prepare("
    INSERT INTO transactions_paypal (user_id, payment_id, hash, complete) VALUES (:user_id, :payment_id, :hash, 0)
    ");

$store->execute([
    'user_id' => $_SESSION['user_id'],
    'payment_id' => $payment->getId(),
    'hash' => $hash
]);
header('Location: ' . $paypal_url); // the url where the user pays via a paypal.com site
</code>```

After this code is executed, the user is redirected to pay.php:

```<code>session_start();
var_dump($_SESSION); // This returns an empty array
$paymentId = $db->prepare("
    SELECT payment_id
    FROM transactions_paypal
    WHERE hash = :hash
    ");
$paymentId->execute([
    'hash' => $_SESSION['paypal_hash']
]);
</code>```

Hash is stored properly in the database but is not kept in the session after being redirected back from PayPal.

答: Okay, shortly after some helpful comments, I found out that some files had put https:// and some files https://www. - Changing it to the same solved the issue.</p>

Body:
I am making a payment processing system, using a PayPal API, and the issue is, that when I redirect the user to PayPal, I store a 'paypal_hash' inside the session, after information being entered into the PayPal system, the user is then redirected to the webpage, and the 'paypal_hash' is no longer there.
process_payment.php:

session_start();
$payment->create($api);

//Generate hash
$hash = md5($payment->getId()); // Will encrypt better at a later point
$_SESSION['paypal_hash'] = $hash;

//Prepare and execute transacting storage
$store = $db->prepare("
    INSERT INTO transactions_paypal (user_id, payment_id, hash, complete) VALUES (:user_id, :payment_id, :hash, 0)
    ");

$store->execute([
    'user_id' => $_SESSION['user_id'],
    'payment_id' => $payment->getId(),
    'hash' => $hash
]);
header('Location: ' . $paypal_url); // the url where the user pays via a paypal.com site

After this code is executed, the user is redirected to pay.php:

session_start();
var_dump($_SESSION); // This returns an empty array
$paymentId = $db->prepare("
    SELECT payment_id
    FROM transactions_paypal
    WHERE hash = :hash
    ");
$paymentId->execute([
    'hash' => $_SESSION['paypal_hash']
]);

Hash is stored properly in the database but is not kept in the session after being redirected back from PayPal.


问:
How to convert images to pdf using PHP?
Can anyone have an idea how to convert images to pdf using PHP?

Any response will be appreciated.

Thanks...

答:
You may use, MPDF and Normal PHP upload function to convert image into pdf.
Just follow the below steps.
Create a form to upload the file field "jpgtoconvert"

```<code><?php
   $mpdf = new mPDF();
   $file = $_FILES['jpgtoconvert']['tmp_name'];
   $size =  getimagesize ( $file );
   $width = $size[0];
   $height = $size[1];
   $mpdf->WriteHTML('');
   $mpdf->Image($file,60,50,$width,$height,'jpg','',true, true);
   $mpdf->Output($filename);
?>
</code>```

This function should output the pdf on the browser.

Title: How to convert images to pdf using PHP?

Body:
You may use, MPDF and Normal PHP upload function to convert image into pdf.
Just follow the below steps.
Create a form to upload the file field "jpgtoconvert"

<?php
   $mpdf = new mPDF();
   $file = $_FILES['jpgtoconvert']['tmp_name'];
   $size =  getimagesize ( $file );
   $width = $size[0];
   $height = $size[1];
   $mpdf->WriteHTML('');
   $mpdf->Image($file,60,50,$width,$height,'jpg','',true, true);
   $mpdf->Output($filename);
?>

This function should output the pdf on the browser.


问:
How to convert utf8 byte array to a string of given length
Let's say I have an array of bytes:

```<code>var myArr = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87 };
</code>```

So it has 6 elements while it corresponds to utf8 abąć which has 4 letters. Typically you do

```<code>Encoding.UTF8.GetString(myArr);
</code>```

to convert it to a string. But lets assume that myArr is actually bigger (there are more bytes at the end) but I do know (a priori to conversion) that I only want the first 4 letters. How can efficiently convert this array to the string? Also it would be preferable to have the index of the last byte in myArr array (corresponding to the end of the converted string).

Example:

```<code>// 3 more bytes at the end of formerly defined myArr
var myArr = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87, 0x01, 0x02, 0x03 };
var str = MyConvert(myArr, 4); // read 4 utf8 letters
// str is "abąć"
// possibly I want to know that MyConvert stoped at the index 6 in myArr
</code>```

The resulting string str object should have str.Length == 4.

答:
It looks like Decoder has your back here, in particular with the somewhat huge Convert method. I think you'd want:

```<code>var decoder = Encoding.UTF8.GetDecoder();
var chars = new char[4];
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length,
    true, out int bytesUsed, out int charsUsed, out bool completed);
</code>```

Complete sample using the data in your question:

```<code>using System;
using System.Text;

public class Test
{
    static void Main()
    {
        var bytes = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87, 0x01, 0x02, 0x03 };
        var decoder = Encoding.UTF8.GetDecoder();
        var chars = new char[4];
        decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length,
            true, out int bytesUsed, out int charsUsed, out bool completed);
        Console.WriteLine($"Completed: {completed}");
        Console.WriteLine($"Bytes used: {bytesUsed}");
        Console.WriteLine($"Chars used: {charsUsed}");
        Console.WriteLine($"Text: {new string(chars, 0, charsUsed)}");
    }
}
</code>```

Body:
Let's say I have an array of bytes:

var myArr = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87 };

So it has 6 elements while it corresponds to utf8 abąć which has 4 letters. Typically you do

Encoding.UTF8.GetString(myArr);

to convert it to a string. But lets assume that myArr is actually bigger (there are more bytes at the end) but I do know (a priori to conversion) that I only want the first 4 letters. How can efficiently convert this array to the string? Also it would be preferable to have the index of the last byte in myArr array (corresponding to the end of the converted string).

Example:

// 3 more bytes at the end of formerly defined myArr
var myArr = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87, 0x01, 0x02, 0x03 };
var str = MyConvert(myArr, 4); // read 4 utf8 letters
// str is "abąć"
// possibly I want to know that MyConvert stoped at the index 6 in myArr

The resulting string str object should have str.Length == 4.

Body:
It looks like Decoder has your back here, in particular with the somewhat huge Convert method. I think you'd want:

var decoder = Encoding.UTF8.GetDecoder();
var chars = new char[4];
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length,
    true, out int bytesUsed, out int charsUsed, out bool completed);

Complete sample using the data in your question:

using System;
using System.Text;

public class Test
{
    static void Main()
    {
        var bytes = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87, 0x01, 0x02, 0x03 };
        var decoder = Encoding.UTF8.GetDecoder();
        var chars = new char[4];
        decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length,
            true, out int bytesUsed, out int charsUsed, out bool completed);
        Console.WriteLine($"Completed: {completed}");
        Console.WriteLine($"Bytes used: {bytesUsed}");
        Console.WriteLine($"Chars used: {charsUsed}");
        Console.WriteLine($"Text: {new string(chars, 0, charsUsed)}");
    }
}


问:
How do I access Fauxton on the Google AppEngine platform?
I am creating an offline-first app on Google App Engine, with PouchDB as my local DB, and CouchDB as my remote DB. I have enabled CouchDB on Google AppEngine, and tried to go to the following URL:

```<code>https://[my-app-id].appspot.com:5984/_utils/
</code>```

When I do that, I get the following:

```<code>This site can’t be reached
The connection was reset.
Try:
Checking the connection
Checking the proxy and the firewall
Running Windows Network Diagnostics
ERR_CONNECTION_RESET
</code>```

So I tried enabling https access in the firewall settings.

```<code>**Firewalls**
[ ] Allow HTTP traffic
[Y] Allow HTTPS traffic
</code>```

Still getting the error above.

I searched the documentation but cannot find anything helpful about how to access Fauxton (or Futon) on Google AppEngine. (The instructions only tell you how to access Fauxton on your local machine.)

I have generated a private and public key and logged in to the server via command line.

I have also followed the instructions about configuring the firewall to allow remote access, and have given it to my PC only.

None of this has enabled me to access https://[my-app-id].appspot.com:5984/_utils/

How do I access Fauxton on the Google AppEngine platform?

Update: according to the development tools in my browser, my PouchDB application has successfully created a database to sync to, but it isn't on the server:

app.yaml file

```<code>application: [app-name]
version: 4
runtime: python27
api_version: 1
threadsafe: false

handlers:

- url: /
  script: main.py

- url: /(favicon)\.ico$
  static_files: \1.ico
  upload: /(favicon)\.ico
  application_readable: true

- url: /(package)\.json$
  static_files: \1.json
  upload: /(package)\.json
  application_readable: true

  # Serve images as static resources #
- url: /(.+\.(gif|png|jpg|json|ico))$
  static_files: \1
  upload: .+\.(gif|png|jpg|json|ico)$
  application_readable: true

- url: /index.html
  static_files: index.html
  upload: index.html

- url: /licence.html
  static_files: licence.html
  upload: licence.html

- url: /privacy.html
  static_files: privacy.html
  upload: privacy.html

- url: /pouchnotes.manifest
  static_files: pouchnotes.manifest
  upload: pouchnotes.manifest

- url: /manifest.json
  static_files: manifest.json
  upload: manifest.json

  # static directories #

- url: /img
  static_dir: img

- url: /js
  static_dir: js

- url: /css
  static_dir: css

libraries:
- name: webapp2
  version: "2.5.2"
</code>```

EDIT: I posted this question in the Bitnami community forum (they provide CouchDB on Google App Engine)

答:
FWIW, one of the references in your post points to Google Compute Engine (GCE), which is an IaaS, not a PaaS like Google App Engine (GAE), you might be looking at the wrong product.

The app.yaml file indicates you are using the standard environment, which doesn't offer ways to configure a listening port. And it also doesn't allow listening sockets. From Limitations and restrictions:

Although App Engine supports sockets, there are certain limitations
  and behaviors you need to be aware of when using sockets :

You cannot create a listen socket; you can only create outbound sockets.

The GAE flexible environment might be an alternative as it drops many of the standard environment restrictions, but it's a significantly different solution (which I didn't use yet). The remainder of the answer assumes the flexible environment and it's based solely on the documentation.

Not 100% certain, but you might need to teach your app to listen to port 8080 instead. From Listen to port 8080:

The App Engine front end will route incoming requests to the
  appropriate module on port 8080. You must be sure that your
  application code is listening on 8080.

Unless you can use the forwarded ports network config (again, not 100% certain, I didn't use flex env). From Port forwarding:

Port forwarding allows for direct connections to the Docker container
  on your instances. This traffic can travel over any protocol. Port
  forwarding is intended to help with situations where you might need to
  attach a debugger or profiler.

By default, incoming traffic from outside your network is not allowed
  through the Google Cloud Platform firewalls. After you have
  specified port forwarding in your app.yaml file, you must add a
  firewall rule that allows traffic from the ports you want opened.

You can specify a firewall rule in the Networking Firewall Rules page
  in the Google Cloud Platform Console or using gcloud
  commands.

For example, if you want to forward TCP traffic from port 2222:

Modify the app.yaml to include:

```<code>entrypoint: gunicorn -b :$PORT -b :2222 main:app
</code>```

In the network settings of your app.yaml, include:

```<code>network:
  forwarded_ports:
   - 2222/tcp
</code>```

Specify a firewall rule in the Cloud Platform Console or using gcloud compute firewall-rules create to allow traffic from any
  source (0.0.0.0/0) and from tcp:2222.

Body:
I am creating an offline-first app on Google App Engine, with PouchDB as my local DB, and CouchDB as my remote DB. I have enabled CouchDB on Google AppEngine, and tried to go to the following URL:

https://[my-app-id].appspot.com:5984/_utils/

When I do that, I get the following:

This site can’t be reached
The connection was reset.
Try:
Checking the connection
Checking the proxy and the firewall
Running Windows Network Diagnostics
ERR_CONNECTION_RESET

So I tried enabling https access in the firewall settings.

**Firewalls**
[ ] Allow HTTP traffic
[Y] Allow HTTPS traffic

Still getting the error above.

I searched the documentation but cannot find anything helpful about how to access Fauxton (or Futon) on Google AppEngine. (The instructions only tell you how to access Fauxton on your local machine.)

I have generated a private and public key and logged in to the server via command line.

I have also followed the instructions about configuring the firewall to allow remote access, and have given it to my PC only.

None of this has enabled me to access https://[my-app-id].appspot.com:5984/_utils/

How do I access Fauxton on the Google AppEngine platform?

Update: according to the development tools in my browser, my PouchDB application has successfully created a database to sync to, but it isn't on the server:

app.yaml file

application: [app-name]
version: 4
runtime: python27
api_version: 1
threadsafe: false

handlers:

- url: /
  script: main.py

- url: /(favicon)\.ico$
  static_files: \1.ico
  upload: /(favicon)\.ico
  application_readable: true

- url: /(package)\.json$
  static_files: \1.json
  upload: /(package)\.json
  application_readable: true

  # Serve images as static resources #
- url: /(.+\.(gif|png|jpg|json|ico))$
  static_files: \1
  upload: .+\.(gif|png|jpg|json|ico)$
  application_readable: true

- url: /index.html
  static_files: index.html
  upload: index.html

- url: /licence.html
  static_files: licence.html
  upload: licence.html

- url: /privacy.html
  static_files: privacy.html
  upload: privacy.html

- url: /pouchnotes.manifest
  static_files: pouchnotes.manifest
  upload: pouchnotes.manifest

- url: /manifest.json
  static_files: manifest.json
  upload: manifest.json

  # static directories #

- url: /img
  static_dir: img

- url: /js
  static_dir: js

- url: /css
  static_dir: css

libraries:
- name: webapp2
  version: "2.5.2"

EDIT: I posted this question in the Bitnami community forum (they provide CouchDB on Google App Engine)

Body:
FWIW, one of the references in your post points to Google Compute Engine (GCE), which is an IaaS, not a PaaS like Google App Engine (GAE), you might be looking at the wrong product.

The app.yaml file indicates you are using the standard environment, which doesn't offer ways to configure a listening port. And it also doesn't allow listening sockets. From Limitations and restrictions:

Although App Engine supports sockets, there are certain limitations
  and behaviors you need to be aware of when using sockets :

You cannot create a listen socket; you can only create outbound sockets.

The GAE flexible environment might be an alternative as it drops many of the standard environment restrictions, but it's a significantly different solution (which I didn't use yet). The remainder of the answer assumes the flexible environment and it's based solely on the documentation.

Not 100% certain, but you might need to teach your app to listen to port 8080 instead. From Listen to port 8080:

The App Engine front end will route incoming requests to the
  appropriate module on port 8080. You must be sure that your
  application code is listening on 8080.

Unless you can use the forwarded ports network config (again, not 100% certain, I didn't use flex env). From Port forwarding:

Port forwarding allows for direct connections to the Docker container
  on your instances. This traffic can travel over any protocol. Port
  forwarding is intended to help with situations where you might need to
  attach a debugger or profiler.

By default, incoming traffic from outside your network is not allowed
  through the Google Cloud Platform firewalls. After you have
  specified port forwarding in your app.yaml file, you must add a
  firewall rule that allows traffic from the ports you want opened.

You can specify a firewall rule in the Networking Firewall Rules page
  in the Google Cloud Platform Console or using gcloud
  commands.

For example, if you want to forward TCP traffic from port 2222:

Modify the app.yaml to include:

entrypoint: gunicorn -b :$PORT -b :2222 main:app

In the network settings of your app.yaml, include:

network:
  forwarded_ports:
   - 2222/tcp

Specify a firewall rule in the Cloud Platform Console or using gcloud compute firewall-rules create to allow traffic from any
  source (0.0.0.0/0) and from tcp:2222.


问:
how to convert json array to json object
I am using Retrofit 2 in my project
my app get data from tow APIs api1 and api2

api1 :-

```<code>[{"id":"29867","category_id":"31","author":"admins",
    "title":"hi","abstract":"","image_name":"","created":"11","body":"hi"},
    {"id":"29866","category_id":"14","author":"admins",
    "title":"hi2","abstract":"","image_name":"img.png","created":"2017-11-16 16:02:00","body":"heloo"}]
</code>```

and api2 :-

```<code>    [{"obj":"29867","category_id":"31","obj2":"admins",
"title":"hi","abstract":"","image_name":"","created":"11","obj3":"hi"},
{"obj":"29866","category_id":"14","author":"admins",
"obj2":"hi2","abstract":"","image_name":"Img.png","created":"2017-11-16 16:02:00","obj3":"Hello"}]
</code>```

i want to make one POJO class for both APIs like

```<code>class API_class{
var list:List<api1> =null
var list2:List<pi2> =null

}

class api1{
 @SerializedName("id")
    @Expose
    var id: Int? = null
.
.
.

}

class api2{
@SerializedName("obj")
    @Expose
    var obj: Int? = null
.
.
.
}
</code>```

i try something like the above but it doesn't work for me
i want to do like this so i can use one call function
like this

```<code>    retrofit.enqueue(object: Callback<API_class> {

            override fun onResponse(call: Call<API_class>?, response: Response<API_class>?) {.
.
.
.
}
</code>```

if the api1 and api2 was object Json like this

```<code>{json:"ddd"
[.....]
}
</code>```

i will be able to do my idea but it's now impossible

答:
If you want to transform your json array to a POJO you can use Gson dependency

and test this code below :

```<code>    public static void main(String[] args) throws IOException {

    String json = "[{\"id\":\"29867\",\"category_id\":\"31\",\"author\":\"admins\",\n" +
            "    \"title\":\"hi\",\"abstract\":\"\",\"image_name\":\"\",\"created\":\"11\",\"body\":\"hi\"},\n" +
            "    {\"id\":\"29866\",\"category_id\":\"14\",\"author\":\"admins\",\n" +
            "     \"title\":\"hi2\",\"abstract\":\"\",\"image_name\":\"img.png\",\"created\":\"2017-11-16 16:02:00\",\"body\":\"heloo\"}]";

    Gson gson = new Gson();
    Example yourObj[] = gson.fromJson(json, Example[].class);

}
</code>```

The Example POJO :

```<code>   @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "id",
        "category_id",
        "author",
        "title",
        "abstract",
        "image_name",
        "created",
        "body"
})
public class Example {
    @JsonProperty("id")
    private String id;
    @JsonProperty("category_id")
    private String categoryId;
    @JsonProperty("author")
    private String author;
    @JsonProperty("title")
    private String title;
    @JsonProperty("abstract")
    private String _abstract;
    @JsonProperty("image_name")
    private String imageName;
    @JsonProperty("created")
    private String created;
    @JsonProperty("body")
    private String body;

    @JsonProperty("id")
    public String getId() {
        return id;
    }

    @JsonProperty("id")
    public void setId(String id) {
        this.id = id;
    }

    @JsonProperty("category_id")
    public String getCategoryId() {
        return categoryId;
    }

    @JsonProperty("category_id")
    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    @JsonProperty("author")
    public String getAuthor() {
        return author;
    }

    @JsonProperty("author")
    public void setAuthor(String author) {
        this.author = author;
    }

    @JsonProperty("title")
    public String getTitle() {
        return title;
    }

    @JsonProperty("title")
    public void setTitle(String title) {
        this.title = title;
    }

    @JsonProperty("abstract")
    public String getAbstract() {
        return _abstract;
    }

    @JsonProperty("abstract")
    public void setAbstract(String _abstract) {
        this._abstract = _abstract;
    }

    @JsonProperty("image_name")
    public String getImageName() {
        return imageName;
    }

    @JsonProperty("image_name")
    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    @JsonProperty("created")
    public String getCreated() {
        return created;
    }

    @JsonProperty("created")
    public void setCreated(String created) {
        this.created = created;
    }

    @JsonProperty("body")
    public String getBody() {
        return body;
    }

    @JsonProperty("body")
    public void setBody(String body) {
        this.body = body;
    }
}
</code>```

Body:
I am using Retrofit 2 in my project
my app get data from tow APIs api1 and api2

api1 :-

[{"id":"29867","category_id":"31","author":"admins",
    "title":"hi","abstract":"","image_name":"","created":"11","body":"hi"},
    {"id":"29866","category_id":"14","author":"admins",
    "title":"hi2","abstract":"","image_name":"img.png","created":"2017-11-16 16:02:00","body":"heloo"}]

and api2 :-

    [{"obj":"29867","category_id":"31","obj2":"admins",
"title":"hi","abstract":"","image_name":"","created":"11","obj3":"hi"},
{"obj":"29866","category_id":"14","author":"admins",
"obj2":"hi2","abstract":"","image_name":"Img.png","created":"2017-11-16 16:02:00","obj3":"Hello"}]

i want to make one POJO class for both APIs like

class API_class{
var list:List<api1> =null
var list2:List<pi2> =null

}

class api1{
 @SerializedName("id")
    @Expose
    var id: Int? = null
.
.
.

}

class api2{
@SerializedName("obj")
    @Expose
    var obj: Int? = null
.
.
.
}

i try something like the above but it doesn't work for me
i want to do like this so i can use one call function
like this

    retrofit.enqueue(object: Callback<API_class> {

            override fun onResponse(call: Call<API_class>?, response: Response<API_class>?) {.
.
.
.
}

if the api1 and api2 was object Json like this

{json:"ddd"
[.....]
}

i will be able to do my idea but it's now impossible

Body:
If you want to transform your json array to a POJO you can use Gson dependency

and test this code below :

    public static void main(String[] args) throws IOException {

    String json = "[{\"id\":\"29867\",\"category_id\":\"31\",\"author\":\"admins\",\n" +
            "    \"title\":\"hi\",\"abstract\":\"\",\"image_name\":\"\",\"created\":\"11\",\"body\":\"hi\"},\n" +
            "    {\"id\":\"29866\",\"category_id\":\"14\",\"author\":\"admins\",\n" +
            "     \"title\":\"hi2\",\"abstract\":\"\",\"image_name\":\"img.png\",\"created\":\"2017-11-16 16:02:00\",\"body\":\"heloo\"}]";

    Gson gson = new Gson();
    Example yourObj[] = gson.fromJson(json, Example[].class);

}

The Example POJO :

   @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "id",
        "category_id",
        "author",
        "title",
        "abstract",
        "image_name",
        "created",
        "body"
})
public class Example {
    @JsonProperty("id")
    private String id;
    @JsonProperty("category_id")
    private String categoryId;
    @JsonProperty("author")
    private String author;
    @JsonProperty("title")
    private String title;
    @JsonProperty("abstract")
    private String _abstract;
    @JsonProperty("image_name")
    private String imageName;
    @JsonProperty("created")
    private String created;
    @JsonProperty("body")
    private String body;

    @JsonProperty("id")
    public String getId() {
        return id;
    }

    @JsonProperty("id")
    public void setId(String id) {
        this.id = id;
    }

    @JsonProperty("category_id")
    public String getCategoryId() {
        return categoryId;
    }

    @JsonProperty("category_id")
    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    @JsonProperty("author")
    public String getAuthor() {
        return author;
    }

    @JsonProperty("author")
    public void setAuthor(String author) {
        this.author = author;
    }

    @JsonProperty("title")
    public String getTitle() {
        return title;
    }

    @JsonProperty("title")
    public void setTitle(String title) {
        this.title = title;
    }

    @JsonProperty("abstract")
    public String getAbstract() {
        return _abstract;
    }

    @JsonProperty("abstract")
    public void setAbstract(String _abstract) {
        this._abstract = _abstract;
    }

    @JsonProperty("image_name")
    public String getImageName() {
        return imageName;
    }

    @JsonProperty("image_name")
    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    @JsonProperty("created")
    public String getCreated() {
        return created;
    }

    @JsonProperty("created")
    public void setCreated(String created) {
        this.created = created;
    }

    @JsonProperty("body")
    public String getBody() {
        return body;
    }

    @JsonProperty("body")
    public void setBody(String body) {
        this.body = body;
    }
}


问:
How to order Service operations in alphabetical order in SoapUI project?
Soapui project has service with 100+ operations.
It's very difficult to navigate when operations are not sorted.
Is there a way to order operations in soapui ?

I'm using soapui free version, but I'm interested in solutions for SoapUI NG Pro as well.

答:
SoapUI free version: Preferences -> UI Settings -> Checked: Order Services alphabetically in tree.
Then delete and recreate the list of services from WSDL. The new list is sorted alphabetically.</p>