问:
C++ double free or corruption(out)
I came across this error when I was using iterators with vector STL.

Code:-

```<code>#include <iostream>
#include <vector>

void print_vec(std::vector<int> vec)
{
    auto itr = vec.begin();
    while (itr != vec.end())
        std::cout << *itr++ << " ";
    std::cout << std::endl;
}

int main(int argc, char* argv[])
{
    std::vector<int> vals = { 1, 2, 3, 4, 5, 6 };
    print_vec(vals);
    auto it = vals.begin();
    vals.insert(it, 100);
    print_vec(vals);
    it += 4;
    std::cout << *it << "\n";
    vals.insert(it, 200);
    print_vec(vals);
    return 0;
}
</code>```

Output:-

```<code>1 2 3 4 5 6
100 1 2 3 4 5 6
5
0 100 1 2 3 4 5 6
double free or corruption (out)
Aborted (core dumped)
</code>```

I do not understand why this is happening: is it an issue with the iterator after the vector is modified? I think that my intuition regarding iterators is flawed.

答:
When a std::vector is resized, the iterator becomes invalid because it refers to the vector before resizing which may include moving the vector to a different memory location in order to maintain a contiguity. In that case it will not be automatically updated to refer to the new location.

The result in this case (because it is undefined behaviour) is that the value 200 was not inserted in the vector, but it was written to some other heap memory that the vector previously occupied that has since been deallocated - i.e. you corrupted the heap.  The vector is destroyed on exit from main, and at that time the system heap management fails and the error is reported (after the fact).

Reassigning the iterator following the insertion resolves the issue:

```<code>it = vals.insert(it,100);
...
</code>```

The output of the single item reports 5 rather then 4 as you might expect because it is simply reading the old vector memory not yet reused and overwritten with something else.

You can observe the error by comparing:

```<code>vals.insert(it,100);
std::cout<<std::distance(it,vals.begin())<<'\n' ;
</code>```

with

```<code>it = vals.insert(it,100);
std::cout<<std::distance(it,vals.begin())<<'\n' ;
</code>```

Your results are likely to differ but at https://www.onlinegdb.com/ when I performed the test, the distance between the iterator position and the vector start in the first case was 16 - demonstrating that the iterator no longer refers to an element in the current vector state.  In the second case the distance is zero - the iterator refers to the start of the new vector state.

If the capacity of vals were extended before taking the iterator by for example:

```<code>vals.reserve(10);
</code>```

Then the insertion of a single element would not cause a mem-move, and the failure would not have occurred - that does not make it a good idea not to update the iterator though - it is merely to indicate what is happening under the hood.

Title: C++ double free or corruption(out)

Body:
I came across this error when I was using iterators with vector STL.

Code:-

#include <iostream>
#include <vector>

void print_vec(std::vector<int> vec)
{
    auto itr = vec.begin();
    while (itr != vec.end())
        std::cout << *itr++ << " ";
    std::cout << std::endl;
}

int main(int argc, char* argv[])
{
    std::vector<int> vals = { 1, 2, 3, 4, 5, 6 };
    print_vec(vals);
    auto it = vals.begin();
    vals.insert(it, 100);
    print_vec(vals);
    it += 4;
    std::cout << *it << "\n";
    vals.insert(it, 200);
    print_vec(vals);
    return 0;
}

Output:-

1 2 3 4 5 6
100 1 2 3 4 5 6
5
0 100 1 2 3 4 5 6
double free or corruption (out)
Aborted (core dumped)

I do not understand why this is happening: is it an issue with the iterator after the vector is modified? I think that my intuition regarding iterators is flawed.

Body:
When a std::vector is resized, the iterator becomes invalid because it refers to the vector before resizing which may include moving the vector to a different memory location in order to maintain a contiguity. In that case it will not be automatically updated to refer to the new location.

The result in this case (because it is undefined behaviour) is that the value 200 was not inserted in the vector, but it was written to some other heap memory that the vector previously occupied that has since been deallocated - i.e. you corrupted the heap.  The vector is destroyed on exit from main, and at that time the system heap management fails and the error is reported (after the fact).

Reassigning the iterator following the insertion resolves the issue:

it = vals.insert(it,100);
...

The output of the single item reports 5 rather then 4 as you might expect because it is simply reading the old vector memory not yet reused and overwritten with something else.

You can observe the error by comparing:

vals.insert(it,100);
std::cout<<std::distance(it,vals.begin())<<'\n' ;

with

it = vals.insert(it,100);
std::cout<<std::distance(it,vals.begin())<<'\n' ;

Your results are likely to differ but at https://www.onlinegdb.com/ when I performed the test, the distance between the iterator position and the vector start in the first case was 16 - demonstrating that the iterator no longer refers to an element in the current vector state.  In the second case the distance is zero - the iterator refers to the start of the new vector state.

If the capacity of vals were extended before taking the iterator by for example:

vals.reserve(10);

Then the insertion of a single element would not cause a mem-move, and the failure would not have occurred - that does not make it a good idea not to update the iterator though - it is merely to indicate what is happening under the hood.


来源: stackexchange

问:
glStencilOp -- GL_INCR_WRAP GL_DECR_WRAP. stencil mask behaviour
OpenGL documentation for glStencilOp isn't clear on what happens for increment and decrement operations in the presence of stencil masks.  It seems to imply that the mask will be ignored for increment and decrement operation.

Can anyone confirm/refute that?

Thanks

答: The mask will not be ignored. Instead, the increment or decrement operation is performed as though there was no mask, but the only bits in the stencil buffer that will be set to the incremented value are those allowed by the mask.</p>

ContentLicense: CC BY-SA 3.0


问:
In python how to delete a series of columns every nth element in a numpy 3d array?
Similar to this question, say I have a 3D Numpy array, above which I've added a comment label for clarity:

```<code>          #C  C  C  R  R  C  C  C  R  R  C  C  C
    a = [[[10,11,12,13,14,15,16,17,18,19,20,21,22],
          [23,24,25,26,27,28,29,30,31,32,33,34,35]],

         [[36,37,38,39,40,41,42,43,44,45,46,47,48],
          [48,49,50,51,52,53,54,55,56,57,58,59,60]],

         [[61,62,63,64,65,66,67,68,69,70,71,72,73],
          [74,75,76,77,78,79,80,81,82,83,84,85,86]]]
</code>```

can I delete the columns labelled R in one line of code? So delete two columns every fifth element starting at index 3. In this case, the resulting array would look like this:

```<code>          #C  C  C  C  C  C  C  C  C
    a = [[[10,11,12,15,16,17,20,21,22],
          [23,24,25,28,29,30,33,34,35]],

          [[36,37,38,41,42,43,46,47,48],
           [48,49,50,53,54,55,58,59,60]],

          [[61,62,63,66,67,68,71,72,73],
           [74,75,76,79,80,81,84,85,86]]]
</code>```

I'd like to make the code more generic so it can handle deleting pairs of columns in 3D arrays of varying sizes and locations. For this example, I can delete one column at a time using this:

```<code>    start = 3
    step = 5
    a = numpy.delete(big, numpy.s_[start:numpy.size(big, 2):step], 2)
    a = numpy.delete(a, numpy.s_[start:numpy.size(a, 2):step - 1], 2)
</code>```

But is there a way to specify a range of columns for deletion and so complete the task in one line of code?

ContentLicense: CC BY-SA 4.0

Body:
Similar to this question, say I have a 3D Numpy array, above which I've added a comment label for clarity:

          #C  C  C  R  R  C  C  C  R  R  C  C  C
    a = [[[10,11,12,13,14,15,16,17,18,19,20,21,22],
          [23,24,25,26,27,28,29,30,31,32,33,34,35]],

         [[36,37,38,39,40,41,42,43,44,45,46,47,48],
          [48,49,50,51,52,53,54,55,56,57,58,59,60]],

         [[61,62,63,64,65,66,67,68,69,70,71,72,73],
          [74,75,76,77,78,79,80,81,82,83,84,85,86]]]

can I delete the columns labelled R in one line of code? So delete two columns every fifth element starting at index 3. In this case, the resulting array would look like this:

          #C  C  C  C  C  C  C  C  C
    a = [[[10,11,12,15,16,17,20,21,22],
          [23,24,25,28,29,30,33,34,35]],

          [[36,37,38,41,42,43,46,47,48],
           [48,49,50,53,54,55,58,59,60]],

          [[61,62,63,66,67,68,71,72,73],
           [74,75,76,79,80,81,84,85,86]]]

I'd like to make the code more generic so it can handle deleting pairs of columns in 3D arrays of varying sizes and locations. For this example, I can delete one column at a time using this:

    start = 3
    step = 5
    a = numpy.delete(big, numpy.s_[start:numpy.size(big, 2):step], 2)
    a = numpy.delete(a, numpy.s_[start:numpy.size(a, 2):step - 1], 2)

But is there a way to specify a range of columns for deletion and so complete the task in one line of code?

Body:
Pretty similar to the linked posted answer there -

In [4]: a[...,np.mod(np.arange(a.shape[-1]),5)<3]
Out[4]:
array([[[10, 11, 12, 15, 16, 17, 20, 21, 22],
        [23, 24, 25, 28, 29, 30, 33, 34, 35]],

       [[36, 37, 38, 41, 42, 43, 46, 47, 48],
        [48, 49, 50, 53, 54, 55, 58, 59, 60]],

       [[61, 62, 63, 66, 67, 68, 71, 72, 73],
        [74, 75, 76, 79, 80, 81, 84, 85, 86]]])

Or shorter one -

a[...,(np.arange(a.shape[-1])%5)<3]

Making it generic/parameterize -

group_size = 5
ignore_size = 2
out = a[...,(np.arange(a.shape[-1])%group_size)<(group_size-ignore_size)]


问:
Geotools cannot find HSQL EPSG DB, throws error: NoSuchAuthorityCodeException
I am running Geotools inside of Apache Storm, and having a heck of a time with geotools dependency management. Every thing works when I run the storm cluster locally (windows 7 laptop), but when I deploy to the cluster I get this exception in my logs.

EDIT: Here is the Java I use that calls this functionality

```<code>      GridCoverage2D image =
new GeoTiffReader(f).read(new GeneralParameterValue[]{policy, gridsize, useJaiRead});
        /**
         * reproject to WGS84
         */
        CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
        GridCoverage2D reprojectedImage = (GridCoverage2D) Operations.DEFAULT.resample(image, targetCRS);
</code>```

Here's my environment

```<code>geotools 11.1
java 7
POM is below
running on windows 7 when in local mode (works perfectly here)
this problem happens on Ubuntu 12.04.5 LTS (GNU/Linux 3.2.0-63-virtual x86_64)

here's the exception from the log

[ERROR] Exception in Bolt org.geotools.data.DataSourceException: GEOTIFF Module Error Report
No code "EPSG:32637" from authority "EPSG" found for object of type "EngineeringCRS".
ModelPixelScaleTag: [2.0,2.0,0.0]
ModelTiePointTag: (1 tie points)
TP #0: [0.0,0.0,0.0] -> [337668.0,3837288.0,0.0]
ModelTransformationTag: NOT AVAILABLE
GeoKey #1: Key = 2049, Value = GCS_WGS_1984
GeoKey #2: Key = 2054, Value = 9102
GeoKey #3: Key = 3072, Value = 32637
GeoKey #4: Key = 1024, Value = 1
GeoKey #5: Key = 1025, Value = 1
GeoKey #6: Key = 1026, Value = PCS Name = WGS_1984_UTM_zone_37N
GeoKey #7: Key = 3076, Value = 9001
org.opengis.referencing.NoSuchAuthorityCodeException: No code "EPSG:32637" from authority "EPSG" found for object of type "EngineeringCRS".
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.noSuchAuthorityException(CartesianAuthorityFactory.java:136)
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.createEngineeringCRS(CartesianAuthorityFactory.java:130)
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.createCoordinateReferenceSystem(CartesianAuthorityFactory.java:121)
        at org.geotools.referencing.factory.AuthorityFactoryAdapter.createCoordinateReferenceSystem(AuthorityFactoryAdapter.java:802)
        at org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter.createProjectedCoordinateReferenceSystem(GeoTiffMetadata2CRSAdapter.java:284)
        at org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter.createCoordinateSystem(GeoTiffMetadata2CRSAdapter.java:205)
        at org.geotools.gce.geotiff.GeoTiffReader.getHRInfo(GeoTiffReader.java:299)
        at org.geotools.gce.geotiff.GeoTiffReader.<init>(GeoTiffReader.java:211)
        at org.geotools.gce.geotiff.GeoTiffReader.<init>(GeoTiffReader.java:156)
        at dgi.eii.utils.PixelExtractor.extract(PixelExtractor.java:80)
        at dgi.eii.storm.bolts.RasterPixelExtractorBolt.execute(RasterPixelExtractorBolt.java:59)
        at backtype.storm.daemon.executor$fn__5641$tuple_action_fn__5643.invoke(executor.clj:631)
        at backtype.storm.daemon.executor$mk_task_receiver$fn__5564.invoke(executor.clj:399)
        at backtype.storm.disruptor$clojure_handler$reify__745.onEvent(disruptor.clj:58)
        at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:125)
        at backtype.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:99)
        at backtype.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:80)
        at backtype.storm.daemon.executor$fn__5641$fn__5653$fn__5700.invoke(executor.clj:746)
        at backtype.storm.util$async_loop$fn__457.invoke(util.clj:431)
        at clojure.lang.AFn.run(AFn.java:24)
        at java.lang.Thread.run(Thread.java:745)
</code>```

I also get the same error when encountering an image with EPSQ:4326

```<code> [ERROR] Exception in Bolt org.geotools.data.DataSourceException: GEOTIFF Module Error Report
No code "EPSG:4326" from authority "EPSG" found for object of type "EngineeringCRS".
ModelPixelScaleTag: [2.0230196490091333E-5,2.0230196490071028E-5,0.0]
ModelTiePointTag: (1 tie points)
TP #0: [0.0,0.0,0.0] -> [36.8167576323252,34.429979601192464,0.0]
ModelTransformationTag: NOT AVAILABLE
GeoKey #1: Key = 2048, Value = 4326
GeoKey #2: Key = 2049, Value = GCS_WGS_1984
GeoKey #3: Key = 2054, Value = 9102
GeoKey #4: Key = 1024, Value = 2
GeoKey #5: Key = 2057, Value = 6378137.0
GeoKey #6: Key = 1025, Value = 1
GeoKey #7: Key = 2059, Value = 298.257223563
org.opengis.referencing.NoSuchAuthorityCodeException: No code "EPSG:4326" from authority "EPSG" found for object of type "EngineeringCRS".
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.noSuchAuthorityException(CartesianAuthorityFactory.java:136)
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.createEngineeringCRS(CartesianAuthorityFactory.java:130)
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.createCoordinateReferenceSystem(CartesianAuthorityFactory.java:121)
        at org.geotools.referencing.factory.AuthorityFactoryAdapter.createCoordinateReferenceSystem(AuthorityFactoryAdapter.java:802)
        at org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter.createGeographicCoordinateReferenceSystem(GeoTiffMetadata2CRSAdapter.java:389)
        at org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter.createCoordinateSystem(GeoTiffMetadata2CRSAdapter.java:208)
        at org.geotools.gce.geotiff.GeoTiffReader.getHRInfo(GeoTiffReader.java:299)
        at org.geotools.gce.geotiff.GeoTiffReader.<init>(GeoTiffReader.java:211)
        at org.geotools.gce.geotiff.GeoTiffReader.<init>(GeoTiffReader.java:156)
        at dgi.eii.utils.PixelExtractor.extract(PixelExtractor.java:80)
        at dgi.eii.storm.bolts.RasterPixelExtractorBolt.execute(RasterPixelExtractorBolt.java:59)
        at backtype.storm.daemon.executor$fn__5641$tuple_action_fn__5643.invoke(executor.clj:631)
        at backtype.storm.daemon.executor$mk_task_receiver$fn__5564.invoke(executor.clj:399)
        at backtype.storm.disruptor$clojure_handler$reify__745.onEvent(disruptor.clj:58)
        at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:125)
        at backtype.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:99)
        at backtype.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:80)
        at backtype.storm.daemon.executor$fn__5641$fn__5653$fn__5700.invoke(executor.clj:746)
        at backtype.storm.util$async_loop$fn__457.invoke(util.clj:431)
        at clojure.lang.AFn.run(AFn.java:24)
        at java.lang.Thread.run(Thread.java:745)
</code>```

I have seen several answers that indicated I need to put the gt-epsg-hsql in my pom, and I have, still doesn't find what it needs.

Here are my geotools POM entries

```<code> <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>11.1</version>
        </dependency>
         <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-opengis</artifactId>
            <version>11.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-epsg-hsql</artifactId>
            <version>11.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geotiff</artifactId>
            <version>11.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-image</artifactId>
            <version>11.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-wms</artifactId>
            <version>11.1</version>
        </dependency>
</code>```

here is how I am building the uber-jar with maven shade plugin

```<code> <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <archive>
                        <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
                    </archive>
                    <!--  <minimizeJar>true</minimizeJar>-->
                    <shadedArtifactAttached>true</shadedArtifactAttached>
                    <shadedClassifierName>stand-alone</shadedClassifierName>
                    <artifactSet>
                        <excludes>
                            <exclude>org.slf4j:slf4j-api:jar:</exclude>
                            <exclude>org.slf4j:slf4j-simple:jar:1.6.4:jar:</exclude>
                            <exclude>org.slf4j:slf4j-log4j12:jar:</exclude>
                            <exclude>org.slf4j:jcl-over-slf4j:jar:</exclude>
                            <exclude>org.slf4j:slf4j-api:jar:1.7.5:jar:</exclude>
                            <!-- <exclude>org.slf4j*:</exclude>-->
                            <exclude>commons-logging:commons-logging:jar:</exclude>
                            <exclude>commons-logging:commons-logging-api:jar:</exclude>
                        </excludes>
                    </artifactSet>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                    <finalName>storm-topos</finalName>
                    <transformers>
                        <transformer
                            implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            <mainClass>dgi.eii.storm.base.StormTopologyRunner</mainClass>
                        </transformer>
                       <!-- <transformer
                            implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.handlers</resource>
                        </transformer>
                        <transformer
                            implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.schemas</resource>
                        </transformer>-->
                    </transformers>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

EDIT:
So i figured out a few things and got a little further... now getting this error

```<code>[ERROR] Exception in Bolt org.geotools.data.DataSourceException: org.hsqldb.DatabaseURL.parseURL(Ljava/lang/String;ZZ)Lorg/hsqldb/persist/HsqlProperties;
</code>```

This slight advancement that led to the above new error was due to using the right transformers, and using the maven jar plugin to inject the right entries into the MANIFEST.MF file. Here is the new build section of my POM, which might help someone at least overcome the consolidation of geotools' META-INF/services files and to inject the right entries to overcome the old vendorname cannot be null! error

```<code><build>
    <resources>
        <resource>
            <directory>${basedir}/src/main/resources</directory>
            <filtering>false</filtering>
            <includes>
                <include>schema.xsd</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <shadedClassifierName>stand-alone</shadedClassifierName>
                <artifactSet>
                    <excludes>
                        <exclude>org.slf4j:slf4j-api:jar:</exclude>
                        <exclude>org.slf4j:slf4j-log4j12:jar:</exclude>
                        <exclude>org.slf4j:jcl-over-slf4j:jar:</exclude>

                        <exclude>commons-logging:commons-logging:jar:</exclude>
                        <exclude>commons-logging:commons-logging-api:jar:</exclude>
                    </excludes>
                </artifactSet>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
                <finalName>insightcloud-storm-topos</finalName>
                <transformers>
                    <transformer
                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>dgi.eii.storm.base.StormTopologyRunner</mainClass>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>

                    <transformer
                        implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.handlers</resource>
                    </transformer>
                    <transformer
                        implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.schemas</resource>
                    </transformer>
                </transformers>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
                </archive>
            </configuration>
        </plugin>
    </plugins>

</build>
</code>```

答:
I had this problem when using a Maven dependency (Matsim) which used geotools, while I was not using geotools in my project directly.  I was building a 'fat' jar using the maven-shade-plugin .

The solution was simply to add a transformer to the shade plugin configuration (as cello mentions at the bottom of his answer).

```<code><transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
</code>```

Body:
I am running Geotools inside of Apache Storm, and having a heck of a time with geotools dependency management. Every thing works when I run the storm cluster locally (windows 7 laptop), but when I deploy to the cluster I get this exception in my logs.

EDIT: Here is the Java I use that calls this functionality

      GridCoverage2D image =
new GeoTiffReader(f).read(new GeneralParameterValue[]{policy, gridsize, useJaiRead});
        /**
         * reproject to WGS84
         */
        CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
        GridCoverage2D reprojectedImage = (GridCoverage2D) Operations.DEFAULT.resample(image, targetCRS);

Here's my environment

geotools 11.1
java 7
POM is below
running on windows 7 when in local mode (works perfectly here)
this problem happens on Ubuntu 12.04.5 LTS (GNU/Linux 3.2.0-63-virtual x86_64)

here's the exception from the log

[ERROR] Exception in Bolt org.geotools.data.DataSourceException: GEOTIFF Module Error Report
No code "EPSG:32637" from authority "EPSG" found for object of type "EngineeringCRS".
ModelPixelScaleTag: [2.0,2.0,0.0]
ModelTiePointTag: (1 tie points)
TP #0: [0.0,0.0,0.0] -> [337668.0,3837288.0,0.0]
ModelTransformationTag: NOT AVAILABLE
GeoKey #1: Key = 2049, Value = GCS_WGS_1984
GeoKey #2: Key = 2054, Value = 9102
GeoKey #3: Key = 3072, Value = 32637
GeoKey #4: Key = 1024, Value = 1
GeoKey #5: Key = 1025, Value = 1
GeoKey #6: Key = 1026, Value = PCS Name = WGS_1984_UTM_zone_37N
GeoKey #7: Key = 3076, Value = 9001
org.opengis.referencing.NoSuchAuthorityCodeException: No code "EPSG:32637" from authority "EPSG" found for object of type "EngineeringCRS".
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.noSuchAuthorityException(CartesianAuthorityFactory.java:136)
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.createEngineeringCRS(CartesianAuthorityFactory.java:130)
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.createCoordinateReferenceSystem(CartesianAuthorityFactory.java:121)
        at org.geotools.referencing.factory.AuthorityFactoryAdapter.createCoordinateReferenceSystem(AuthorityFactoryAdapter.java:802)
        at org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter.createProjectedCoordinateReferenceSystem(GeoTiffMetadata2CRSAdapter.java:284)
        at org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter.createCoordinateSystem(GeoTiffMetadata2CRSAdapter.java:205)
        at org.geotools.gce.geotiff.GeoTiffReader.getHRInfo(GeoTiffReader.java:299)
        at org.geotools.gce.geotiff.GeoTiffReader.<init>(GeoTiffReader.java:211)
        at org.geotools.gce.geotiff.GeoTiffReader.<init>(GeoTiffReader.java:156)
        at dgi.eii.utils.PixelExtractor.extract(PixelExtractor.java:80)
        at dgi.eii.storm.bolts.RasterPixelExtractorBolt.execute(RasterPixelExtractorBolt.java:59)
        at backtype.storm.daemon.executor$fn__5641$tuple_action_fn__5643.invoke(executor.clj:631)
        at backtype.storm.daemon.executor$mk_task_receiver$fn__5564.invoke(executor.clj:399)
        at backtype.storm.disruptor$clojure_handler$reify__745.onEvent(disruptor.clj:58)
        at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:125)
        at backtype.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:99)
        at backtype.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:80)
        at backtype.storm.daemon.executor$fn__5641$fn__5653$fn__5700.invoke(executor.clj:746)
        at backtype.storm.util$async_loop$fn__457.invoke(util.clj:431)
        at clojure.lang.AFn.run(AFn.java:24)
        at java.lang.Thread.run(Thread.java:745)

I also get the same error when encountering an image with EPSQ:4326

 [ERROR] Exception in Bolt org.geotools.data.DataSourceException: GEOTIFF Module Error Report
No code "EPSG:4326" from authority "EPSG" found for object of type "EngineeringCRS".
ModelPixelScaleTag: [2.0230196490091333E-5,2.0230196490071028E-5,0.0]
ModelTiePointTag: (1 tie points)
TP #0: [0.0,0.0,0.0] -> [36.8167576323252,34.429979601192464,0.0]
ModelTransformationTag: NOT AVAILABLE
GeoKey #1: Key = 2048, Value = 4326
GeoKey #2: Key = 2049, Value = GCS_WGS_1984
GeoKey #3: Key = 2054, Value = 9102
GeoKey #4: Key = 1024, Value = 2
GeoKey #5: Key = 2057, Value = 6378137.0
GeoKey #6: Key = 1025, Value = 1
GeoKey #7: Key = 2059, Value = 298.257223563
org.opengis.referencing.NoSuchAuthorityCodeException: No code "EPSG:4326" from authority "EPSG" found for object of type "EngineeringCRS".
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.noSuchAuthorityException(CartesianAuthorityFactory.java:136)
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.createEngineeringCRS(CartesianAuthorityFactory.java:130)
        at org.geotools.referencing.factory.epsg.CartesianAuthorityFactory.createCoordinateReferenceSystem(CartesianAuthorityFactory.java:121)
        at org.geotools.referencing.factory.AuthorityFactoryAdapter.createCoordinateReferenceSystem(AuthorityFactoryAdapter.java:802)
        at org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter.createGeographicCoordinateReferenceSystem(GeoTiffMetadata2CRSAdapter.java:389)
        at org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter.createCoordinateSystem(GeoTiffMetadata2CRSAdapter.java:208)
        at org.geotools.gce.geotiff.GeoTiffReader.getHRInfo(GeoTiffReader.java:299)
        at org.geotools.gce.geotiff.GeoTiffReader.<init>(GeoTiffReader.java:211)
        at org.geotools.gce.geotiff.GeoTiffReader.<init>(GeoTiffReader.java:156)
        at dgi.eii.utils.PixelExtractor.extract(PixelExtractor.java:80)
        at dgi.eii.storm.bolts.RasterPixelExtractorBolt.execute(RasterPixelExtractorBolt.java:59)
        at backtype.storm.daemon.executor$fn__5641$tuple_action_fn__5643.invoke(executor.clj:631)
        at backtype.storm.daemon.executor$mk_task_receiver$fn__5564.invoke(executor.clj:399)
        at backtype.storm.disruptor$clojure_handler$reify__745.onEvent(disruptor.clj:58)
        at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:125)
        at backtype.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:99)
        at backtype.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:80)
        at backtype.storm.daemon.executor$fn__5641$fn__5653$fn__5700.invoke(executor.clj:746)
        at backtype.storm.util$async_loop$fn__457.invoke(util.clj:431)
        at clojure.lang.AFn.run(AFn.java:24)
        at java.lang.Thread.run(Thread.java:745)

I have seen several answers that indicated I need to put the gt-epsg-hsql in my pom, and I have, still doesn't find what it needs.

Here are my geotools POM entries

 <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>11.1</version>
        </dependency>
         <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-opengis</artifactId>
            <version>11.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-epsg-hsql</artifactId>
            <version>11.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geotiff</artifactId>
            <version>11.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-image</artifactId>
            <version>11.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-wms</artifactId>
            <version>11.1</version>
        </dependency>

here is how I am building the uber-jar with maven shade plugin

 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <archive>
                        <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
                    </archive>

                    <shadedArtifactAttached>true</shadedArtifactAttached>
                    <shadedClassifierName>stand-alone</shadedClassifierName>
                    <artifactSet>
                        <excludes>
                            <exclude>org.slf4j:slf4j-api:jar:</exclude>
                            <exclude>org.slf4j:slf4j-simple:jar:1.6.4:jar:</exclude>
                            <exclude>org.slf4j:slf4j-log4j12:jar:</exclude>
                            <exclude>org.slf4j:jcl-over-slf4j:jar:</exclude>
                            <exclude>org.slf4j:slf4j-api:jar:1.7.5:jar:</exclude>

                            <exclude>commons-logging:commons-logging:jar:</exclude>
                            <exclude>commons-logging:commons-logging-api:jar:</exclude>
                        </excludes>
                    </artifactSet>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                    <finalName>storm-topos</finalName>
                    <transformers>
                        <transformer
                            implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            <mainClass>dgi.eii.storm.base.StormTopologyRunner</mainClass>
                        </transformer>

                    </transformers>
                </configuration>
            </plugin>
        </plugins>
    </build>

EDIT:
So i figured out a few things and got a little further... now getting this error

[ERROR] Exception in Bolt org.geotools.data.DataSourceException: org.hsqldb.DatabaseURL.parseURL(Ljava/lang/String;ZZ)Lorg/hsqldb/persist/HsqlProperties;

This slight advancement that led to the above new error was due to using the right transformers, and using the maven jar plugin to inject the right entries into the MANIFEST.MF file. Here is the new build section of my POM, which might help someone at least overcome the consolidation of geotools' META-INF/services files and to inject the right entries to overcome the old vendorname cannot be null! error

<build>
    <resources>
        <resource>
            <directory>${basedir}/src/main/resources</directory>
            <filtering>false</filtering>
            <includes>
                <include>schema.xsd</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <shadedClassifierName>stand-alone</shadedClassifierName>
                <artifactSet>
                    <excludes>
                        <exclude>org.slf4j:slf4j-api:jar:</exclude>
                        <exclude>org.slf4j:slf4j-log4j12:jar:</exclude>
                        <exclude>org.slf4j:jcl-over-slf4j:jar:</exclude>

                        <exclude>commons-logging:commons-logging:jar:</exclude>
                        <exclude>commons-logging:commons-logging-api:jar:</exclude>
                    </excludes>
                </artifactSet>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
                <finalName>insightcloud-storm-topos</finalName>
                <transformers>
                    <transformer
                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>dgi.eii.storm.base.StormTopologyRunner</mainClass>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>

                    <transformer
                        implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.handlers</resource>
                    </transformer>
                    <transformer
                        implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.schemas</resource>
                    </transformer>
                </transformers>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
                </archive>
            </configuration>
        </plugin>
    </plugins>

</build>

Body:
I had this problem when using a Maven dependency (Matsim) which used geotools, while I was not using geotools in my project directly.  I was building a 'fat' jar using the maven-shade-plugin .

The solution was simply to add a transformer to the shade plugin configuration (as cello mentions at the bottom of his answer).

<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />


问:
C++: Using a single get function to return the variables related to an object
I am a novice programmer working on a coding project for school.

The problem domain is as follows:

Write a C++ program related to a clock

Define a class called Clock , saved in a separate file, that includes the following members:

three member variables related to the hours, minutes and seconds

one accessor function that returns the values of the three variables (hint: use pointers)

one mutator function that modifies all variables (hint: use three arguments)

functions to increment each variable with 1 (hint: three function)

overloading functions to increment the variables with a value entered by the user (hint: the value is the argument of the function)

one default constructor that sets the clock to 0 hours, 0 minutes and 0 seconds

an overloading constructor that sets the clock to a given time (hr, min, sec)

Define a second class, saved in a separate file, that includes

a static member variable

a static member function

Include in the previously defined files C++ code that insures that a class will not be loaded twice in the main program

Define a main program, saved in a separate file, that

instantiates three objects, one with the default constructor of Clock, one with the overloaded constructor of Clock, and one based on the second class

uses the objects to call all the functions defined in the two classes:

use several ”cin” statement to read from the user the desired time and use the values as parameters for the corresponding functions that required

call each function only once, using one of the defined objects

use the accessor function to print the time after each function call that modifies the variables of the Clock class

includes code that uses the static members of the second class

we have done many examples in class where we are able to use separate get\set functions but this is the first time we are trying to do this with a single get function and pointers. Quite frankly, I am lost

Here is the contents of my header file:

```<code>// default class definition
#ifndef CLOCK1_H
#define CLOCK1_H

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Clock
{
private:
    int hours;
    int minutes;
    int seconds;

public:
    int Clock::getInitialTime();
    int Clock::setClockTime();
    Clock::Clock();             // default constructor
    Clock::~Clock();                // default destructor
};
#endif
</code>```

Here is the contents of my source code file:

```<code>// function declarations \ main program
//

#include "stdafx.h"
#include "Clock1.h"
#include <iostream>
#include <conio.h>
using namespace std;

int Clock::getInitialTime()
{
    return hours, minutes, seconds;
}

//void Clock::setClockTime(int hr,min,sec)
//{
//  hours=hr;
//  minutes=min;
//  seconds=sec;
//}

// default constructor
Clock::Clock()
{
    hours=0;
    minutes=0;
    seconds=0;
}

// default destructor
Clock::~Clock()
{
    cin.get();
    cin.get();
}

int main()
{
    Clock defaultObj;
    defaultObj.getInitialTime();
    cout << "The initial time is " << defaultObj.getInitialTime() << endl;
    return 0;
}
</code>```

I am trying to take this in small steps, the first goal being to be able to output the initial values for the hours, minutes, seconds. once this is done, I can add additional constructor(s) with additional arguments.

My first guess is that I need to add the following:

Constructor:
add the appropriate arguments to the default constructor

```<code>Clock::Clock(int *hourPrt, int *minutePtr, int *secondPrt)
</code>```

create the pointers

```<code>Clock *hourPtr;
Clock *minutePtr;
Clock *secondPtr;
</code>```

associate them with the object's attributes

```<code>hourPrt=defaultObj.hours
minutePtr=defaultObj.minutes
secondPrt=defaultObj.seconds
</code>```

getInitialTime function
modify it some how

function call in main
modify it some how

Can anyone help me with this?

Thanks

答:
The constructor is not one of the functions you need to change.  Start by writing void Clock::setClockTime(int hours, int minutes, int seconds), it's the easiest.

Please also note that you do not prefix member functions with the class name when inside the class.

```<code>class Clock
{
public:
    Clock::Clock();             // WRONG
    Clock(); // RIGHT way to declare constructor
};
</code>```

Body:
I am a novice programmer working on a coding project for school.

The problem domain is as follows:

Write a C++ program related to a clock

Define a class called Clock , saved in a separate file, that includes the following members:

three member variables related to the hours, minutes and seconds

one accessor function that returns the values of the three variables (hint: use pointers)

one mutator function that modifies all variables (hint: use three arguments)

functions to increment each variable with 1 (hint: three function)

overloading functions to increment the variables with a value entered by the user (hint: the value is the argument of the function)

one default constructor that sets the clock to 0 hours, 0 minutes and 0 seconds

an overloading constructor that sets the clock to a given time (hr, min, sec)

Define a second class, saved in a separate file, that includes

a static member variable

a static member function

Include in the previously defined files C++ code that insures that a class will not be loaded twice in the main program

Define a main program, saved in a separate file, that

instantiates three objects, one with the default constructor of Clock, one with the overloaded constructor of Clock, and one based on the second class

uses the objects to call all the functions defined in the two classes:

use several ”cin” statement to read from the user the desired time and use the values as parameters for the corresponding functions that required

call each function only once, using one of the defined objects

use the accessor function to print the time after each function call that modifies the variables of the Clock class

includes code that uses the static members of the second class

we have done many examples in class where we are able to use separate get\set functions but this is the first time we are trying to do this with a single get function and pointers. Quite frankly, I am lost

Here is the contents of my header file:

// default class definition
#ifndef CLOCK1_H
#define CLOCK1_H

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Clock
{
private:
    int hours;
    int minutes;
    int seconds;

public:
    int Clock::getInitialTime();
    int Clock::setClockTime();
    Clock::Clock();             // default constructor
    Clock::~Clock();                // default destructor
};
#endif

Here is the contents of my source code file:

// function declarations \ main program
//

#include "stdafx.h"
#include "Clock1.h"
#include <iostream>
#include <conio.h>
using namespace std;

int Clock::getInitialTime()
{
    return hours, minutes, seconds;
}

//void Clock::setClockTime(int hr,min,sec)
//{
//  hours=hr;
//  minutes=min;
//  seconds=sec;
//}

// default constructor
Clock::Clock()
{
    hours=0;
    minutes=0;
    seconds=0;
}

// default destructor
Clock::~Clock()
{
    cin.get();
    cin.get();
}

int main()
{
    Clock defaultObj;
    defaultObj.getInitialTime();
    cout << "The initial time is " << defaultObj.getInitialTime() << endl;
    return 0;
}

I am trying to take this in small steps, the first goal being to be able to output the initial values for the hours, minutes, seconds. once this is done, I can add additional constructor(s) with additional arguments.

My first guess is that I need to add the following:

Constructor:
add the appropriate arguments to the default constructor

Clock::Clock(int *hourPrt, int *minutePtr, int *secondPrt)

create the pointers

Clock *hourPtr;
Clock *minutePtr;
Clock *secondPtr;

associate them with the object's attributes

hourPrt=defaultObj.hours
minutePtr=defaultObj.minutes
secondPrt=defaultObj.seconds

getInitialTime function
modify it some how

function call in main
modify it some how

Can anyone help me with this?

Thanks

Body:
The constructor is not one of the functions you need to change.  Start by writing void Clock::setClockTime(int hours, int minutes, int seconds), it's the easiest.

Please also note that you do not prefix member functions with the class name when inside the class.

class Clock
{
public:
    Clock::Clock();             // WRONG
    Clock(); // RIGHT way to declare constructor
};


问:
Creating HTML Lists Purely in CSS
Trying to make it easy for a disabled friend to enter content into the site that I created for him without excessive typing, is there some way in CSS to create bulleted and ordered lists using existing line breaks or tabs rather than putting in list elements? These examples are for unordered but ordered is also needed.

For example, this:

```<code><div class="Unordered"><br />
    List item 1<br />
    List item 2<br />
    List item 3<br />
</div>
</code>```

. . . with the br coming from nl2br() and CSS something like this?

```<code>.Unordered {
    margin: auto;
    display: flex;
    flex-direction: row;
    width: 100%;
    text-align: center;
}

.Unordered br {
    list-style-type: disc;
}
</code>```

I'm trying to produce a list with the visual appearance created by a regular list like this:

```<code><ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
</ul>
</code>```

I am not adverse to doing this using PHP either.

答:
You can approximate this using background coloration where you have control over the height of each line by setting line-height

.Unordered {
   padding-left:20px;
   margin:10px;
   line-height:1.2em;
   background:
    radial-gradient(circle 0.3em,#000 86%,transparent 100%) 0 0/20px 1.2em repeat-y;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Unordered">
    List item 1<br>
    List item 2<br>
    List item 3<br>
</div>

<div class="Unordered">
    List item 1<br>
    List item 2<br>
    List item 3<br>
    List item 4<br>
    List item 5<br>
</div></code>```

Or like below if you are able to consider a different tag for the line break than

.Unordered,
.Ordered{
   padding-left:20px;
   margin:10px;
   counter-reset:num;
}
/*Line break*/
.Unordered z::before,
.Ordered z::before{
   content:"\A";
   white-space:pre;
}
/*bullet*/
.Unordered z::after {
   content:"•";
}
/*numver*/
.Ordered z::after {
   content:counter(num) ".";
   counter-increment:num;
}
.Unordered z:last-of-type,
.Ordered z:last-of-type{
  display:none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Unordered"><z></z>
    List item 1<z></z>
    List item 2<z></z>
    List item 3<z></z>
</div>

<div class="Ordered"><z></z>
    List item 1<z></z>
    List item 2<z></z>
    List item 3<z></z>
    List item 4<z></z>
    List item 5<z></z>
</div></code>```

Another hacky idea (I insist on hacky)

.Unordered,
.Ordered{
   padding-left:20px;
   margin:10px;
   line-height:1.2em;
   position:relative;
   overflow:hidden;
}
.Unordered:before{
  content:"";
  position:absolute;
  top:1.2em;
  bottom:0;
  left:0;
  right:0;
   background:
    radial-gradient(circle 0.3em,#000 86%,transparent 100%) 0 0/20px 1.2em repeat-y;
}
.Ordered:before{
  content:"1 2 3 4 5 7 8 9 10 11 12 13 14 15 16 17 18 19 20";  /*yes manually write them all !!*/
  position:absolute;
  top:1.2em;
  bottom:0;
  left:0;
  width:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Unordered"><br>
    List item 1<br>
    List item 2<br>
    List item 3<br>
</div>

<div class="Ordered"><br>
    List item 1<br>
    List item 2<br>
    List item 3<br>
    List item 4<br>
    List item 5<br>
</div></code>```

Title: Creating HTML Lists Purely in CSS

Body:
Trying to make it easy for a disabled friend to enter content into the site that I created for him without excessive typing, is there some way in CSS to create bulleted and ordered lists using existing line breaks or tabs rather than putting in list elements? These examples are for unordered but ordered is also needed.

For example, this:

    List item 1

    List item 2

    List item 3

. . . with the br coming from nl2br() and CSS something like this?

.Unordered {
    margin: auto;
    display: flex;
    flex-direction: row;
    width: 100%;
    text-align: center;
}

.Unordered br {
    list-style-type: disc;
}

I'm trying to produce a list with the visual appearance created by a regular list like this:

List item 1

List item 2

List item 3

I am not adverse to doing this using PHP either.

Body:
You can approximate this using background coloration where you have control over the height of each line by setting line-height

.Unordered {
   padding-left:20px;
   margin:10px;
   line-height:1.2em;
   background:
    radial-gradient(circle 0.3em,#000 86%,transparent 100%) 0 0/20px 1.2em repeat-y;
}

<div class="Unordered">
    List item 1<br>
    List item 2<br>
    List item 3<br>
</div>

<div class="Unordered">
    List item 1<br>
    List item 2<br>
    List item 3<br>
    List item 4<br>
    List item 5<br>
</div>

Or like below if you are able to consider a different tag for the line break than <br>

.Unordered,
.Ordered{
   padding-left:20px;
   margin:10px;
   counter-reset:num;
}
/*Line break*/
.Unordered z::before,
.Ordered z::before{
   content:"\A";
   white-space:pre;
}
/*bullet*/
.Unordered z::after {
   content:"•";
}
/*numver*/
.Ordered z::after {
   content:counter(num) ".";
   counter-increment:num;
}
.Unordered z:last-of-type,
.Ordered z:last-of-type{
  display:none;
}

<div class="Unordered"><z></z>
    List item 1<z></z>
    List item 2<z></z>
    List item 3<z></z>
</div>

<div class="Ordered"><z></z>
    List item 1<z></z>
    List item 2<z></z>
    List item 3<z></z>
    List item 4<z></z>
    List item 5<z></z>
</div>

Another hacky idea (I insist on hacky)

.Unordered,
.Ordered{
   padding-left:20px;
   margin:10px;
   line-height:1.2em;
   position:relative;
   overflow:hidden;
}
.Unordered:before{
  content:"";
  position:absolute;
  top:1.2em;
  bottom:0;
  left:0;
  right:0;
   background:
    radial-gradient(circle 0.3em,#000 86%,transparent 100%) 0 0/20px 1.2em repeat-y;
}
.Ordered:before{
  content:"1 2 3 4 5 7 8 9 10 11 12 13 14 15 16 17 18 19 20";  /*yes manually write them all !!*/
  position:absolute;
  top:1.2em;
  bottom:0;
  left:0;
  width:0;
}

<div class="Unordered"><br>
    List item 1<br>
    List item 2<br>
    List item 3<br>
</div>

<div class="Ordered"><br>
    List item 1<br>
    List item 2<br>
    List item 3<br>
    List item 4<br>
    List item 5<br>
</div>


问:
C - remove students from an array(array of structure) except 10 with the highest average grade
Hello everyone and thanks for taking your time to read this. I am practicing C and I have come upon an exercise I have not been able to solve for several days, no matter what I do.

The exercise says that I am given two structures Student and Grade. I am to create a function which accepts an array of students as a parameter and removes all students except 10 with the highest average grade. There are two restrictions: I cannot create any arrays and I cannot sort the given array.

What I have tried: I have created a for loop which iterates from 0 to size-10 and to remove students one by one starting with the one with the lowest average grade, so in the end, I am left with 10 with the highest average grade.

I have auxiliary functions: average calculates the average grade of one student;

index_lowest finds the index of the student to be removed

the function top_students is the main function that does what the exercise says.

Here is my program:

```<code>struct Grade {
    char subject_name[100];
    int grade;
};

struct Student {
    char name[20], surname[20];
    int no_of_grades;
    struct Grade grades[100];
};

double average(struct Student s) {
    int i;
    double avg = 0;
    for (i = 0; i < s.no_of_grades; i++) {
        avg += s.grades[i].grade;
    }
    return avg / s.no_of_grades;
}

int index_lowest(struct Student students[], int size) { // returns the index of the student with the lowest avg
    double min = average(students[0]);

    int i, mini = 0; // mini is the index we search for

    for (i = 0; i < size; i++) {
        if (average(students[i]) < min) {
            min = average(students[i]);
            mini = i;
        }
    }
    return mini;
}

void top_students(struct Student students[], int size) {
    int i, j;

    for (i = 0; i < (size - 10); i++) {
        int index = index_lowest(students, size);

        for (j = index; j < (size - 1); j++) {
            students[j] = students[j + 1];
        }
        size--;
    }
}
</code>```

答:
The test of the outer loop of top_student is incorrect: you increase i and reduce size at each iteration, hence you stop too soon.

Here is simplified version:

void top_students(struct Student students[], int size) {
    while (size > 10) {
        for (int j = index_lowest(students, size); j < size - 1; j++) {
            students[j] = students[j + 1];
        }
        size--;
    }
}
```

<p>Note also that passing large structures by value is inefficient. Passing a pointer is much preferred. Computing <code>average()</code> just once per iteration is also advisable.</p>

<p>Here is a modified version:</p>

```double average(const struct Student *s) {
    int i, n;
    double avg = 0.0;
    for (i = 0, n = s->no_of_grades; i < n; i++) {
        avg += s->grades[i].grade;
    }
    return avg / n;
}

int index_lowest(const struct Student students[], int size) {
    // returns the index of the student with the lowest avegare
    // in case of ties, return the last index for the lowest average
    double min = average(&students[0]);
    int i, mini = 0; // mini is the index we search for

    for (i = 1; i < size; i++) {
        double avg = average(&students[i]);
        if (avg <= min) {
            min = avg;
            mini = i;
        }
    }
    return mini;
}
```

Body:
Hello everyone and thanks for taking your time to read this. I am practicing C and I have come upon an exercise I have not been able to solve for several days, no matter what I do.

The exercise says that I am given two structures Student and Grade. I am to create a function which accepts an array of students as a parameter and removes all students except 10 with the highest average grade. There are two restrictions: I cannot create any arrays and I cannot sort the given array.

What I have tried: I have created a for loop which iterates from 0 to size-10 and to remove students one by one starting with the one with the lowest average grade, so in the end, I am left with 10 with the highest average grade.

I have auxiliary functions: average calculates the average grade of one student;

index_lowest finds the index of the student to be removed

the function top_students is the main function that does what the exercise says.

Here is my program:

struct Grade {
    char subject_name[100];
    int grade;
};

struct Student {
    char name[20], surname[20];
    int no_of_grades;
    struct Grade grades[100];
};

double average(struct Student s) {
    int i;
    double avg = 0;
    for (i = 0; i < s.no_of_grades; i++) {
        avg += s.grades[i].grade;
    }
    return avg / s.no_of_grades;
}

int index_lowest(struct Student students[], int size) { // returns the index of the student with the lowest avg
    double min = average(students[0]);

    int i, mini = 0; // mini is the index we search for

    for (i = 0; i < size; i++) {
        if (average(students[i]) < min) {
            min = average(students[i]);
            mini = i;
        }
    }
    return mini;
}

void top_students(struct Student students[], int size) {
    int i, j;

    for (i = 0; i < (size - 10); i++) {
        int index = index_lowest(students, size);

        for (j = index; j < (size - 1); j++) {
            students[j] = students[j + 1];
        }
        size--;
    }
}

Body:
The test of the outer loop of top_student is incorrect: you increase i and reduce size at each iteration, hence you stop too soon.

Here is simplified version:

void top_students(struct Student students[], int size) {
    while (size > 10) {
        for (int j = index_lowest(students, size); j < size - 1; j++) {
            students[j] = students[j + 1];
        }
        size--;
    }
}

Note also that passing large structures by value is inefficient. Passing a pointer is much preferred. Computing average() just once per iteration is also advisable.

Here is a modified version:

double average(const struct Student *s) {
    int i, n;
    double avg = 0.0;
    for (i = 0, n = s->no_of_grades; i < n; i++) {
        avg += s->grades[i].grade;
    }
    return avg / n;
}

int index_lowest(const struct Student students[], int size) {
    // returns the index of the student with the lowest avegare
    // in case of ties, return the last index for the lowest average
    double min = average(&students[0]);
    int i, mini = 0; // mini is the index we search for

    for (i = 1; i < size; i++) {
        double avg = average(&students[i]);
        if (avg <= min) {
            min = avg;
            mini = i;
        }
    }
    return mini;
}


问:
How to create a circle with given radius in Tkinter?
What I want to do is create a circle using create_oval() with the radius r entered in Entry() widget. I don't understand what the problem is. Here's my code:

```<code>from tkinter import *

root = Tk()

#Drawing the circle
def circle(canvas,x,y,r):
   id = canvas.create_oval(x-r,y-r,x+r,y+r)
   return id

#Label
radiusLabel = Label(root, text="Enter the radius: ")
radiusLabel.grid(row=0,column=0)

#Entering the radius
radiusEntry = Entry(root)
radiusEntry.grid(row=1, column=0)

r = int(radiusEntry.get())

#Canvas
canvas = Canvas(width=400,height=400, bg="#cedbd2")
canvas.grid(row=2,column=0)

#Calling the function for drawing the circle button
radiusButton = Button(root, text="Create",command=circle(canvas,100,100,r))
radiusButton.grid(row=2,column=1)

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

Here's the output and the console:

答:
The parameter "command" takes a pointer to a function, not a function itself so you cannot call it like that, also, when you first run the program, get() returns an empty string thus causing the invalid literal error you are getting, you need to call it when your button is clicked, e.g.:

```<code>from tkinter import *

root = Tk()

#Label
radiusLabel = Label(root, text="Enter the radius: ")
radiusLabel.grid(row=0,column=0)

#Entering the radius
radiusEntry = Entry(root)
radiusEntry.grid(row=1, column=0)

#Canvas
canvas = Canvas(width=400,height=400, bg="#cedbd2")
canvas.grid(row=2,column=0)

#Drawing the circle
def circle():
    x=100
    y=100
    r = 0
    if radiusEntry.get():
        r = int(radiusEntry.get())
    id = canvas.create_oval(x-r,y-r,x+r,y+r)
    return id

#Calling the function for drawing the circle button
radiusButton = Button(root, text="Create", command=circle)
radiusButton.grid(row=2,column=1)

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

Hope it helps.

Body:
What I want to do is create a circle using create_oval() with the radius r entered in Entry() widget. I don't understand what the problem is. Here's my code:

from tkinter import *

root = Tk()

#Drawing the circle
def circle(canvas,x,y,r):
   id = canvas.create_oval(x-r,y-r,x+r,y+r)
   return id

#Label
radiusLabel = Label(root, text="Enter the radius: ")
radiusLabel.grid(row=0,column=0)

#Entering the radius
radiusEntry = Entry(root)
radiusEntry.grid(row=1, column=0)

r = int(radiusEntry.get())

#Canvas
canvas = Canvas(width=400,height=400, bg="#cedbd2")
canvas.grid(row=2,column=0)

#Calling the function for drawing the circle button
radiusButton = Button(root, text="Create",command=circle(canvas,100,100,r))
radiusButton.grid(row=2,column=1)

root.mainLoop()

Here's the output and the console:

Body:
The parameter "command" takes a pointer to a function, not a function itself so you cannot call it like that, also, when you first run the program, get() returns an empty string thus causing the invalid literal error you are getting, you need to call it when your button is clicked, e.g.:

from tkinter import *

root = Tk()

#Label
radiusLabel = Label(root, text="Enter the radius: ")
radiusLabel.grid(row=0,column=0)

#Entering the radius
radiusEntry = Entry(root)
radiusEntry.grid(row=1, column=0)

#Canvas
canvas = Canvas(width=400,height=400, bg="#cedbd2")
canvas.grid(row=2,column=0)

#Drawing the circle
def circle():
    x=100
    y=100
    r = 0
    if radiusEntry.get():
        r = int(radiusEntry.get())
    id = canvas.create_oval(x-r,y-r,x+r,y+r)
    return id

#Calling the function for drawing the circle button
radiusButton = Button(root, text="Create", command=circle)
radiusButton.grid(row=2,column=1)

root.mainloop()

Hope it helps.


问:
List of functions: Apply additional argument only to those functions who can take it
I have a list of functions, most of which take the same additional argument (na.rm = TRUE).

I want to add a function which doesn't take this argument (length). Is it possible to apply the additional argument only to the functions which can take it? I thought of using ..., but I am not really sure how to apply it, and if this is possible at all.

I am using lapply, but happy with any options, also beyond base R.

x <- c(1:10,NA)

# working example only with functions that take the extra argument

show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}
show_stats(x)
#> $mean
#> [1] 5.5
#>
#> $sd
#> [1] 3.02765

# sadly not working, because length() only takes one argument
show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd, n = length)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}

show_stats(x)
#> Error in f(x, na.rm = TRUE): 2 arguments passed to 'length' which requires 1
```

Created on 2020-02-16 by the reprex package (v0.3.0)

答:
You can try partial from purrr as well, not sure if you are intended this way. You may also want to check possibly, safely and quietly from purrr, they might useful in some cases

```<code>func_factory <- function(x){
  partial(x, na.rm=T)
}

show_stats <- function(x) {
  funs <- list(mean = func_factory(mean),
               sd = func_factory(sd), n = length)

  lapply(funs, function(f) f(x))
}

show_stats(x)
</code>```

Output:

```<code>> show_stats(x)
$mean
[1] 5.5

$sd
[1] 3.02765

$n
[1] 11

>
</code>```

Body:
I have a list of functions, most of which take the same additional argument (na.rm = TRUE).

I want to add a function which doesn't take this argument (length). Is it possible to apply the additional argument only to the functions which can take it? I thought of using ..., but I am not really sure how to apply it, and if this is possible at all.

I am using lapply, but happy with any options, also beyond base R.

x <- c(1:10,NA)

# working example only with functions that take the extra argument

show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}
show_stats(x)
#> $mean
#> [1] 5.5
#>
#> $sd
#> [1] 3.02765

# sadly not working, because length() only takes one argument
show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd, n = length)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}

show_stats(x)
#> Error in f(x, na.rm = TRUE): 2 arguments passed to 'length' which requires 1

Created on 2020-02-16 by the reprex package (v0.3.0)

Body:
You can try partial from purrr as well, not sure if you are intended this way. You may also want to check possibly, safely and quietly from purrr, they might useful in some cases

func_factory <- function(x){
  partial(x, na.rm=T)
}

show_stats <- function(x) {
  funs <- list(mean = func_factory(mean),
               sd = func_factory(sd), n = length)

  lapply(funs, function(f) f(x))
}

show_stats(x)

Output:

> show_stats(x)
$mean
[1] 5.5

$sd
[1] 3.02765

$n
[1] 11

>


问:
Rendering a new component inside componentDidMount - React
I will have to render a new component after all the expected components are loaded. I will need a timeout based on which the the new component has to be rendered. So this new component has to show up after 5 minutes after the page has loaded.
I need to render a component called new_component that extends React.component

```<code>public componentDidMount(): void {
      if (visited) {
      setTimeout(() => {
        console.log('Reached the timeout')
        //Render the new conponent here. (Not sure how to call the render function of another component here)
      }, timeout);
    }
</code>```

Can someone help me call the render function of new_component inside componentDidMount please. i tried new_component.render(). But that does not seem to work.

答:
You can use state to track this.

```<code>componentDidMount() {
    setTimeout(() => {
        this.setState({ showNewComponent: true })
    })
}
</code>```

and in render:

```<code>render() {
    if (this.state.showNewComponent) {
         return <NewComponent />
    }
    return null
}
</code>```

Body:
I will have to render a new component after all the expected components are loaded. I will need a timeout based on which the the new component has to be rendered. So this new component has to show up after 5 minutes after the page has loaded.
I need to render a component called new_component that extends React.component

public componentDidMount(): void {
      if (visited) {
      setTimeout(() => {
        console.log('Reached the timeout')
        //Render the new conponent here. (Not sure how to call the render function of another component here)
      }, timeout);
    }

Can someone help me call the render function of new_component inside componentDidMount please. i tried new_component.render(). But that does not seem to work.

Body:
You can use state to track this.

componentDidMount() {
    setTimeout(() => {
        this.setState({ showNewComponent: true })
    })
}

and in render:

render() {
    if (this.state.showNewComponent) {
         return <NewComponent />
    }
    return null
}


问:
Can't open a file when not running from __main__
This is my file tree:

```<code>run.py
foo/
    file.py
    foo.json
</code>```

In file.py there is the following code:

```<code>import json

print(json.load(open('foo.json')))
</code>```

In run.py there is the following code:

```<code>import foo.foo as foo
</code>```

When running run.py I get the following error:

```<code>Traceback (most recent call last):
  File "run.py", line 1, in <module>
    import foo.foo as foo
  File "C:\Users\user\Desktop\foo\foo.py", line 3, in <module>
    print(json.load(open('foo.json')))
FileNotFoundError: [Errno 2] No such file or directory: 'foo.json'
</code>```

How do I run run.py without getting that error and without run.py being in the same directory. Any help is appreciated!

答:
As @DeepSpace mentioned can you try setting foo.json to foo/foo.json? As the error indicates it is not able to find such file called 'foo.json` so it's likely to do with the file not being located.

You can also run it with an Absolute path (read here). Try getting the current working directory and setting the file_name as the argument.

Python 2 and 3

For the directory of the script being run:

```<code>import os
os.path.dirname(os.path.abspath(__file__))

</code>```

If you mean the current working directory:

```<code>import os
os.path.abspath(os.getcwd())
</code>```

Read more on this from the docs here

Body:
This is my file tree:

run.py
foo/
    file.py
    foo.json

In file.py there is the following code:

import json

print(json.load(open('foo.json')))

In run.py there is the following code:

import foo.foo as foo

When running run.py I get the following error:

Traceback (most recent call last):
  File "run.py", line 1, in <module>
    import foo.foo as foo
  File "C:\Users\user\Desktop\foo\foo.py", line 3, in <module>
    print(json.load(open('foo.json')))
FileNotFoundError: [Errno 2] No such file or directory: 'foo.json'

How do I run run.py without getting that error and without run.py being in the same directory. Any help is appreciated!

Body:
As @DeepSpace mentioned can you try setting foo.json to foo/foo.json? As the error indicates it is not able to find such file called 'foo.json` so it's likely to do with the file not being located.

You can also run it with an Absolute path (read here). Try getting the current working directory and setting the file_name as the argument.

Python 2 and 3

For the directory of the script being run:

import os
os.path.dirname(os.path.abspath(__file__))

If you mean the current working directory:

import os
os.path.abspath(os.getcwd())

Read more on this from the docs here


问:
autoresizing mask in UITableViewCell
In my didSelectRowAtIndexPath I have the following:

```<code>[self.table beginUpdates];
sideSwipeView = [[[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)] autorelease];
sideSwipeView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
[cell.contentView addSubview:sideSwipeView];
[self.table endUpdates];
</code>```

and in the heightAtRowIndexPath I add the height of the cell if I am adding a UIView.. but however the UIView position is not sticking to the bottom of the cell's, why is this? It's taking the old cell.frame.size.height value, I want to be able it to adjust dynamically if I resize the height of the cell.
'

答: You have the autoresizing mask set to flexible bottom margin. If you want the view to stick to the bottom, you want a flexible top margin instead (or set it to have flexible height).

Title: autoresizing mask in UITableViewCell

Body:
In my didSelectRowAtIndexPath I have the following:

[self.table beginUpdates];
sideSwipeView = [[[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)] autorelease];
sideSwipeView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
[cell.contentView addSubview:sideSwipeView];
[self.table endUpdates];

and in the heightAtRowIndexPath I add the height of the cell if I am adding a UIView.. but however the UIView position is not sticking to the bottom of the cell's, why is this? It's taking the old cell.frame.size.height value, I want to be able it to adjust dynamically if I resize the height of the cell.
'


问:
Cpanel Yandex MX Error
I want to transfer my e-mail accounts to Yandex. I use Cpanel at hosting server.
I get an error when adding Yandex mx addresses, "mx.yandex.net." I can't add address with dot. Error says: "It must have a valid TLD tag." I stuck here.

答:
I had the same problem.
I could manage to fix it by deleting all old MX records and adding a new one
Priority: 10
Destination: mx.yandex.net

enter image description here

You also need to add the TXT record

v=spf1 redirect=_spf.yandex.net

enter image description here

Title: Cpanel Yandex MX Error


问:
How do I deal with an HTTP 410 when web scraping?
I can access a web site through my browser, for example:

https://waset.org/conferences-in-february-2020-in-london

... but if I try and web scrape this web site (I am using php simplehtmldom), I get an HTTP Error 410 (which means the page is gone, but it is there as I can see it through my browser).

Other web sites (from the same family, e.g. https://waset.org/conferences-in-february-2021-in-london), I can scrape just fine.

Does anybody know why I get a 410, when the web page is there, and what I can do about it.

答:
You even can crawl it. Chrome also get 410 error code:

Continue your stuff like if it was 200 code.

-- Edit --

Look at this code it works well for your page :

```<code>$context = stream_context_create(array(
    'http' => array('ignore_errors' => true),
));

$result = file_get_contents('https://waset.org/conferences-in-february-2020-in-london', false, $context);

var_dump($result);
// output <!DOCTYPE html> <html lang="en" dir="ltr" id="desktop"> <head> <!--Google Tag Manager -->...
</code>```

We only choose to ignore errors, like our browser do automatically.

Body:
You even can crawl it. Chrome also get 410 error code:

Continue your stuff like if it was 200 code.

-- Edit --

Look at this code it works well for your page :

$context = stream_context_create(array(
    'http' => array('ignore_errors' => true),
));

$result = file_get_contents('https://waset.org/conferences-in-february-2020-in-london', false, $context);

var_dump($result);
// output <!DOCTYPE html> <html lang="en" dir="ltr" id="desktop"> <head> <!--Google Tag Manager -->...

We only choose to ignore errors, like our browser do automatically.


问:
@Input ony available in Life Cycle Hooks
The basketList objest is available in the html and in the Life Cycle Hook ngOnInit. However, when I try to access it with a function this.set() defined outside the hook then it doesn't work.

```<code>export class MenuOrderItemComponent implements OnInit, OnChanges {

  @Input() basketList: any;

  set(): void{
    setInterval(function(){
      console.log(this.basketList);
      console.log(this.basketList.length);
    },3000);
  }

  constructor() { }

  ngOnInit() {
    console.log('item');
    console.log(this.basketList);
    console.log(this.basketList.length);
    this.set();
  }
</code>```

I'm getting undefined for this.basketList and the error TypeError: Cannot read property 'length' of undefined for the second console.log in this.set()

答:
It seems that the issue is about scope. You can either use arrow function or bind the scope manually.

```<code>export class MenuOrderItemComponent implements OnInit, OnChanges {

  @Input() basketList: any;

  set = (): void => {
  //    ^^^^^^^^^ Here

    setInterval(() => {
        //    ^^^^^^^^^ And here

       ...
    },3000);
  }

  ......
</code>```

Body:
The basketList objest is available in the html and in the Life Cycle Hook ngOnInit. However, when I try to access it with a function this.set() defined outside the hook then it doesn't work.

export class MenuOrderItemComponent implements OnInit, OnChanges {

  @Input() basketList: any;

  set(): void{
    setInterval(function(){
      console.log(this.basketList);
      console.log(this.basketList.length);
    },3000);
  }

  constructor() { }

  ngOnInit() {
    console.log('item');
    console.log(this.basketList);
    console.log(this.basketList.length);
    this.set();
  }

I'm getting undefined for this.basketList and the error TypeError: Cannot read property 'length' of undefined for the second console.log in this.set()

Body:
It seems that the issue is about scope. You can either use arrow function or bind the scope manually.

export class MenuOrderItemComponent implements OnInit, OnChanges {

  @Input() basketList: any;

  set = (): void => {
  //    ^^^^^^^^^ Here

    setInterval(() => {
        //    ^^^^^^^^^ And here

       ...
    },3000);
  }

  ......


问:
Where does greenlock-express saves lets-encrypt certificates?
I'm using greenlock-express to generate lets-encrypt certificates. However, I don't know where the certificate is stored. Therefore, everytime I started my application, it generated a new certificate, because I use docker, and so I reached the lets-encrypt maximum number of certificates.

Where does greenlock saves the certificates? I want to mount this folder as a volume so docker reuses it on every startup. But is mounting this folder enough?

答:
I have just ran into the same problem.

You can set up the path to the certificates using this command:

```<code>npx greenlock defaults --store greenlock-store-fs --store-base-path <path_to_certificates>
</code>```

All that's left is to mount your volume.

I'm also pointing my configDir: '<path_to_certificates>' there as the config does not seem like something you want to commit. If I ran out of certificates, I'll let you know.

Body:
I have just ran into the same problem.

You can set up the path to the certificates using this command:

npx greenlock defaults --store greenlock-store-fs --store-base-path <path_to_certificates>

All that's left is to mount your volume.

I'm also pointing my configDir: '<path_to_certificates>' there as the config does not seem like something you want to commit. If I ran out of certificates, I'll let you know.


答:
You will get the updated value of 'basketList' in ngOnchange() life cycle hook-
    @input() id: number;
     @input() name: string;
     ngOnChanges(changes: SimpleChanges) {
     console.log(changes);
     }
     // Output
     {id: SimpleChange, name: SimpleChange}

And by setter method of typescript-

```<code> @Input() set basketList(data: any) {
 // you might do something special in here
 this.basketList= data;
 }
</code>```

Title: @Input ony available in Life Cycle Hooks

Body:
You will get the updated value of 'basketList' in ngOnchange() life cycle hook-
    @input() id: number;
     @input() name: string;
     ngOnChanges(changes: SimpleChanges) {
     console.log(changes);
     }
     // Output
     {id: SimpleChange, name: SimpleChange}

And by setter method of typescript-

 @Input() set basketList(data: any) {
 // you might do something special in here
 this.basketList= data;
 }


问:
Sluggishness in VS Code due to Gtk on Windows 10
In VS Code, when I run a Julia file, if I have included the library ProfileView via using ProfileView, I get the following warning.

Warning: You are using Gtk on Windows which is currently not recommended. Your REPL/IDE and anything depending on task switches will become sluggish and much slower (up to ~85x slower).

The IDE does become very sluggish.

What should I do to fix this? JuliaPro and Atom are also very slow, and this slowness was why I switched to VS Code (the reason for the slowness may have been different, but I mention this just in case it is useful).

As suggested by the error message, I'm on Windows 10.

答: per the warning message you are getting, the only way to "fix" this would be to not use a Windows computer. There's nothing you can do about the slow down on Windows with respect to GTK.jl at this time.</p>


问:
Laravel Auth::hasUser always false in Global Scope
I have the following code in my model:

```<code>protected static function boot()
{
    parent::boot();

    static::addGlobalScope(new CompanyScope);
}
</code>```

Here is my CompanyScope:

```<code>class CompanyScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        \Log::info('apply');

        if (Auth::hasUser()) {
            \Log::info('auth');

            $builder->where($model->getTable() . '.company_id', company()->id);
        }
    }
}
</code>```

In my log, I only see apply, I do not see auth, nor is the scope being applied.

Why?

答:
I just tested what you have here except I've used \Illuminate\Support\Facades\Log rather than \Log and it seems it works fine as long as you are actually testing it with the authenticated user:

app/User.php

```<code><?php

namespace App;

use App\Scopes\CompanyScope;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new CompanyScope);
    }
}
</code>```

app/Scopes/CompanyScope.php

```<code><?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Scope;

class CompanyScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        Log::info('apply');

        if (Auth::hasUser()) {
            Log::info('auth');

            $builder->where($model->getTable() . '.company_id', company()->id);
        }
    }
}
</code>```

In my controller I just fetch the user with id 1:

```<code>/**
* Get landing view.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index(): JsonResponse
{
    $user = User::find(1);

    return new JsonResponse([
        'user' => $user,
    ]);
}
</code>```

and the corresponding test:

```<code>/**
 * @test
 */
public function global_scope()
{
    $this->actingAs($user = factory(User::class)->create(['id' => 1]));

    $this->assertTrue($user->exists);
    $this->assertAuthenticatedAs($user);

    $response = $this->get(route('home'));

    $response->assertExactJson([
        'user' => $user->toArray()
    ]);
}
</code>```

After running the test, my log file contains:

```<code>[2020-02-16 14:18:59] testing.INFO: apply
[2020-02-16 14:18:59] testing.INFO: auth
</code>```

If you try the same without logging the user in, then only apply will be logged.

Body:
I have the following code in my model:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope(new CompanyScope);
}

Here is my CompanyScope:

class CompanyScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        \Log::info('apply');

        if (Auth::hasUser()) {
            \Log::info('auth');

            $builder->where($model->getTable() . '.company_id', company()->id);
        }
    }
}

In my log, I only see apply, I do not see auth, nor is the scope being applied.

Why?

Body:
I just tested what you have here except I've used \Illuminate\Support\Facades\Log rather than \Log and it seems it works fine as long as you are actually testing it with the authenticated user:

app/User.php

<?php

namespace App;

use App\Scopes\CompanyScope;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new CompanyScope);
    }
}

app/Scopes/CompanyScope.php

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Scope;

class CompanyScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        Log::info('apply');

        if (Auth::hasUser()) {
            Log::info('auth');

            $builder->where($model->getTable() . '.company_id', company()->id);
        }
    }
}

In my controller I just fetch the user with id 1:

/**
* Get landing view.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index(): JsonResponse
{
    $user = User::find(1);

    return new JsonResponse([
        'user' => $user,
    ]);
}

and the corresponding test:

/**
 * @test
 */
public function global_scope()
{
    $this->actingAs($user = factory(User::class)->create(['id' => 1]));

    $this->assertTrue($user->exists);
    $this->assertAuthenticatedAs($user);

    $response = $this->get(route('home'));

    $response->assertExactJson([
        'user' => $user->toArray()
    ]);
}

After running the test, my log file contains:

[2020-02-16 14:18:59] testing.INFO: apply
[2020-02-16 14:18:59] testing.INFO: auth

If you try the same without logging the user in, then only apply will be logged.


问:
Set-returning functions are not allowed in UPDATE when using Postgres 11
I have a Postgresql 9.6 (and postgis 2.5) function that calculates a json with parameters based on a geometry  of a record.
I created a json field and wrote the json calculation output there, and all was well.

```<code>UPDATE public.recordtable
SET polygoncalc = public.fn_calculate_polygon(5)
WHERE id = 5;
</code>```

When I try to run it on Postgres 11.2 , it returns a error:

```<code>SQL Error [0A000]:ERROR: set-returning functions are not allowed in UPDATE
</code>```

Based on this link I understand there has been a change in postgresql, but honestly,

how can I write the json into the field in Postgres 11.2 without getting the error ?

Thank you in advance.

EDIT: I changed the output field to type json and added the function text

```<code>the function:

CREATE OR REPLACE FUNCTION public.fn_create_jsn_point(pid double precision)
 RETURNS TABLE(jsn json)
 LANGUAGE plpgsql
AS $function$
DECLARE
    p_id double precision = pid;
    myjson json = null ;

    begin
       return QUERY
       select row_to_json(finaljson)
            from(
            select
                 ST_x(a.wgs_84_dump_point) as X,
                 ST_y(a.wgs_84_dump_point) as Y
                        (
                             select (st_transform(st_centroid(t.geom),4326))  wgs_84_dump_point
                                 from baserecords t where base_id = p_id
                        ) a ) finaljson;
    END;
$function$
;
</code>```

答:
The function is returning a table. No matter how many rows are returned, it is returning a table, i.e a set.

Since you know a single value will be returned, you can change the function to restrict it:

CREATE OR REPLACE FUNCTION public.fn_create_jsn_point(pid double precision)
 RETURNS json -- <---------------------------- Return a single value
 LANGUAGE plpgsql
AS $function$
DECLARE
    p_id double precision = pid;
    myjson json = null ;

    begin
       return ( -- <---------------------------------- return a single value
         select row_to_json(finaljson)
            from(
            select
                 ST_x(a.wgs_84_dump_point) as X,
                 ST_y(a.wgs_84_dump_point) as Y
                        (
                             select (st_transform(st_centroid(t.geom),4326))  wgs_84_dump_point
                                 from baserecords t where base_id = p_id
                        ) a ) finaljson
       );
    END;
$function$
;
```

Body:
I have a Postgresql 9.6 (and postgis 2.5) function that calculates a json with parameters based on a geometry  of a record.
I created a json field and wrote the json calculation output there, and all was well.

UPDATE public.recordtable
SET polygoncalc = public.fn_calculate_polygon(5)
WHERE id = 5;

When I try to run it on Postgres 11.2 , it returns a error:

SQL Error [0A000]:ERROR: set-returning functions are not allowed in UPDATE

Based on this link I understand there has been a change in postgresql, but honestly,

how can I write the json into the field in Postgres 11.2 without getting the error ?

Thank you in advance.

EDIT: I changed the output field to type json and added the function text

the function:

CREATE OR REPLACE FUNCTION public.fn_create_jsn_point(pid double precision)
 RETURNS TABLE(jsn json)
 LANGUAGE plpgsql
AS $function$
DECLARE
    p_id double precision = pid;
    myjson json = null ;

    begin
       return QUERY
       select row_to_json(finaljson)
            from(
            select
                 ST_x(a.wgs_84_dump_point) as X,
                 ST_y(a.wgs_84_dump_point) as Y
                        (
                             select (st_transform(st_centroid(t.geom),4326))  wgs_84_dump_point
                                 from baserecords t where base_id = p_id
                        ) a ) finaljson;
    END;
$function$
;


问:
set view height as matchparent programmatically in kotlin
I need to set programatically the height of a button as matchparent  in my constraintLayout class.

```<code>open class Myword @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
     ) : ConstraintLayout(context,attrs) {

    var set = ConstraintSet()
    val tastoetim= Button(this.context)
    init{
        this.addView(tastoetim)
        tastoetim.requestLayout()

        set.connect(tastoetim.id, ConstraintSet.LEFT,this.id, ConstraintSet.LEFT, 10)
        set.connect(tastoetim.id, ConstraintSet.BOTTOM,this.id, ConstraintSet.BOTTOM, 0)

        tastoetim.minHeight = 0
        tastoetim.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT

    } }

</code>```

this does not work.

As already pointed out by author of this post (set height of imageview as matchparent programmatically), none of these answers works.

答:
Resolved by firstly setting :

```<code>tastoetim.setMinHeight(0);
tastoetim.setMinimumHeight(0);
</code>```

And then :

```<code>tastoetim.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;
</code>```

setMinHeight is defined by ButtonView, while setMinimumHeight is defined by View. According to the docs, the greater of the two values is used, so both must be set.

Body:
I need to set programatically the height of a button as matchparent  in my constraintLayout class.

open class Myword @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
     ) : ConstraintLayout(context,attrs) {

    var set = ConstraintSet()
    val tastoetim= Button(this.context)
    init{
        this.addView(tastoetim)
        tastoetim.requestLayout()

        set.connect(tastoetim.id, ConstraintSet.LEFT,this.id, ConstraintSet.LEFT, 10)
        set.connect(tastoetim.id, ConstraintSet.BOTTOM,this.id, ConstraintSet.BOTTOM, 0)

        tastoetim.minHeight = 0
        tastoetim.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT

    } }

this does not work.

As already pointed out by author of this post (set height of imageview as matchparent programmatically), none of these answers works.

Body:
Resolved by firstly setting :

tastoetim.setMinHeight(0);
tastoetim.setMinimumHeight(0);

And then :

tastoetim.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;

setMinHeight is defined by ButtonView, while setMinimumHeight is defined by View. According to the docs, the greater of the two values is used, so both must be set.


问:
Getting the average size of a specific class from a running JVM
I'm trying to get the average size of all instances of a certain class in a running JVM. I can create a heap dump with jcmd or similar but that takes a few seconds and this is a production server so I'd rather have something faster. jcmd has an option to create a histogram of this format:

```<code> num     #instances         #bytes  class name
----------------------------------------------
   1:         84907      559415720  [I
   2:       9572537      229740888  java.lang.String
   3:        803323      142900392  [C
   4:       3190710      102102720  java.util.Hashtable$Entry
</code>```

which seems promising, but I think the byte size is of shallow rather than retained memory. Is there a way to create the same histogram with retained size? Or maybe another method of getting the average size of instances of a class quickly?

I'm aware of the GDB method but it's not suitable because the sequence of commands will take me a few seconds to type and this is approximately the time a heap dump will take me with jcmd.

答:
I do not think that a generic tool that will report a histogram of the "deep sizes" of objects is technically feasible.

Why not?

If the "deep size" of an object depends on the semantics of its class, we have the problem that a general purpose tool doesn't know where the object boundaries are.  One could implement a tool with hard-coded knowledge of standard types like String, StringBuffer or HashMap. However:

That approach does not doesn't scale, and it doesn't deal with the application and 3rd party library classes.

With some types (e.g. collection types) the semantic boundary (i.e. what the user wants to find out) may be context dependent.

Alternatively, if the "deep size" of an object is the simply the sum of the sizes of all objects that are reachable from it, there are two problems:

There will be significant over-counting.  For instance, most of memory usage for strings is in the character arrays. These arrays will be counted twice: once in the reachability graphs of the String objects, and a second time as character arrays.  For complex objects, the over-counting is likely to render the measure useless.

Computing the averages for the histogram would be very expensive.  A simple approach would perform a reachability graph walk for each and every object in the heap.  I don't know if there is a faster alternative.

The alternative would be avoid double counting by not including the "internal" objects in the instance counts.  Unfortunately, then you would have the equally misleading phenomenon that (for example) internal strings, collections, etc inside more complex objects disappear.  That means that you can no longer get accurate estimates for their average sizes.

I don't think there is a counting scheme that is actually going to work.

Having said that, the source code for the (OpenJDK) tools you currently using is available for download.  You could modify the tools to analyze the object sizes differently.  But I don't imagine that it will "quick" in terms of dev effort or speed of the modified tools.

Body:
I'm trying to get the average size of all instances of a certain class in a running JVM. I can create a heap dump with jcmd or similar but that takes a few seconds and this is a production server so I'd rather have something faster. jcmd has an option to create a histogram of this format:

 num     #instances         #bytes  class name
----------------------------------------------
   1:         84907      559415720  [I
   2:       9572537      229740888  java.lang.String
   3:        803323      142900392  [C
   4:       3190710      102102720  java.util.Hashtable$Entry

which seems promising, but I think the byte size is of shallow rather than retained memory. Is there a way to create the same histogram with retained size? Or maybe another method of getting the average size of instances of a class quickly?

I'm aware of the GDB method but it's not suitable because the sequence of commands will take me a few seconds to type and this is approximately the time a heap dump will take me with jcmd.