问:
Unhashable type 'dict' when trying to send an Elasticsearch
I keep on getting the following error in Python

Exception has occurred: TypeError unhashable type: 'dict'

on line 92

```<code>  "should": [],
  "must_not": []
</code>```

This is the query string

```<code>res = es.search(
                scroll = '2m',
                index = "logstash-*",
                body = {
{
  "aggs": {
    "2": {
      "terms": {
        "field": "src_ip.keyword",
        "size": 50,
        "order": {
          "1": "desc"
        }
      },
      "aggs": {
        "1": {
          "cardinality": {
            "field": "src_ip.keyword"
          }
        }
      }
    }
  },
  "size": 0,
  "_source": {
    "excludes": []
  },
  "stored_fields": [
    "*"
  ],
  "script_fields": {},
  "docvalue_fields": [
    {
      "field": "@timestamp",
      "format": "date_time"
    },
    {
      "field": "flow.start",
      "format": "date_time"
    },
    {
      "field": "timestamp",
      "format": "date_time"
    },
    {
      "field": "tls.notafter",
      "format": "date_time"
    },
    {
      "field": "tls.notbefore",
      "format": "date_time"
    }
  ],
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "@timestamp": {
              "gte": 1555777931992,
              "lte": 1558369931992,
              "format": "epoch_millis"
            }
          }
        }
      ],
      "filter": [
        {
          "match_all": {}
        }
      ],
      "should": [],
      "must_not": []
    }
  }
}
})
</code>```

答:
the value of body is a set ({ } without key-value is a set literal, e.g., {1,2} is a set). Inside this set you have a dictionary.

Items in a set have to be hashable, and dictionary isn't.
As the comment from @Carcigenicate says, it seems like a typo of having {{ }} instead of { } for the value of body.

Elasticsearch documentation shows that body should be a dictionary.

More about sets from python docs

Body:
I keep on getting the following error in Python

Exception has occurred: TypeError unhashable type: 'dict'

on line 92

  "should": [],
  "must_not": []

This is the query string

res = es.search(
                scroll = '2m',
                index = "logstash-*",
                body = {
{
  "aggs": {
    "2": {
      "terms": {
        "field": "src_ip.keyword",
        "size": 50,
        "order": {
          "1": "desc"
        }
      },
      "aggs": {
        "1": {
          "cardinality": {
            "field": "src_ip.keyword"
          }
        }
      }
    }
  },
  "size": 0,
  "_source": {
    "excludes": []
  },
  "stored_fields": [
    "*"
  ],
  "script_fields": {},
  "docvalue_fields": [
    {
      "field": "@timestamp",
      "format": "date_time"
    },
    {
      "field": "flow.start",
      "format": "date_time"
    },
    {
      "field": "timestamp",
      "format": "date_time"
    },
    {
      "field": "tls.notafter",
      "format": "date_time"
    },
    {
      "field": "tls.notbefore",
      "format": "date_time"
    }
  ],
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "@timestamp": {
              "gte": 1555777931992,
              "lte": 1558369931992,
              "format": "epoch_millis"
            }
          }
        }
      ],
      "filter": [
        {
          "match_all": {}
        }
      ],
      "should": [],
      "must_not": []
    }
  }
}
})


来源: stackexchange

问:
Issues with iterating over list, or set of elements in Terraform
I am trying to launch AWS instances in different subnets created across AZs using the count variable over a list of subnet IDs, it fails with  error messages with different approaches.

I have tried using element() and using [count.index], I am using TF v12.

Below is a snippet of the code, please ignore lines with #(commented).

```<code>resource "aws_instance" "workers" {
#count         =   length(data.terraform_remote_state.network.outputs.public_subnet_list)
count         = length(data.aws_subnet_ids.subnet_list.ids)
instance_type = var.worker_instance_type
ami           = var.k8_ami
key_name      = aws_key_pair.ssh_key.key_name
#subnet_id     = "${data.terraform_remote_state.network.outputs.public_subnet_list[count.index]}"
subnet_id = "${element(data.aws_subnet_ids.subnet_list.ids, count.index)}"
vpc_security_group_ids = [
aws_security_group.kubernetes.id
]
}
</code>```

Below are two error snippets.

```<code>Error: Invalid index

on k8-cluster.tf line 85, in resource "aws_instance" "workers":
85:   subnet_id = "${data.aws_subnet_ids.subnet_list.ids[count.index]}"
|----------------
| count.index is 2
| data.aws_subnet_ids.subnet_list.ids is set of string with 4 elements

This value does not have any indices.
</code>```

Another error with element():

```<code>Error: Error in function call

on k8-cluster.tf line 85, in resource "aws_instance" "workers":
85:   subnet_id = "${element(data.aws_subnet_ids.subnet_list.ids, count.index)}"
|----------------
| count.index is 3
| data.aws_subnet_ids.subnet_list.ids is set of string with 4 elements

Call to function "element" failed: cannot read elements from set of string.
</code>```

答:
You just need to change the count like this:

```<code>count = "${length(data.aws_subnet_ids.subnet_list.ids)}"
</code>```

And when you quote the variables, I suggest you do it like this:

```<code>"${var.var_name}"
</code>```

So the whole code will like below:

```<code>resource "aws_instance" "workers" {
    #count         =   "${length(data.terraform_remote_state.network.outputs.public_subnet_list)}"
    count         = "${length(data.aws_subnet_ids.subnet_list.ids)}"
    instance_type = "${var.worker_instance_type}"
    ami           = "${var.k8_ami}"
    key_name      = "${aws_key_pair.ssh_key.key_name}"
    #subnet_id     = "${data.terraform_remote_state.network.outputs.public_subnet_list[count.index]}"
    subnet_id = "${element(data.aws_subnet_ids.subnet_list.ids, count.index)}"
    vpc_security_group_ids = [
    "${aws_security_group.kubernetes.id}"
    ]
}
</code>```

You can see the example in Terraform.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to launch AWS instances in different subnets created across AZs using the count variable over a list of subnet IDs, it fails with  error messages with different approaches.

I have tried using element() and using [count.index], I am using TF v12.

Below is a snippet of the code, please ignore lines with #(commented).

resource "aws_instance" "workers" {
#count         =   length(data.terraform_remote_state.network.outputs.public_subnet_list)
count         = length(data.aws_subnet_ids.subnet_list.ids)
instance_type = var.worker_instance_type
ami           = var.k8_ami
key_name      = aws_key_pair.ssh_key.key_name
#subnet_id     = "${data.terraform_remote_state.network.outputs.public_subnet_list[count.index]}"
subnet_id = "${element(data.aws_subnet_ids.subnet_list.ids, count.index)}"
vpc_security_group_ids = [
aws_security_group.kubernetes.id
]
}

Below are two error snippets.

Error: Invalid index

on k8-cluster.tf line 85, in resource "aws_instance" "workers":
85:   subnet_id = "${data.aws_subnet_ids.subnet_list.ids[count.index]}"
|----------------
| count.index is 2
| data.aws_subnet_ids.subnet_list.ids is set of string with 4 elements

This value does not have any indices.

Another error with element():

Error: Error in function call

on k8-cluster.tf line 85, in resource "aws_instance" "workers":
85:   subnet_id = "${element(data.aws_subnet_ids.subnet_list.ids, count.index)}"
|----------------
| count.index is 3
| data.aws_subnet_ids.subnet_list.ids is set of string with 4 elements

Call to function "element" failed: cannot read elements from set of string.

Body:
You just need to change the count like this:

count = "${length(data.aws_subnet_ids.subnet_list.ids)}"

And when you quote the variables, I suggest you do it like this:

"${var.var_name}"

So the whole code will like below:

resource "aws_instance" "workers" {
    #count         =   "${length(data.terraform_remote_state.network.outputs.public_subnet_list)}"
    count         = "${length(data.aws_subnet_ids.subnet_list.ids)}"
    instance_type = "${var.worker_instance_type}"
    ami           = "${var.k8_ami}"
    key_name      = "${aws_key_pair.ssh_key.key_name}"
    #subnet_id     = "${data.terraform_remote_state.network.outputs.public_subnet_list[count.index]}"
    subnet_id = "${element(data.aws_subnet_ids.subnet_list.ids, count.index)}"
    vpc_security_group_ids = [
    "${aws_security_group.kubernetes.id}"
    ]
}

You can see the example in Terraform.


问:
hide bootstrap divs one by one when geeting a particular resolution(responsive)
parentRow is a row containing 3 or more divs. It should not go to second row. The first div "Apple" should be visible in every resolution. The second div "Orange" should be visible for col-md-4 and col-lg-4 and col-xl-4 while 3rd div "Pineapple" should be visible only for col-lg-4 and col-xl-4?

In short there is a row containing 3 or more divs (Bootstrap 4.3.1 grids) when the screen is resized the divs should hide one by one and at smaller resolution one div(grid) should remain visible?

Shorter and effective method is welcomed. Please avoid media queries.

        Apple

        Orange

        Pineapple

```

答:
You should use display utilities to hide elements on certain breakpoints.

For example .d-none.d-md-block will be hidden on xs and sm resolutions, and will have display: block on md, lg and xl.

.box {
  padding: .75rem;
  background-color: rgba(86,61,124,.15);
  border: 1px solid rgba(86,61,124,.2);
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="row">
  <div class="col box">
    apple (always visible)
  </div>
  <div class="col box d-none d-md-block">
    Orange (visible on md and bigger)
  </div>
  <div class="col box d-none d-lg-block">
    PineApple (visible on lg and bigger)
  </div>
</div></code>```

Body:
You should use display utilities to hide elements on certain breakpoints.

For example .d-none.d-md-block will be hidden on xs and sm resolutions, and will have display: block on md, lg and xl.

.box {
  padding: .75rem;
  background-color: rgba(86,61,124,.15);
  border: 1px solid rgba(86,61,124,.2);
  text-align: center;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="row">
  <div class="col box">
    apple (always visible)
  </div>
  <div class="col box d-none d-md-block">
    Orange (visible on md and bigger)
  </div>
  <div class="col box d-none d-lg-block">
    PineApple (visible on lg and bigger)
  </div>
</div>


问:
Mongoose: How to avoid inserting duplicate records?
I have written the following mongoose function to create new document in mongodb

```<code>createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
    }));
    return sEntry.save();
}
</code>```

I want to modify the above logic so that it doesn't insert two rows with same dataId

In other words, if a particular value of dataId is already existing in mongo then it should not create another entry with same dataId

答: putting unique: true for dataId in the schema has resolved the issue

Body:
I have written the following mongoose function to create new document in mongodb

createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
    }));
    return sEntry.save();
}

I want to modify the above logic so that it doesn't insert two rows with same dataId

In other words, if a particular value of dataId is already existing in mongo then it should not create another entry with same dataId


问:
Guarding resources with Singleton?
I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge:

Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).

Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).

My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).

Is my choice of making this class a singleton class a bad decision?

答:
Yes and No

No because the problems you see about concurrency are problems you can't "safely" avoid while playing with threads. Sooner or later, bad synchronization mechanisms will come back at you and break your lovely code. You WILL need mutexes and semaphores and such to guard ressources.

Yes, because the singleton is a bad pattern to involve with threads. Check this page about singletons, you will see some pitfalls associated with it. Basically, you're asking for trouble.

Regarding the general "Singletons are evil", it is because it makes it much harder to figure out how it works, they are the OOP version of global variables. Suppose that you have a singleton somewhere, that gets modified in 15 places, how do you track it all? If you had a "real" object, you'd be able to see how it is passed around in parameters and such. The singleton breaks the concept of scope and is easy to transform into a mess.

ContentLicense: CC BY-SA 3.0

Title: Guarding resources with Singleton?


问:
Flyway ClassNotFoundException: JavaUtilLogCreator
I'm using Flyway 5.2.4 and OSGI Bundle Activator. I want to migrate database on bundle Start() method.
Here's my ActivatorClass:

```<code>import org.flywaydb.core.Flyway;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Activator implements BundleActivator {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private ServiceRegistration serviceRegistration;

    public void start(BundleContext bundleContext) {
        log.info("Starting...");
        serviceRegistration = bundleContext.registerService(IConnector.class.getName(), new Connector(), null);
        log.info("Started.");

        //FlyWay Section
        Flyway flyway = Flyway.configure().dataSource("jdbc:postgresql://localhost:5432/", "postgres", "12345").load();
        flyway.migrate();
    }

    public void stop(BundleContext bundleContext) {
        log.info("Stopping...");
        serviceRegistration.unregister();
        log.info("Stopped.");
    }

}
</code>```

As you can see, I'm using slf4j as my Logger. Maybe that's why I get this errors in my StackTrace after app deploying:

```<code>java.lang.Exception: Could not start bundle mvn:internship/db-connector/1.0.0 in feature(s) feature-1.0.0: Activator start error in bundle db-connector [2343].
        at org.apache.karaf.features.internal.FeaturesServiceImpl.startBundle(FeaturesServiceImpl.java:519)[20:org.apache.karaf.features.core:3.0.8]
        at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeatures(FeaturesServiceImpl.java:474)[20:org.apache.karaf.features.core:3.0.8]
        at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeature(FeaturesServiceImpl.java:415)[20:org.apache.karaf.features.core:3.0.8]
        at Proxy683d032e_ad2c_4b9a_98f7_baca7b5564f1.installFeature(Unknown Source)[:]
        at Proxyfff1bf4b_671e_4ff6_bb97_e0dabf9f20e8.installFeature(Unknown Source)[:]
        at org.apache.karaf.kar.internal.KarServiceImpl.installFeatures(KarServiceImpl.java:282)[89:org.apache.karaf.kar.core:3.0.8]
        at org.apache.karaf.kar.internal.KarServiceImpl.install(KarServiceImpl.java:111)[89:org.apache.karaf.kar.core:3.0.8]
        at org.apache.karaf.kar.internal.KarServiceImpl.install(KarServiceImpl.java:93)[89:org.apache.karaf.kar.core:3.0.8]
        at Proxy40d8d25a_37b2_4855_a381_fbb78daa68ce.install(Unknown Source)[:]
        at Proxy068a2f57_120b_4ee8_b953_7c8262bae9a2.install(Unknown Source)[:]
        at org.apache.karaf.deployer.kar.KarArtifactInstaller.update(KarArtifactInstaller.java:62)[91:org.apache.karaf.deployer.kar:3.0.8]
        at Proxy3c143b4c_a2ef_49d0_870b_21a9b5f74704.update(Unknown Source)[:]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.update(DirectoryWatcher.java:1101)[7:org.apache.felix.fileinstall:3.5.2]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.update(DirectoryWatcher.java:898)[7:org.apache.felix.fileinstall:3.5.2]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.doProcess(DirectoryWatcher.java:478)[7:org.apache.felix.fileinstall:3.5.2]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:355)[7:org.apache.felix.fileinstall:3.5.2]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.run(DirectoryWatcher.java:307)[7:org.apache.felix.fileinstall:3.5.2]
Caused by: org.osgi.framework.BundleException: Activator start error in bundle db-connector [2343].
        at org.apache.felix.framework.Felix.activateBundle(Felix.java:2196)[org.apache.felix.framework-4.2.1.jar:]
        at org.apache.felix.framework.Felix.startBundle(Felix.java:2064)[org.apache.felix.framework-4.2.1.jar:]
        at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:955)[org.apache.felix.framework-4.2.1.jar:]
        at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:942)[org.apache.felix.framework-4.2.1.jar:]
        at org.apache.karaf.features.internal.FeaturesServiceImpl.startBundle(FeaturesServiceImpl.java:516)[20:org.apache.karaf.features.core:3.0.8]
        ... 16 more
Caused by: java.lang.ExceptionInInitializerError
        at org.flywaydb.core.internal.util.FeatureDetector.isSlf4jAvailable(FeatureDetector.java:96)
        at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:39)
        at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)
        at org.flywaydb.core.internal.util.FeatureDetector.<clinit>(FeatureDetector.java:25)
        at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:35)
        at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)
        at org.flywaydb.core.Flyway.<clinit>(Flyway.java:86)
        at internship.connectors.postgresConnector.Activator.start(Activator.java:18)
        at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:645)
        at org.apache.felix.framework.Felix.activateBundle(Felix.java:2146)
        ... 20 more
Caused by: org.flywaydb.core.api.FlywayException: Unable to instantiate class org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator : org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator
        at org.flywaydb.core.internal.util.ClassUtils.instantiate(ClassUtils.java:63)[2348:org.flywaydb.core:5.2.4]
        at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:46)[2348:org.flywaydb.core:5.2.4]
        at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)[2348:org.flywaydb.core:5.2.4]
        at org.flywaydb.core.internal.util.ClassUtils.<clinit>(ClassUtils.java:39)[2348:org.flywaydb.core:5.2.4]
        ... 30 more
Caused by: java.lang.ClassNotFoundException: org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator
        at java.net.URLClassLoader.findClass(Unknown Source)[:1.8.0_212]
        at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_212]
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)[:1.8.0_212]
        at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_212]
        at java.lang.Class.forName0(Native Method)[:1.8.0_212]
        at java.lang.Class.forName(Unknown Source)[:1.8.0_212]
        at org.flywaydb.core.internal.util.ClassUtils.instantiate(ClassUtils.java:61)[2348:org.flywaydb.core:5.2.4]
        ... 33 more
</code>```

So, I just have no idea what's wrong here, I've used simpliest example from official Flyway's site and get this errors.
I've already try to delete my own Logger. I thought it can let FlyWay to use it's logger, but everything goes the same way (same errors).

Could you help me?

P.S. Looks like this pull request somehow related to my problem.

答:
Indeed it seems Flyway might have issues in OSGi. Maybe you can provide them an issue and your example.

Another issue with your example is that you try to access the DataSource via a url. This does not work in OSGi. The reason is that this way flyway has to have direct access to the database driver classes. This does not work in OSGi.

In OSGi the way to access a Database is with a DataSourceFactory which the database driver creates as a service. From this factory you can create a DataSource.

As not all database drivers offer this service there is pax-jdbc which provides factories for all common databases. It also allows to create a DataSource including pooling from a OSGi config.

Your approach of migrating on bundle start is a very bad idea. The methods in the activator must return quickly and a databse migration might take a while. Of course you want to make sure the migration takes place before any bundle in the system accesses the database. Fortunately there is a way to hook into the DataSource creation to do things like a migration.

See the liquibase tutorial which also shows a database migration. It uses the PreHook offered by pax-jdbc which makes sure your migration code is run before the DataSource is given to any other bundle.

Body:
I'm using Flyway 5.2.4 and OSGI Bundle Activator. I want to migrate database on bundle Start() method.
Here's my ActivatorClass:

import org.flywaydb.core.Flyway;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Activator implements BundleActivator {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private ServiceRegistration serviceRegistration;

    public void start(BundleContext bundleContext) {
        log.info("Starting...");
        serviceRegistration = bundleContext.registerService(IConnector.class.getName(), new Connector(), null);
        log.info("Started.");

        //FlyWay Section
        Flyway flyway = Flyway.configure().dataSource("jdbc:postgresql://localhost:5432/", "postgres", "12345").load();
        flyway.migrate();
    }

    public void stop(BundleContext bundleContext) {
        log.info("Stopping...");
        serviceRegistration.unregister();
        log.info("Stopped.");
    }

}

As you can see, I'm using slf4j as my Logger. Maybe that's why I get this errors in my StackTrace after app deploying:

java.lang.Exception: Could not start bundle mvn:internship/db-connector/1.0.0 in feature(s) feature-1.0.0: Activator start error in bundle db-connector [2343].
        at org.apache.karaf.features.internal.FeaturesServiceImpl.startBundle(FeaturesServiceImpl.java:519)[20:org.apache.karaf.features.core:3.0.8]
        at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeatures(FeaturesServiceImpl.java:474)[20:org.apache.karaf.features.core:3.0.8]
        at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeature(FeaturesServiceImpl.java:415)[20:org.apache.karaf.features.core:3.0.8]
        at Proxy683d032e_ad2c_4b9a_98f7_baca7b5564f1.installFeature(Unknown Source)[:]
        at Proxyfff1bf4b_671e_4ff6_bb97_e0dabf9f20e8.installFeature(Unknown Source)[:]
        at org.apache.karaf.kar.internal.KarServiceImpl.installFeatures(KarServiceImpl.java:282)[89:org.apache.karaf.kar.core:3.0.8]
        at org.apache.karaf.kar.internal.KarServiceImpl.install(KarServiceImpl.java:111)[89:org.apache.karaf.kar.core:3.0.8]
        at org.apache.karaf.kar.internal.KarServiceImpl.install(KarServiceImpl.java:93)[89:org.apache.karaf.kar.core:3.0.8]
        at Proxy40d8d25a_37b2_4855_a381_fbb78daa68ce.install(Unknown Source)[:]
        at Proxy068a2f57_120b_4ee8_b953_7c8262bae9a2.install(Unknown Source)[:]
        at org.apache.karaf.deployer.kar.KarArtifactInstaller.update(KarArtifactInstaller.java:62)[91:org.apache.karaf.deployer.kar:3.0.8]
        at Proxy3c143b4c_a2ef_49d0_870b_21a9b5f74704.update(Unknown Source)[:]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.update(DirectoryWatcher.java:1101)[7:org.apache.felix.fileinstall:3.5.2]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.update(DirectoryWatcher.java:898)[7:org.apache.felix.fileinstall:3.5.2]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.doProcess(DirectoryWatcher.java:478)[7:org.apache.felix.fileinstall:3.5.2]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:355)[7:org.apache.felix.fileinstall:3.5.2]
        at org.apache.felix.fileinstall.internal.DirectoryWatcher.run(DirectoryWatcher.java:307)[7:org.apache.felix.fileinstall:3.5.2]
Caused by: org.osgi.framework.BundleException: Activator start error in bundle db-connector [2343].
        at org.apache.felix.framework.Felix.activateBundle(Felix.java:2196)[org.apache.felix.framework-4.2.1.jar:]
        at org.apache.felix.framework.Felix.startBundle(Felix.java:2064)[org.apache.felix.framework-4.2.1.jar:]
        at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:955)[org.apache.felix.framework-4.2.1.jar:]
        at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:942)[org.apache.felix.framework-4.2.1.jar:]
        at org.apache.karaf.features.internal.FeaturesServiceImpl.startBundle(FeaturesServiceImpl.java:516)[20:org.apache.karaf.features.core:3.0.8]
        ... 16 more
Caused by: java.lang.ExceptionInInitializerError
        at org.flywaydb.core.internal.util.FeatureDetector.isSlf4jAvailable(FeatureDetector.java:96)
        at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:39)
        at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)
        at org.flywaydb.core.internal.util.FeatureDetector.<clinit>(FeatureDetector.java:25)
        at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:35)
        at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)
        at org.flywaydb.core.Flyway.<clinit>(Flyway.java:86)
        at internship.connectors.postgresConnector.Activator.start(Activator.java:18)
        at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:645)
        at org.apache.felix.framework.Felix.activateBundle(Felix.java:2146)
        ... 20 more
Caused by: org.flywaydb.core.api.FlywayException: Unable to instantiate class org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator : org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator
        at org.flywaydb.core.internal.util.ClassUtils.instantiate(ClassUtils.java:63)[2348:org.flywaydb.core:5.2.4]
        at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:46)[2348:org.flywaydb.core:5.2.4]
        at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)[2348:org.flywaydb.core:5.2.4]
        at org.flywaydb.core.internal.util.ClassUtils.<clinit>(ClassUtils.java:39)[2348:org.flywaydb.core:5.2.4]
        ... 30 more
Caused by: java.lang.ClassNotFoundException: org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator
        at java.net.URLClassLoader.findClass(Unknown Source)[:1.8.0_212]
        at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_212]
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)[:1.8.0_212]
        at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_212]
        at java.lang.Class.forName0(Native Method)[:1.8.0_212]
        at java.lang.Class.forName(Unknown Source)[:1.8.0_212]
        at org.flywaydb.core.internal.util.ClassUtils.instantiate(ClassUtils.java:61)[2348:org.flywaydb.core:5.2.4]
        ... 33 more

So, I just have no idea what's wrong here, I've used simpliest example from official Flyway's site and get this errors.
I've already try to delete my own Logger. I thought it can let FlyWay to use it's logger, but everything goes the same way (same errors).

Could you help me?

P.S. Looks like this pull request somehow related to my problem.


问:
Why my element needs to be clicked on in order for CSS to work?
My element has to be clicked on for CSS to work.

I tried using bootstrap for a nav bar. With 1 logout link on the top right.
I used navbar-nav ml-auto for it.

After that, I tried to override spacing of bootstrap by adding margin-right: 50% !important;

When I refresh the page, it is not applied immediately. If I clicked on the link, it will "jump" to the left as I expected.

Here is what I've tried:

```<code> <nav class="navbar navbar-expand-sm bg-light">
        <!-- Links -->
        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" href="#">Home</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Category</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Blog posts</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Role Management</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">User Management</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">File and Folder Management</a>
            </li>
        </ul>
        <ul class="navbar-nav ml-auto">
            <li>
                <a class="nav-item" id="logout-btn" href="#"> Logout </a>
            </li>
        </ul>
    </nav>
</code>```

CSS:

```<code>* {
    /*display: none;*/
    box-sizing: border-box;
}
 #logout-btn.nav-item {
    margin-right: 50% !important;
}
</code>```

Can you help me explain why, or is it my browser's fault?
I find it quite weird, already cleared cached.

答:
Remove css style for logout-btn.nav-item which you override. this get applied to the anchor tag. we need to add margin to the ul tag  not to a tag. so we have bootstrap 4 in-built margin classes, so we can make use of it. so remove overrided styles and add mr-4 class to the second ul which contains the logout link.The modified code is given below.

```<code> <nav class="navbar navbar-expand-sm bg-light">
        <!-- Links -->
     <ul class="navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="#">Home</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Category</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Blog posts</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Role Management</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">User Management</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">File and Folder Management</a>
        </li>
     </ul>
     <ul class="navbar-nav ml-auto mr-4">
        <li>
            <a class="nav-item" id="logout-btn" href="#"> Logout </a>
        </li>
     </ul>
</nav>
</code>```

Body:
My element has to be clicked on for CSS to work.

I tried using bootstrap for a nav bar. With 1 logout link on the top right.
I used navbar-nav ml-auto for it.

After that, I tried to override spacing of bootstrap by adding margin-right: 50% !important;

When I refresh the page, it is not applied immediately. If I clicked on the link, it will "jump" to the left as I expected.

Here is what I've tried:

                Home

                Category

                Blog posts

                Role Management

                User Management

                File and Folder Management

                 Logout

CSS:

* {
    /*display: none;*/
    box-sizing: border-box;
}
 #logout-btn.nav-item {
    margin-right: 50% !important;
}

Can you help me explain why, or is it my browser's fault?
I find it quite weird, already cleared cached.

Body:
Remove css style for logout-btn.nav-item which you override. this get applied to the anchor tag. we need to add margin to the ul tag  not to a tag. so we have bootstrap 4 in-built margin classes, so we can make use of it. so remove overrided styles and add mr-4 class to the second ul which contains the logout link.The modified code is given below.

 <nav class="navbar navbar-expand-sm bg-light">
        <!-- Links -->
     <ul class="navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="#">Home</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Category</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Blog posts</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Role Management</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">User Management</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">File and Folder Management</a>
        </li>
     </ul>
     <ul class="navbar-nav ml-auto mr-4">
        <li>
            <a class="nav-item" id="logout-btn" href="#"> Logout </a>
        </li>
     </ul>
</nav>


问:
Getting attribute of type postgres
lets say I create a type like this:

```<code>CREATE TYPE books AS (
  book_id NUMERIC
, row_num NUMERIC
);
</code>```

I want to write a query that returns me the attributes (book_id, row_num) of books.

I am not sure how to do this?

答:
Use this

```<code>SELECT array_agg(a.attname)
  FROM   pg_class c JOIN pg_attribute a
         ON c.oid = a.attrelid
WHERE  c.relname = 'books';
</code>```

Result

```<code>     array_agg
-------------------
 {book_id,row_num}
(1 row)
</code>```

Title: Getting attribute of type postgres

Body:
lets say I create a type like this:

CREATE TYPE books AS (
  book_id NUMERIC
, row_num NUMERIC
);

I want to write a query that returns me the attributes (book_id, row_num) of books.

I am not sure how to do this?

Body:
Use this

SELECT array_agg(a.attname)
  FROM   pg_class c JOIN pg_attribute a
         ON c.oid = a.attrelid
WHERE  c.relname = 'books';

Result

     array_agg
-------------------
 {book_id,row_num}
(1 row)


问:
Optimization with Loop Tiling and OpenMP
Below is my function that I'm trying to optimize using OpenMP and Loop Tiling(aka Loop Blocking). However, my output of out currently gives the wrong value after I apply the loop tiling like below. Can someone look over my code, and point out what makes it wrong. Thank you so much</p>

```<code>#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
#include "utils.h"
const long BLOCK_SIZE = 8*DIM;
int i, j, k,ii,jj,kk, dim = DIM-1;

long compute, out = 1.0, we_need, gimmie;

void work_it_par(long *old, long *new)
{
 we_need = need_func();
 gimmie = gimmie_func();

 #pragma omp parallel for private(i,j,k,ii,jj,kk, compute)      firstprivate(we_need, gimmie, dim,old,BLOCK_SIZE) reduction(+:out)   num_threads(omp_get_num_procs())
for (ii=1; ii<dim-BLOCK_SIZE; ii+=BLOCK_SIZE) {
  for (jj=1; jj<dim-BLOCK_SIZE; jj+=BLOCK_SIZE) {
    for (kk=1; kk<dim-BLOCK_SIZE; kk+=BLOCK_SIZE) {
      for (i=ii; i<ii+BLOCK_SIZE; i++) {
        for (j=jj; j<jj+BLOCK_SIZE; j++) {
          for (k=kk; k<kk+BLOCK_SIZE; k++) {
            //int temp = i*DIM*DIM+j*DIM+k;
            compute = old[i*DIM*DIM+j*DIM+k] * we_need;
            out += compute / gimmie;
          }
        }
      }

    }
  }
}

printf("AGGR:%ld\n",out);

}
</code>```

答:
First of all, const long BLOCK_SIZE = 8*DIM; seems super fishy to me...
Maybe replacing the * by a / would be more of what you wanted?

But even though, you still have to deal with the limits by checking that the i, j and k indexes do not go over their limits. I let you figure out how to achieve that.

Last point on the algorithm: are you sure your loops have to start from index 1?

Finally, a few notes on the OpenMP correctness:

although I see nothing wrong in there, declaring firstprivate(we_need, gimmie, dim,old,BLOCK_SIZE) doesn't make much sense. These could happily stay shared.

I don't really know whether num_threads(omp_get_num_procs()) is correct or not. My feeling is that it is indeed valid, but just for "safety", I would tend to separate the call to the function from the directive (by either calling the function first and storing its result in a constant, and using it in the directive, or calling omp_set_num_threads()before the parallel directive)

when your algorithm is fixed, you might want to consider adding some collapse directive to increase the level of parallelism you achieve here...

Good luck with your code.

Body:
Below is my function that I'm trying to optimize using OpenMP and Loop Tiling(aka Loop Blocking). However, my output of out currently gives the wrong value after I apply the loop tiling like below. Can someone look over my code, and point out what makes it wrong. Thank you so much

#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
#include "utils.h"
const long BLOCK_SIZE = 8*DIM;
int i, j, k,ii,jj,kk, dim = DIM-1;

long compute, out = 1.0, we_need, gimmie;

void work_it_par(long *old, long *new)
{
 we_need = need_func();
 gimmie = gimmie_func();

 #pragma omp parallel for private(i,j,k,ii,jj,kk, compute)      firstprivate(we_need, gimmie, dim,old,BLOCK_SIZE) reduction(+:out)   num_threads(omp_get_num_procs())
for (ii=1; ii<dim-BLOCK_SIZE; ii+=BLOCK_SIZE) {
  for (jj=1; jj<dim-BLOCK_SIZE; jj+=BLOCK_SIZE) {
    for (kk=1; kk<dim-BLOCK_SIZE; kk+=BLOCK_SIZE) {
      for (i=ii; i<ii+BLOCK_SIZE; i++) {
        for (j=jj; j<jj+BLOCK_SIZE; j++) {
          for (k=kk; k<kk+BLOCK_SIZE; k++) {
            //int temp = i*DIM*DIM+j*DIM+k;
            compute = old[i*DIM*DIM+j*DIM+k] * we_need;
            out += compute / gimmie;
          }
        }
      }

    }
  }
}

printf("AGGR:%ld\n",out);

}


问:
Get the number of pages in a Word document
I am making lots of changes to a Word document using automation, and then running a VBA macro which - among other things - checks that the document is no more than a certain number of pages.

I'm using ActiveDocument.Information(wdNumberOfPagesInDocument) to get the number of pages, but this method is returning an incorrect result.  I think this is because Word has not yet updated the pagination of the document to reflect the changes that I've made.

ActiveDocument.ComputeStatistics(wdStatisticPages) also suffers from the same issue.

I've tried sticking in a call to ActiveDocument.Repaginate, but that makes no difference.

I did have some luck with adding a paragraph to the end of the document and then deleting it again - but that hack seems to no longer work (I've recently moved from Word 2003 to Word 2010).

Is there any way I can force Word to actually repaginate, and/or wait until the repagination is complete?

答:
```<code>Dim wordapp As Object
Set wordapp = CreateObject("Word.Application")
Dim doc As Object
Set doc = wordapp.Documents.Open(oFile.Path)

Dim pagesCount As Integer
pagesCount = doc.Content.Information(4) 'wdNumberOfPagesInDocument
doc.Close False
Set doc = Nothing
</code>```


问:
How to run a web service from eclipse on another machine/real server
I'm new to the Java world and I managed to create a web service, run it on Tomcat server and use it in my Silverlight project.

The problem is I don't know how to start this service on a Windows machine that doesn't have Eclipse.

More importantly, how can I start it on a real server? A tutorial or step-by-step guide would be nice.

答:
Have you read the FAQ for the relevant version of Tomcat? For example, for version 7.0, the Setup page of the docs gives some information, as well as linking to the docs for running Tomcat as a Windows service.

Of course, configuring Tomcat to run your servlet is a separate task, but the Tomcat docs are pretty comprehensive.

If you're still running into problems after reading those docs very carefully, please edit your question to tell us exactly which bits you're having problems with.


问:
Create combinations from list and remove if substring to delimiter characters is in more than 1 subelement of a list item
I have a list that I use itertools.combinations to create all combinations. The elements in each list item are able to be delimited by the string ": ". I need to remove list items where there is more than one occurrence of the same matched substring in more than 1 element. The characters in the string up until ": " (delimiter to use for regex match???) needs to check each sub-element in a list item. Or, is there a better way?

```<code>inList = [['TEST1: sub1'],
['TEST1: sub2'],
['TEST1: sub3'],
['TESTING FOR FUN: randomtext'],
['TESTING FOR FUN: random text x2'],
['ABC123: dog']]
outputList = list(combinations(inList,3))
outputList
</code>```

I get this as a result:

```<code>[(['TEST1: sub1'], ['TEST1: sub2']),
 (['TEST1: sub1'], ['TEST1: sub3']),
 (['TEST1: sub1'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub1'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub1'], ['ABC123: dog']),
 (['TEST1: sub2'], ['TEST1: sub3']),
 (['TEST1: sub2'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub2'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub2'], ['ABC123: dog']),
 (['TEST1: sub3'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub3'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub3'], ['ABC123: dog']),
 (['TESTING FOR FUN: randomtext'], ['TESTING FOR FUN: random text x2']),
 (['TESTING FOR FUN: randomtext'], ['ABC123: dog']),
 (['TESTING FOR FUN: random text x2'], ['ABC123: dog'])]
</code>```

But I'd like to remove where substrings match sub-elements up until the delimiter ": ".

Desired output after sub-elements are checked for >1 occurrence in other sub-elements of a list item:

```<code>(['TEST1: sub1'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub1'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub1'], ['ABC123: dog']),
 (['TEST1: sub2'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub2'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub2'], ['ABC123: dog']),
 (['TEST1: sub3'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub3'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub3'], ['ABC123: dog']),
 (['TESTING FOR FUN: randomtext'], ['ABC123: dog']),
 (['TESTING FOR FUN: random text x2'], ['ABC123: dog'])]
</code>```

*Notice the first 2 items in the list are removed in the desired output? (this applied to others where the substring prior to ": " occurs regardless of string length.

答:
If the desired output is correct, then you can break this down into three separate steps:

First, The delimiter is representing a key value relationship, so you can just use a dictionary to group the data with same keys before doing any other operation.

Second, take as many n length combinations of the data with different keys.

Lastly, for each of those combinations, use itertools product to get all possible pairs within the combination.

```<code>from itertools import combinations, product
from collections import defaultdict

inList = [['TEST1: sub1'],
['TEST1: sub2'],
['TEST1: sub3'],
['TESTING FOR FUN: randomtext'],
['TESTING FOR FUN: random text x2'],
['ABC123: dog']]

inDict = defaultdict(list)
for lst in inList:
    key = lst[0].partition(':')[0]
    inDict[key].append(lst)

print(inDict)
#Output:
defaultdict(list,
            {'TEST1': [['TEST1: sub1'], ['TEST1: sub2'], ['TEST1: sub3']],
             'TESTING FOR FUN': [['TESTING FOR FUN: randomtext'],
              ['TESTING FOR FUN: random text x2']],
             'ABC123': [['ABC123: dog']]})

temp = combinations(inDict.values(), 2) #2 length pairs from all dict values. change the number here as needed
result = []
for group in temp:
    result.extend(product(*group)) #calculate all products for each pair of lists.

print(result)
#Output:
[(['TEST1: sub1'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub1'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub2'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub2'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub3'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub3'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub1'], ['ABC123: dog']),
 (['TEST1: sub2'], ['ABC123: dog']),
 (['TEST1: sub3'], ['ABC123: dog']),
 (['TESTING FOR FUN: randomtext'], ['ABC123: dog']),
 (['TESTING FOR FUN: random text x2'], ['ABC123: dog'])]
</code>```

Body:
I have a list that I use itertools.combinations to create all combinations. The elements in each list item are able to be delimited by the string ": ". I need to remove list items where there is more than one occurrence of the same matched substring in more than 1 element. The characters in the string up until ": " (delimiter to use for regex match???) needs to check each sub-element in a list item. Or, is there a better way?

inList = [['TEST1: sub1'],
['TEST1: sub2'],
['TEST1: sub3'],
['TESTING FOR FUN: randomtext'],
['TESTING FOR FUN: random text x2'],
['ABC123: dog']]
outputList = list(combinations(inList,3))
outputList

I get this as a result:

[(['TEST1: sub1'], ['TEST1: sub2']),
 (['TEST1: sub1'], ['TEST1: sub3']),
 (['TEST1: sub1'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub1'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub1'], ['ABC123: dog']),
 (['TEST1: sub2'], ['TEST1: sub3']),
 (['TEST1: sub2'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub2'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub2'], ['ABC123: dog']),
 (['TEST1: sub3'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub3'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub3'], ['ABC123: dog']),
 (['TESTING FOR FUN: randomtext'], ['TESTING FOR FUN: random text x2']),
 (['TESTING FOR FUN: randomtext'], ['ABC123: dog']),
 (['TESTING FOR FUN: random text x2'], ['ABC123: dog'])]

But I'd like to remove where substrings match sub-elements up until the delimiter ": ".

Desired output after sub-elements are checked for >1 occurrence in other sub-elements of a list item:

(['TEST1: sub1'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub1'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub1'], ['ABC123: dog']),
 (['TEST1: sub2'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub2'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub2'], ['ABC123: dog']),
 (['TEST1: sub3'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub3'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub3'], ['ABC123: dog']),
 (['TESTING FOR FUN: randomtext'], ['ABC123: dog']),
 (['TESTING FOR FUN: random text x2'], ['ABC123: dog'])]

*Notice the first 2 items in the list are removed in the desired output? (this applied to others where the substring prior to ": " occurs regardless of string length.

Body:
If the desired output is correct, then you can break this down into three separate steps:

First, The delimiter is representing a key value relationship, so you can just use a dictionary to group the data with same keys before doing any other operation.

Second, take as many n length combinations of the data with different keys.

Lastly, for each of those combinations, use itertools product to get all possible pairs within the combination.

from itertools import combinations, product
from collections import defaultdict

inList = [['TEST1: sub1'],
['TEST1: sub2'],
['TEST1: sub3'],
['TESTING FOR FUN: randomtext'],
['TESTING FOR FUN: random text x2'],
['ABC123: dog']]

inDict = defaultdict(list)
for lst in inList:
    key = lst[0].partition(':')[0]
    inDict[key].append(lst)

print(inDict)
#Output:
defaultdict(list,
            {'TEST1': [['TEST1: sub1'], ['TEST1: sub2'], ['TEST1: sub3']],
             'TESTING FOR FUN': [['TESTING FOR FUN: randomtext'],
              ['TESTING FOR FUN: random text x2']],
             'ABC123': [['ABC123: dog']]})

temp = combinations(inDict.values(), 2) #2 length pairs from all dict values. change the number here as needed
result = []
for group in temp:
    result.extend(product(*group)) #calculate all products for each pair of lists.

print(result)
#Output:
[(['TEST1: sub1'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub1'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub2'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub2'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub3'], ['TESTING FOR FUN: randomtext']),
 (['TEST1: sub3'], ['TESTING FOR FUN: random text x2']),
 (['TEST1: sub1'], ['ABC123: dog']),
 (['TEST1: sub2'], ['ABC123: dog']),
 (['TEST1: sub3'], ['ABC123: dog']),
 (['TESTING FOR FUN: randomtext'], ['ABC123: dog']),
 (['TESTING FOR FUN: random text x2'], ['ABC123: dog'])]


问:
DB2 equivalency for Teradata clustered tables
In Teradata the definition of a clustered table is very simple and exists in a single syntax (correct me if I'm wrong).

```<code>CREATE TABLE table_name (charcol1 varchar(10), idcol integer)
primary index (idcol);
</code>```

I am reading that there are a whole number of "clustered" table types in DB2 with respect to creating a share-nothing physical data layout for the object.

Defined primary index in TD will spread the table data across all nodes/virtual cpus available to the TD server.

What is the closest method (and syntax) to achieve the same within DB2?

答:
I would recommend to start with this overview of data partitioning (concepts) for Db2.

The following three clauses demonstrate the levels of data organization that can be used together in any combination:

DISTRIBUTE BY to spread data evenly across database partitions (to enable intraquery parallelism and to balance the load across each database partition) (database partitioning)

PARTITION BY to group rows with similar values of a single dimension in the same data partition (table partitioning)

ORGANIZE BY to group rows with similar values on multiple dimensions in the same table extent (multidimensional clustering) or to group rows according to the time of the insert operation (insert time clustering table).

All three clauses can be used within the same CREATE TABLE statement. Its usage depends on the data and the envisioned queries.

The database partitioning (DISTRIBUTE BY) is the shared-nothing you asked for. Distribute the data across partitions based on the YEAR.

```<code> CREATE TABLE SALES
     (CUSTOMER   VARCHAR(80),
      REGION     CHAR(5),
      YEAR       INTEGER)
   DISTRIBUTE BY HASH (YEAR)
</code>```

Body:
In Teradata the definition of a clustered table is very simple and exists in a single syntax (correct me if I'm wrong).

CREATE TABLE table_name (charcol1 varchar(10), idcol integer)
primary index (idcol);

I am reading that there are a whole number of "clustered" table types in DB2 with respect to creating a share-nothing physical data layout for the object.

Defined primary index in TD will spread the table data across all nodes/virtual cpus available to the TD server.

What is the closest method (and syntax) to achieve the same within DB2?

Body:
I would recommend to start with this overview of data partitioning (concepts) for Db2.

The following three clauses demonstrate the levels of data organization that can be used together in any combination:

DISTRIBUTE BY to spread data evenly across database partitions (to enable intraquery parallelism and to balance the load across each database partition) (database partitioning)

PARTITION BY to group rows with similar values of a single dimension in the same data partition (table partitioning)

ORGANIZE BY to group rows with similar values on multiple dimensions in the same table extent (multidimensional clustering) or to group rows according to the time of the insert operation (insert time clustering table).

All three clauses can be used within the same CREATE TABLE statement. Its usage depends on the data and the envisioned queries.

The database partitioning (DISTRIBUTE BY) is the shared-nothing you asked for. Distribute the data across partitions based on the YEAR.

 CREATE TABLE SALES
     (CUSTOMER   VARCHAR(80),
      REGION     CHAR(5),
      YEAR       INTEGER)
   DISTRIBUTE BY HASH (YEAR)


问:
Pygame and Keyboard modules combination, True loop breaking abruptly
I am making a code which moves a 0 up, down, left and right using WASD keys and the keyboard module for python!

I am not sure what to do and I haven't tried anything yet...

This is the code!

import pygame
from pygame.locals import *
import keyboard;

def draw():
    pygame.init();
    x=1280
    y=720
    screen=pygame.display.set_mode((x, y))
    font = pygame.font.Font('freesansbold.ttf', 24)
    black=(0, 0, 0)
    white=(255, 255, 255)
    text = font.render('0', True, black, white)
    textRect = text.get_rect()
    x=x/2; y=y/2;
    textRect.center=(x, y)
    screen.fill((white))
    screen.blit(text, textRect)

    while True:
        if keyboard.is_pressed('w'):
            textRect = text.get_rect()
            y = y - 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)

        if keyboard.is_pressed('a'):
            textRect = text.get_rect()
            x = x - 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        if keyboard.is_pressed('d'):
            textRect = text.get_rect()
            x = x + 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        if keyboard.is_pressed('s'):
            textRect = text.get_rect()
            y = y + 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit();
                quit();
            pygame.display.update()

if __name__=="__main__":
    draw()
```

This is the error

Here is a gif of the error(I don't have the reputation yet to upload it here!)

link to gif: https://gfycat.com/GlossyCheerfulEstuarinecrocodile

The actual result should be the zero moving up...

答:
I didn't find any error at the link you provided: just a white screen with O in the center and flashing small windows with a text so small it impossible to read.

When I tried to run your code, the error was:

Hello from the pygame community. https://www.pygame.org/contribute.html
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keyboard/__init__.py", line 292, in listen
    _os_keyboard.listen(self.direct_callback)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keyboard/_darwinkeyboard.py", line 430, in listen
    raise OSError("Error 13 - Must be run as administrator")
OSError: Error 13 - Must be run as administrator
```

<p>So, I ran it as an administrator with 'sudo' and was able to move zero '0' with the keyboard.</p>

<pre class="lang-none prettyprint-override"><code>sudo python3.7 object_type.py
</code>```

Body:
I am making a code which moves a 0 up, down, left and right using WASD keys and the keyboard module for python!

I am not sure what to do and I haven't tried anything yet...

This is the code!

import pygame
from pygame.locals import *
import keyboard;

def draw():
    pygame.init();
    x=1280
    y=720
    screen=pygame.display.set_mode((x, y))
    font = pygame.font.Font('freesansbold.ttf', 24)
    black=(0, 0, 0)
    white=(255, 255, 255)
    text = font.render('0', True, black, white)
    textRect = text.get_rect()
    x=x/2; y=y/2;
    textRect.center=(x, y)
    screen.fill((white))
    screen.blit(text, textRect)

    while True:
        if keyboard.is_pressed('w'):
            textRect = text.get_rect()
            y = y - 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)

        if keyboard.is_pressed('a'):
            textRect = text.get_rect()
            x = x - 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        if keyboard.is_pressed('d'):
            textRect = text.get_rect()
            x = x + 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        if keyboard.is_pressed('s'):
            textRect = text.get_rect()
            y = y + 5;
            textRect.center = (x, y)
            screen.fill((white))
            screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit();
                quit();
            pygame.display.update()

if __name__=="__main__":
    draw()

This is the error

Here is a gif of the error(I don't have the reputation yet to upload it here!)

link to gif: https://gfycat.com/GlossyCheerfulEstuarinecrocodile

The actual result should be the zero moving up...

Body:
I didn't find any error at the link you provided: just a white screen with O in the center and flashing small windows with a text so small it impossible to read.

When I tried to run your code, the error was:

Hello from the pygame community. https://www.pygame.org/contribute.html
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keyboard/__init__.py", line 292, in listen
    _os_keyboard.listen(self.direct_callback)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keyboard/_darwinkeyboard.py", line 430, in listen
    raise OSError("Error 13 - Must be run as administrator")
OSError: Error 13 - Must be run as administrator

So, I ran it as an administrator with 'sudo' and was able to move zero '0' with the keyboard.

sudo python3.7 object_type.py


问:
install tflearn but not found contrib
With Ubuntu 18.04 64bit , anaconda3 , and python3

```<code>>>> import tflearn
</code>```

Traceback (most recent call last):
    File "", line 1, in
    File "/home/a1/anaconda3/lib/python3.7/site-packages/tflearn/init.py", line 4, in
      from . import config
    File "/home/a1/anaconda3/lib/python3.7/site-packages/tflearn/config.py", line 5, in
      from .variables import variable
    File "/home/a1/anaconda3/lib/python3.7/site-packages/tflearn/variables.py", line 7, in
      from tensorflow.contrib.framework.python.ops import add_arg_scope as contrib_add_arg_scope
  ModuleNotFoundError: No module named 'tensorflow.contrib'

But I can't install it.

```<code>pip install tflearn
</code>```

Requirement already satisfied: tflearn in ./anaconda3/lib/python3.7/site-packages (0.3.2)
  Requirement already satisfied: Pillow in ./anaconda3/lib/python3.7/site-packages (from tflearn) (5.3.0)
  Requirement already satisfied: six in ./anaconda3/lib/python3.7/site-packages (from tflearn) (1.12.0)
  Requirement already satisfied: numpy in ./anaconda3/lib/python3.7/site-packages (from tflearn) (1.15.4)

Pleeeeease help me :<

答:
As seen in the error message, it seems you do not have tensorflow installed. Install it using

```<code>pip install tensorflow
</code>```

and then check.

Title: install tflearn but not found contrib

Body:
With Ubuntu 18.04 64bit , anaconda3 , and python3

>>> import tflearn

Traceback (most recent call last):
    File "", line 1, in
    File "/home/a1/anaconda3/lib/python3.7/site-packages/tflearn/init.py", line 4, in
      from . import config
    File "/home/a1/anaconda3/lib/python3.7/site-packages/tflearn/config.py", line 5, in
      from .variables import variable
    File "/home/a1/anaconda3/lib/python3.7/site-packages/tflearn/variables.py", line 7, in
      from tensorflow.contrib.framework.python.ops import add_arg_scope as contrib_add_arg_scope
  ModuleNotFoundError: No module named 'tensorflow.contrib'

But I can't install it.

pip install tflearn

Requirement already satisfied: tflearn in ./anaconda3/lib/python3.7/site-packages (0.3.2)
  Requirement already satisfied: Pillow in ./anaconda3/lib/python3.7/site-packages (from tflearn) (5.3.0)
  Requirement already satisfied: six in ./anaconda3/lib/python3.7/site-packages (from tflearn) (1.12.0)
  Requirement already satisfied: numpy in ./anaconda3/lib/python3.7/site-packages (from tflearn) (1.15.4)

Pleeeeease help me :<

Body:
As seen in the error message, it seems you do not have tensorflow installed. Install it using

pip install tensorflow

and then check.


问:
How to get the value of multidimensional array based on the ID
I have a multidimensional array, i display all of the values in a table using foreach loop. in that table i have an view profile (a href=). what i want to do is to get the array and pass it to another page and display the value of the array based on the id</p>

```<code><?php include_once('fake_db.php'); ?>

<--index.php-->

<div class="widget-body">
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
    <thead>
    <tr>
        <th>Name</th><th>Position</th><th>Action</th>
    </tr>
    </thead>
    <?php foreach($employees as $key => $value){ ?>
        <tr>
            <td><?= $value['name']?></td>
            <td><?= $value['position']; ?></td>
            <td><a href="profile.php?id=<?= $key; ?>">View Profile</a></td>
        </tr>
    <?php } ?>
</table>
</div>

<-- profile.php -->
<h3>Employee Profile : Employee Name</h3>
<a href="index.php">Back to Employee List</a>
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
    <thead>
    <tr>
        <td>Name </td>
        <td>Employee Position</td>
    </tr>
    </thead>
    <tr>

            <td></td>
            <td></td>
    </tr>
</table>

<--fake_db.php-->
<?php

$employees = array
             (
               1 => array("name" => 'Jason Alipala', "employee_id" => 'G1001-05', 'position' => 1),
               2 => array("name" => 'Bryann Revina', "employee_id" => 'G1009-03', 'position' => 2),
               3 => array("name" => 'Jeniel Mangahis', "employee_id" => 'G1009-04', 'position' => 2),
               4 => array("name" => 'Arjay Bussala', "employee_id" => 'G1009-05', 'position' => 3),
               5 => array("name" => 'Ronnel Ines', "employee_id" => 'G1002-06', 'position' => 3)
             );

$emp_positions = array_count_values(array_column($employees, 'position'));

$positions = array(1 => 'TL', 2 => 'Programmer', 3 => 'Converter');

?>

</code>```

答:
Please replace profile.php to following.

<?php include_once('fake_db.php');
    $id = $_GET['id'];
    $employee = $employees[$id]
    ?>

Employee Profile : Employee Name

Back to Employee List

        Name
        Employee Position

            <?php echo $employee['name'] ?>
            <?php echo $employee['position'] ?>

```

Body:
I have a multidimensional array, i display all of the values in a table using foreach loop. in that table i have an view profile (a href=). what i want to do is to get the array and pass it to another page and display the value of the array based on the id

<?php include_once('fake_db.php'); ?>

<--index.php-->

        Name	Position	Action

    <?php foreach($employees as $key => $value){ ?>

            <?= $value['name']?>
            <?= $value['position']; ?>
            <a href="profile.php?id=<?= $key; ?>">View Profile

    <?php } ?>

<-- profile.php -->

Employee Profile : Employee Name

Back to Employee List

        Name
        Employee Position

<--fake_db.php-->
<?php

$employees = array
             (
               1 => array("name" => 'Jason Alipala', "employee_id" => 'G1001-05', 'position' => 1),
               2 => array("name" => 'Bryann Revina', "employee_id" => 'G1009-03', 'position' => 2),
               3 => array("name" => 'Jeniel Mangahis', "employee_id" => 'G1009-04', 'position' => 2),
               4 => array("name" => 'Arjay Bussala', "employee_id" => 'G1009-05', 'position' => 3),
               5 => array("name" => 'Ronnel Ines', "employee_id" => 'G1002-06', 'position' => 3)
             );

$emp_positions = array_count_values(array_column($employees, 'position'));

$positions = array(1 => 'TL', 2 => 'Programmer', 3 => 'Converter');

?>

Body:
Please replace profile.php to following.

<?php include_once('fake_db.php');
    $id = $_GET['id'];
    $employee = $employees[$id]
    ?>
<h3>Employee Profile : Employee Name</h3>
<a href="index.php">Back to Employee List</a>
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
    <thead>
    <tr>
        <td>Name </td>
        <td>Employee Position</td>
    </tr>
    </thead>
    <tr>

            <td><?php echo $employee['name'] ?></td>
            <td><?php echo $employee['position'] ?></td>
    </tr>
</table>


问:
Spring Boot always shows @Value annotation's value to be null
I have a small class in my Spring-Boot project in which I am getting the some values from the application.properties file. My class is in src/main/java/com/company/package folder and my application properties file in src/main/resources/application.properties. This is my class:

```<code>@Component
@Configuration
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

private String user;
private String password;

public ElasticConnection(@Value("${elasticsearch.user}")      String user,
                        @Value("${elasticsearch.password}") String password){
    this.user = user;
    this.password = password;
}
</code>```

I am Autowiring this class to the Application class:

```<code>@Configuration
@SpringBootApplication
public class ElasticApplication {

@Autowired
ElasticConnection elastic;

public static void main(String[] args) {

    SpringApplication.run(ElasticApplication.class, args);
}
</code>```

}

Now as soon as the constrctor of the ElasticConnection class is called user and password are set to null. I know the values are read properly because InteliJ is kind enough to show the value (until you click on @Value and shows the "${elasticsearch.user}" again)

EDIT: this is the application properties file.

```<code># App config
server.port=8070

 # Local ElasticSearch instance configuration
 elasticsearch.clustername = elasticsearch
 elasticsearch.host = localhost
 elasticsearch.port = 9300

 #spring.main.allow-bean-definition-overriding=true

 # Elasticsearch Settings
  elasticsearch.user=test
  elasticsearch.password=test
</code>```

答:
If we want to use the @Value annotation for a constructor argument we must not forget to add the @Autowired annotation on the constructor as well.So your code should be :

```<code>@Component
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

private String user;
private String password;

@Autowired
public ElasticConnection(@Value("${elasticsearch.user}")      String user,
                        @Value("${elasticsearch.password}") String password){
    this.user = user;
    this.password = password;
}
</code>```

This enables spring to use constructor injection for your fields.
Instead of injecting the values via the constructor you can also try the following in your code :

```<code>@Component
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

@Value("${elasticsearch.user}")
private String user;

@Value("${elasticsearch.password}")
private String password;

//setters and getters
}
</code>```

Or you can even use @ConfigurationProperties annotation to read values from the property files.

Related : Spring @Autowire on Properties vs Constructor

Body:
I have a small class in my Spring-Boot project in which I am getting the some values from the application.properties file. My class is in src/main/java/com/company/package folder and my application properties file in src/main/resources/application.properties. This is my class:

@Component
@Configuration
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

private String user;
private String password;

public ElasticConnection(@Value("${elasticsearch.user}")      String user,
                        @Value("${elasticsearch.password}") String password){
    this.user = user;
    this.password = password;
}

I am Autowiring this class to the Application class:

@Configuration
@SpringBootApplication
public class ElasticApplication {

@Autowired
ElasticConnection elastic;

public static void main(String[] args) {

    SpringApplication.run(ElasticApplication.class, args);
}

}

Now as soon as the constrctor of the ElasticConnection class is called user and password are set to null. I know the values are read properly because InteliJ is kind enough to show the value (until you click on @Value and shows the "${elasticsearch.user}" again)

EDIT: this is the application properties file.

# App config
server.port=8070

 # Local ElasticSearch instance configuration
 elasticsearch.clustername = elasticsearch
 elasticsearch.host = localhost
 elasticsearch.port = 9300

 #spring.main.allow-bean-definition-overriding=true

 # Elasticsearch Settings
  elasticsearch.user=test
  elasticsearch.password=test

Body:
If we want to use the @Value annotation for a constructor argument we must not forget to add the @Autowired annotation on the constructor as well.So your code should be :

@Component
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

private String user;
private String password;

@Autowired
public ElasticConnection(@Value("${elasticsearch.user}")      String user,
                        @Value("${elasticsearch.password}") String password){
    this.user = user;
    this.password = password;
}

This enables spring to use constructor injection for your fields.
Instead of injecting the values via the constructor you can also try the following in your code :

@Component
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

@Value("${elasticsearch.user}")
private String user;

@Value("${elasticsearch.password}")
private String password;

//setters and getters
}

Or you can even use @ConfigurationProperties annotation to read values from the property files.

Related : Spring @Autowire on Properties vs Constructor


问:
How i change the position more to the left in the navbar-toggler Bootstrap?
I intend to slightly change the navbar-toggler-icon more to the left and their respective menus as well. I have already tried to change the position in the css but this only changes the icon shown in the image and the menus are exactly the same. Could they help me? Thank you.

https://imgur.com/MZBGbCC

Code of the menu:

```<code><a href="#" id="scroll"><span></span></a>
<div class="menu">
    <nav class="navbar container-fluid navbar-expand-lg navbar transparent">
    <button class="navbar-toggler navbar-toggler-right" id="menu_colapso" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"><img src="conteudo/menu.png" id="imagem_icon"></span>
    </button>
    <a class="navbar-brand">
        <img src="conteudo/asus.png" class="collapse navbar-collapse" id="imagem_logo">
    </a>
    <div class="collapse navbar-collapse pr-5 mt-5" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">    <!--mr-auto para voltar ao lado esquerdo-->
            <li class="nav-item">
                <a class="nav-link" id="linhaactiva" href="inicio">Início</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="destaques">Destaques</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="museu">Museu</a>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Urgeiriça</a>
                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                <a class="dropdown-item" href="historia">Cronologia</a>
                <a class="dropdown-item" href="bairro">Bairro Mineiro</a>
                <a class="dropdown-item" href="minas">As Minas</a>
                <a class="dropdown-item" href="processamento">Processamento</a>
                <a class="dropdown-item" href="ambiental">Impactos Ambientais</a>
                <a class="dropdown-item" href="saude_publica">Saúde Pública</a>
                <a class="dropdown-item" href="recuperacao">Recuperação Ambiental</a>
                </div>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Mineiros</a>
                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                <a class="dropdown-item" href="laborais">Condições Laborais</a>
                <a class="dropdown-item" href="impacto_saude">Impacto na Saúde</a>
                <a class="dropdown-item" href="mural">Mural</a>
                </div>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Associação</a>
                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                <a class="dropdown-item" href="fundacao">Fundação</a>
                <a class="dropdown-item" href="objectivos">Objectivos</a>
                </div>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="informacoes">Informações </a>
            </li>
            <li class="nav-item">
                <a class="nav-link"> </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">PT</a>
            </li>
            <li class="nav-item2">
                <a class="nav-link" href="#">|</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">EN</a>
            </li>
        </ul>
    </div>
    </nav>
</div>
</code>```

答:
padding-left:0 is what you're looking for...

You can do it on the toggler... which moves it left a little (class: pullToLeft)

You can do it on the nav... which moves it left little more (class: pullNavLeft)

I replaced the image you had so that I and other people on stack overflow can see the effects in action; working snippet below:

.pullToLeft {
  padding-left: 0 !important;
}

.pullNavLeft {
  padding: .5rem .3rem !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<div class="menu">
  <nav class="navbar container-fluid navbar-expand-lg navbar transparent pullNavLeft">
    <button class="navbar-toggler navbar-toggler-right pullToLeft" id="menu_colapso" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"><img src="https://www.akberiqbal.com/favicon.ico" class='img-fluid ' id="imagem_icon"></span>
    </button>

      <img src="conteudo/asus.png" class="collapse navbar-collapse" id="imagem_logo">

    <div class="collapse navbar-collapse pr-5 mt-5" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <!--mr-auto para voltar ao lado esquerdo-->
        <li class="nav-item">
          Início
        </li>
        <li class="nav-item">
          Destaques
        </li>
        <li class="nav-item">
          Museu
        </li>
        <li class="nav-item dropdown">
          Urgeiriça
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            Cronologia
            Bairro Mineiro
            As Minas
            Processamento
            Impactos Ambientais
            Saúde Pública
            Recuperação Ambiental
          </div>
        </li>
        <li class="nav-item dropdown">
          Mineiros
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            Condições Laborais
            Impacto na Saúde
            Mural
          </div>
        </li>
        <li class="nav-item dropdown">
          Associação
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            Fundação
            Objectivos
          </div>
        </li>
        <li class="nav-item">
          Informações
        </li>
        <li class="nav-item">

        </li>
        <li class="nav-item">
          PT
        </li>
        <li class="nav-item2">
          |
        </li>
        <li class="nav-item">
          EN
        </li>
      </ul>
    </div>
  </nav>
</div>

<div class="container">
  <h3>Collapsible Navbar</h3>
  <p>In this example, the navigation bar is hidden on small screens and replaced by a button in the top right corner (try to re-size this window).</p>
  <p>Only when the button is clicked, the navigation bar will be displayed.</p>
  <p>Tip: You can also remove the .navbar-expand-md class to ALWAYS hide navbar links and display the toggler button.</p>
</div></code>```

Body:
I intend to slightly change the navbar-toggler-icon more to the left and their respective menus as well. I have already tried to change the position in the css but this only changes the icon shown in the image and the menus are exactly the same. Could they help me? Thank you.

https://imgur.com/MZBGbCC

Code of the menu:

    <button class="navbar-toggler navbar-toggler-right" id="menu_colapso" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Início

                Destaques

                Museu

                Urgeiriça

                Cronologia
                Bairro Mineiro
                As Minas
                Processamento
                Impactos Ambientais
                Saúde Pública
                Recuperação Ambiental

                Mineiros

                Condições Laborais
                Impacto na Saúde
                Mural

                Associação

                Fundação
                Objectivos

                Informações

                PT

                |

                EN

Body:
padding-left:0 is what you're looking for...

You can do it on the toggler... which moves it left a little (class: pullToLeft)

You can do it on the nav... which moves it left little more (class: pullNavLeft)

I replaced the image you had so that I and other people on stack overflow can see the effects in action; working snippet below:

.pullToLeft {
  padding-left: 0 !important;
}

.pullNavLeft {
  padding: .5rem .3rem !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<div class="menu">
  <nav class="navbar container-fluid navbar-expand-lg navbar transparent pullNavLeft">
    <button class="navbar-toggler navbar-toggler-right pullToLeft" id="menu_colapso" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"><img src="https://www.akberiqbal.com/favicon.ico" class='img-fluid ' id="imagem_icon"></span>
    </button>
    <a class="navbar-brand">
      <img src="conteudo/asus.png" class="collapse navbar-collapse" id="imagem_logo">
    </a>
    <div class="collapse navbar-collapse pr-5 mt-5" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <!--mr-auto para voltar ao lado esquerdo-->
        <li class="nav-item">
          <a class="nav-link" id="linhaactiva" href="inicio">Início</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="destaques">Destaques</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="museu">Museu</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Urgeiriça</a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="historia">Cronologia</a>
            <a class="dropdown-item" href="bairro">Bairro Mineiro</a>
            <a class="dropdown-item" href="minas">As Minas</a>
            <a class="dropdown-item" href="processamento">Processamento</a>
            <a class="dropdown-item" href="ambiental">Impactos Ambientais</a>
            <a class="dropdown-item" href="saude_publica">Saúde Pública</a>
            <a class="dropdown-item" href="recuperacao">Recuperação Ambiental</a>
          </div>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Mineiros</a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="laborais">Condições Laborais</a>
            <a class="dropdown-item" href="impacto_saude">Impacto na Saúde</a>
            <a class="dropdown-item" href="mural">Mural</a>
          </div>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Associação</a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="fundacao">Fundação</a>
            <a class="dropdown-item" href="objectivos">Objectivos</a>
          </div>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="informacoes">Informações </a>
        </li>
        <li class="nav-item">
          <a class="nav-link"> </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">PT</a>
        </li>
        <li class="nav-item2">
          <a class="nav-link" href="#">|</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">EN</a>
        </li>
      </ul>
    </div>
  </nav>
</div>

<div class="container">
  <h3>Collapsible Navbar</h3>
  <p>In this example, the navigation bar is hidden on small screens and replaced by a button in the top right corner (try to re-size this window).</p>
  <p>Only when the button is clicked, the navigation bar will be displayed.</p>
  <p>Tip: You can also remove the .navbar-expand-md class to ALWAYS hide navbar links and display the toggler button.</p>
</div>


问:
Difference between events and delegates and its respective applications
I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate.

Would you explain to me the differences and when to use which?  What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.

答:
Edit#1 When would you use delegates over events and vs.versa? Please state your real world experience with both, say in the production code.

When I design my own APIs, I define delegates which are passed as parameters to methods, or to the constructors of classes:

So that a method can implement a simple 'template method' pattern (as e.g. the Predicate and Action delegates are passed to the .Net generic collection classes)

Or so that the class can do a 'callback' (typically a callback to a method of the class which created it).

These delegates are generally non-optional at run-time (i.e. mustn't be null).

I tend not to use events; but where I do use events, I use them for optionally signalling events to zero, one, or more clients that might be interested, i.e. when it makes sense that a class (e.g. the System.Windows.Form class) should exist and run whether or not any client has added an event handler to its event (e.g. the form's 'mouse down' event exists, but it's optional whether any external client is interested in installing an event handler onto that event).

OwnerDisplayName: Sasha

LastEditorDisplayName: RoBorg

OwnerDisplayName: ChrisW

ContentLicense: CC BY-SA 2.5


问:
Updated Screen Sizes Chart
Google provides a chart of Android screen sizes, based on devices accessing the Android Market. Unfortunately, it's very old; it's from August 2010.

Is there somewhere I can find fresher data?

(Why do I ask? I'm pretty sure that the August chart is no longer accurate. It shows 45.9% of users having Normal/MDPI screens [i.e. 320x480 resolution], but there are almost no devices being sold in 2011 that have Normal/MDPI screens. Plus, the version chart updated in April 2011 indicates that over 90% of today's Android users have Android 2.x, but there are extremely few Normal/MDPI devices that support Android 2.x; most of them were stuck on Android 1.6.)

答: This isn't a direct answer, but I have some statistics that may be helpful as the screen sizes can be understood from the device.

Title: Updated Screen Sizes Chart


问:
ElasticSearch 6.6.0 Aggregation Avg with script not working
I have the following I am trying to run on my cluster:

```<code>GET _search
{
  "aggs": {
    "buckets": {
      "terms": {
        "field": "main_feature_id.keyword",
        "size": 10
      },
      "aggs": {
        "average_dwell": {
          "avg": {
            "field": "dwell.dwell_ms",
            "script": {
              "lang": "painless",
              "source": "long x = Math.round(_value*100)/100000; return x;"
            }
          }
        }
      }
    }
  }
}
</code>```

But no matter what I try I cannot get it to round the result.

Here is what the result looks like:

```<code>"doc_count" : 26032,
      "average_dwell" : {
        "value" : 44.87277178006528
      }
</code>```

Can someone please tell me what I am doing wrong I am sure it is something obvious.

Thank you!

答:
_value script applies the script on each value of the document and then calculates the average of the modified values. What you seem to achieve is to reduce the precision to two decimal places. This can be achieved by making use of bucket script aggregation to get the expected value.

```<code>{
  "aggs": {
    "buckets": {
      "terms": {
        "field": "main_feature_id.keyword",
        "size": 10
      },
      "aggs": {
        "average_dwell": {
          "avg": {
            "field": "dwell.dwell_ms"
          }
        },
        "rounded_avg": {
          "bucket_script": {
            "buckets_path": {
              "curr_avg": "average_dwell"
            },
            "script": "Math.round(params.curr_avg * 100)/100.0;"
          }
        }
      }
    }
  }
}
</code>```

Body:
I have the following I am trying to run on my cluster:

GET _search
{
  "aggs": {
    "buckets": {
      "terms": {
        "field": "main_feature_id.keyword",
        "size": 10
      },
      "aggs": {
        "average_dwell": {
          "avg": {
            "field": "dwell.dwell_ms",
            "script": {
              "lang": "painless",
              "source": "long x = Math.round(_value*100)/100000; return x;"
            }
          }
        }
      }
    }
  }
}

But no matter what I try I cannot get it to round the result.

Here is what the result looks like:

"doc_count" : 26032,
      "average_dwell" : {
        "value" : 44.87277178006528
      }

Can someone please tell me what I am doing wrong I am sure it is something obvious.

Thank you!

Body:
_value script applies the script on each value of the document and then calculates the average of the modified values. What you seem to achieve is to reduce the precision to two decimal places. This can be achieved by making use of bucket script aggregation to get the expected value.

{
  "aggs": {
    "buckets": {
      "terms": {
        "field": "main_feature_id.keyword",
        "size": 10
      },
      "aggs": {
        "average_dwell": {
          "avg": {
            "field": "dwell.dwell_ms"
          }
        },
        "rounded_avg": {
          "bucket_script": {
            "buckets_path": {
              "curr_avg": "average_dwell"
            },
            "script": "Math.round(params.curr_avg * 100)/100.0;"
          }
        }
      }
    }
  }
}