问:
Accessing Hive using JdbcIO in apache beam throws java.lang.NoClassDefFoundError: org/apache/avro/reflect/AvroSchema
I could access my mysql table using JDBCIO and Avro Coder. Now I am trying to load my hive database using JdbcIO.
Below exception has thrown while connecting to hive from dataflow. Any help from the beam geeks would be really helpful.

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/avro/reflect/AvroSchema
at org.apache.beam.sdk.coders.AvroCoder$AvroDeterminismChecker.recurse(AvroCoder.java:426)
at org.apache.beam.sdk.coders.AvroCoder$AvroDeterminismChecker.check(AvroCoder.java:419)
at org.apache.beam.sdk.coders.AvroCoder.<init>(AvroCoder.java:259)
at org.apache.beam.sdk.coders.AvroCoder.of(AvroCoder.java:120)
at com.google.cloud.bigquery.csv.loader.GoogleSQLPipeline.main(GoogleSQLPipeline.java:101)
Caused by: java.lang.ClassNotFoundException: org.apache.avro.reflect.AvroSchema
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 5 more
</code>```

Below code snippet is trying to access hive :

```<code>dataflowPipeline
            .apply(JdbcIO.<Customer>read()
                    .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration
                            .create("org.apache.hive.jdbc.HiveDriver", "jdbc:hive2://<ip>/mydb")
                            .withUsername("username").withPassword("password"))
                    .withQuery(
                            "select c_customer_id,c_first_name,c_last_name,c_preferred_cust_flag,c_birth_day,c_birth_month,c_birth_year,c_birth_country,c_customer_sk,c_current_cdemo_sk,c_current_hdemo_sk from customer")
                    .withRowMapper(new JdbcIO.RowMapper<Customer>() {
                        @Override
                        public Customer mapRow(ResultSet resultSet) throws Exception
</code>```

POM Dependecies :

```<code><dependencies>
    <dependency>
        <groupId>com.google.cloud.dataflow</groupId>
        <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
        <version>2.0.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.beam/beam-sdks-java-io-jdbc -->
    <dependency>
        <groupId>org.apache.beam</groupId>
        <artifactId>beam-sdks-java-io-jdbc</artifactId>
        <version>2.0.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.hive/hive-jdbc -->
    <dependency>
        <groupId>org.apache.hive</groupId>
        <artifactId>hive-jdbc</artifactId>
        <version>1.2.1</version>
    </dependency>
    <dependency>
        <groupId>jdk.tools</groupId>
        <artifactId>jdk.tools</artifactId>
        <version>1.8.0_131</version>
        <scope>system</scope>
        <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-common -->
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.8.1</version>
    </dependency>

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>
    <!-- slf4j API frontend binding with JUL backend -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-jdk14</artifactId>
        <version>1.7.14</version>
    </dependency>
</dependencies>
</code>```

答: Added dependency for Avro 1.8.1 and manually imported import org.apache.avro.reflect.AvroSchema; Now that issue is solved. Again, issues related to com.google.protobuf.GeneratedMessageV3 is solved by manually importing this class. </p>

Body:
I could access my mysql table using JDBCIO and Avro Coder. Now I am trying to load my hive database using JdbcIO.
Below exception has thrown while connecting to hive from dataflow. Any help from the beam geeks would be really helpful.

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/avro/reflect/AvroSchema
at org.apache.beam.sdk.coders.AvroCoder$AvroDeterminismChecker.recurse(AvroCoder.java:426)
at org.apache.beam.sdk.coders.AvroCoder$AvroDeterminismChecker.check(AvroCoder.java:419)
at org.apache.beam.sdk.coders.AvroCoder.<init>(AvroCoder.java:259)
at org.apache.beam.sdk.coders.AvroCoder.of(AvroCoder.java:120)
at com.google.cloud.bigquery.csv.loader.GoogleSQLPipeline.main(GoogleSQLPipeline.java:101)
Caused by: java.lang.ClassNotFoundException: org.apache.avro.reflect.AvroSchema
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 5 more

Below code snippet is trying to access hive :

dataflowPipeline
            .apply(JdbcIO.<Customer>read()
                    .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration
                            .create("org.apache.hive.jdbc.HiveDriver", "jdbc:hive2://<ip>/mydb")
                            .withUsername("username").withPassword("password"))
                    .withQuery(
                            "select c_customer_id,c_first_name,c_last_name,c_preferred_cust_flag,c_birth_day,c_birth_month,c_birth_year,c_birth_country,c_customer_sk,c_current_cdemo_sk,c_current_hdemo_sk from customer")
                    .withRowMapper(new JdbcIO.RowMapper<Customer>() {
                        @Override
                        public Customer mapRow(ResultSet resultSet) throws Exception

POM Dependecies :

<dependencies>
    <dependency>
        <groupId>com.google.cloud.dataflow</groupId>
        <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
        <version>2.0.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.beam</groupId>
        <artifactId>beam-sdks-java-io-jdbc</artifactId>
        <version>2.0.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.hive</groupId>
        <artifactId>hive-jdbc</artifactId>
        <version>1.2.1</version>
    </dependency>
    <dependency>
        <groupId>jdk.tools</groupId>
        <artifactId>jdk.tools</artifactId>
        <version>1.8.0_131</version>
        <scope>system</scope>
        <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
    </dependency>

    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.8.1</version>
    </dependency>

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-jdk14</artifactId>
        <version>1.7.14</version>
    </dependency>
</dependencies>


来源: stackexchange

问:
How to get total data usage of an android device programmatically?
In the settings menu on my android smartphone, I can see the total data usage of the current and past cycles. Can I somehow retrieve that information programmatically in my app?

Thanks in advance.

答:
You can use android.net.TrafficStats to get traffic details:

for example to get Total bytes received:

```<code>android.net.TrafficStats.getTotalRxBytes()
</code>```

and if you want to get send and received info of your apps one by one you can get it like this:

first get all apps running info by this:

```<code>List<RunningAppProcessInfo>
</code>```

then get UID of each app you want

```<code>ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningApps = manager.getRunningAppProcesses();

for (RunningAppProcessInfo runningApp : runningApps) {
  // Get UID of the selected process
  int uid = ((RunningAppProcessInfo)getListAdapter().getItem(position)).uid;

  long received = TrafficStats.getUidRxBytes(uid);//received amount of each app
  long send   = TrafficStats.getUidTxBytes(uid);//sent amount of each app
}
</code>```

let me know is this what you want

ContentLicense: CC BY-SA 4.0

Body:
You can use android.net.TrafficStats to get traffic details:

for example to get Total bytes received:

android.net.TrafficStats.getTotalRxBytes()

and if you want to get send and received info of your apps one by one you can get it like this:

first get all apps running info by this:

List<RunningAppProcessInfo>

then get UID of each app you want

ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningApps = manager.getRunningAppProcesses();

for (RunningAppProcessInfo runningApp : runningApps) {
  // Get UID of the selected process
  int uid = ((RunningAppProcessInfo)getListAdapter().getItem(position)).uid;

  long received = TrafficStats.getUidRxBytes(uid);//received amount of each app
  long send   = TrafficStats.getUidTxBytes(uid);//sent amount of each app
}

let me know is this what you want

ContentLicense: CC BY-SA 3.0


问:
Sails & Async Each Not Assigning Values
I'm using async each to iterate over objects and perform a query to populate their children. Each site has locations which have floors which have areas. My sites and locations populate just fine, however, that is where it stops. Sails outputs that it is looking for floors and areas though but they are never assigned. Any ideas?</p>

```<code>gg: function (req, res) {
    var userID = req.param('id');

    User.findOne({ id: userID }).populate('sites').exec(function afterFind(err, foundUser) {
        if (err) return res.json({ status: 'failure', message: 'Server error' });
        if (foundUser === undefined) return res.json({ status: 'failure', message: 'User was not found' });

        var resultToJson = foundUser.toJSON();
        var sites = resultToJson.sites;

        async.each(sites, function (site, siteCb) {
            sails.log.debug('Finding locations for ' + site.name);
            Locations.find({ site: site.id }).exec(function afterFind(err, foundLocations) {
                if (err) {
                    siteCb(err);
                } else {
                    site['locations'] = foundLocations;

                    async.each(site['locations'], function (location, locCb) {
                        sails.log.debug('Finding floors for ' + location.name);
                        Floor.find({ location: location.id }).exec(function afterFind(err, foundFloors) {
                            if (err) {
                                locCb(err);
                            } else {
                                location['floors'] = foundFloors;

                                async.each(location['floors'], function (floor, floorCb) {
                                    sails.log.debug('Finding areas for ' + floor.name);
                                    Area.find({ floor: floor.id }).exec(function afterFind(err, foundAreas) {
                                        if (err) {
                                            floorCb(err);
                                        } else {
                                            floor['areas'] = foundAreas;
                                            floorCb();
                                        }
                                    });
                                }, function (floorError) {
                                    if (floorError) {
                                        locCb(floorError);
                                    }
                                    else {
                                        locCb();
                                    }
                                });
                            }
                        });
                    }, function (locError) {
                        if (locError) {
                            siteCb(locError);
                        } else {
                            siteCb();
                        }
                    });
                }
            });
        }, function (siteError) {
            if (siteError) {
                sails.log.debug(siteError);
                return res.json({ status: 'failure', message: 'Server error' });
            } else {
                return res.json({ status: 'success', message: 'Sites for user retrieved', sites: sites });
            }
        });
    });
}
</code>```

答:
This code should be fixed with use of toJSON() on foundLocations. Anytime when you're overriding a defined attribute with populated one (or something else) it will not work when using a ORM returned object, use toJSON() or something and assign to plain JS object.

Ref: https://stackoverflow.com/a/43500017/1435132

Also, any reason to not use populate with Locations.find?

Title: Sails & Async Each Not Assigning Values

Body:
I'm using async each to iterate over objects and perform a query to populate their children. Each site has locations which have floors which have areas. My sites and locations populate just fine, however, that is where it stops. Sails outputs that it is looking for floors and areas though but they are never assigned. Any ideas?

gg: function (req, res) {
    var userID = req.param('id');

    User.findOne({ id: userID }).populate('sites').exec(function afterFind(err, foundUser) {
        if (err) return res.json({ status: 'failure', message: 'Server error' });
        if (foundUser === undefined) return res.json({ status: 'failure', message: 'User was not found' });

        var resultToJson = foundUser.toJSON();
        var sites = resultToJson.sites;

        async.each(sites, function (site, siteCb) {
            sails.log.debug('Finding locations for ' + site.name);
            Locations.find({ site: site.id }).exec(function afterFind(err, foundLocations) {
                if (err) {
                    siteCb(err);
                } else {
                    site['locations'] = foundLocations;

                    async.each(site['locations'], function (location, locCb) {
                        sails.log.debug('Finding floors for ' + location.name);
                        Floor.find({ location: location.id }).exec(function afterFind(err, foundFloors) {
                            if (err) {
                                locCb(err);
                            } else {
                                location['floors'] = foundFloors;

                                async.each(location['floors'], function (floor, floorCb) {
                                    sails.log.debug('Finding areas for ' + floor.name);
                                    Area.find({ floor: floor.id }).exec(function afterFind(err, foundAreas) {
                                        if (err) {
                                            floorCb(err);
                                        } else {
                                            floor['areas'] = foundAreas;
                                            floorCb();
                                        }
                                    });
                                }, function (floorError) {
                                    if (floorError) {
                                        locCb(floorError);
                                    }
                                    else {
                                        locCb();
                                    }
                                });
                            }
                        });
                    }, function (locError) {
                        if (locError) {
                            siteCb(locError);
                        } else {
                            siteCb();
                        }
                    });
                }
            });
        }, function (siteError) {
            if (siteError) {
                sails.log.debug(siteError);
                return res.json({ status: 'failure', message: 'Server error' });
            } else {
                return res.json({ status: 'success', message: 'Sites for user retrieved', sites: sites });
            }
        });
    });
}


问:
restore sql server from .bak file Exclusive access could not be obtained
I am trying to restore my sql using bak file

I am getting error

Exclusive access could not be obtained because the database is in use

I tried

```<code>USE [master]
ALTER DATABASE myDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
</code>```

and run the query

```<code>USE [master] RESTORE DATABASE  myDB
   FROM DISK = 'C:\MyDatabase.bak' WITH  FILE = 1,  NOUNLOAD,  STATS = 10
</code>```

I also tried from restore wizard with same result.

Exclusive access could not be obtained because the database is in use.

答:
Anyone that has had the issues listed above, and none of the advice works.. Just turn off the Taillog backup under 'options'..

Setting (or leaving) this option on will attempt to take a tail-log of the source database itself (even if your source for the restore is just a file).  So if the source database is in use (which if you are doing a copy of a production DB will normally be the case) then the restore fails.

Body:
I am trying to restore my sql using bak file

I am getting error

Exclusive access could not be obtained because the database is in use

I tried

USE [master]
ALTER DATABASE myDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

and run the query

USE [master] RESTORE DATABASE  myDB
   FROM DISK = 'C:\MyDatabase.bak' WITH  FILE = 1,  NOUNLOAD,  STATS = 10

I also tried from restore wizard with same result.

Exclusive access could not be obtained because the database is in use.


问:
Where is spark loading it's jars from?
When specifying a jar at "spark.jars", and running on a standalone spark, without spark-submit. Where is the jar loaded from?

I have a Spring application that performs some spark operations on a Spark standalone running in Docker.

My application relies on various libraries such as MySQL JDBC, ElasticSearch, etc, and thus it fails running on the cluster which doesn't have them.

I assembled my jar with all its dependencies and moved it to the /jars directory in Docker. But still no luck.

```<code>13:28:42.577 [Executor task launch worker-0] INFO org.apache.spark.executor.Executor - Fetching spark://192.168.99.1:58290/jars/xdf-1.0.jar with timestamp 1499088505128
13:28:42.614 [dispatcher-event-loop-0] INFO org.apache.spark.executor.Executor - Executor is trying to kill task 0.3 in stage 1.0 (TID 7)
13:28:42.698 [Executor task launch worker-0] DEBUG org.apache.spark.network.client.TransportClient - Sending stream request for /jars/xdf-1.0.jar to /192.168.99.1:58290
13:28:42.741 [shuffle-client-7-1] DEBUG org.apache.spark.rpc.netty.NettyRpcEnv - Error downloading stream /jars/xdf-1.0.jar.
java.lang.RuntimeException: Stream '/jars/xdf-1.0.jar' was not found.
</code>```

Now I noticed that it's looking for the jar on the driver host but I don't understand where it's trying to deploy it from.
Any one has an
idea where it's looking for that jar.

答:
I figured it out. The jars are loaded from the driver node.
So, I didn't need to move my jar to the spark nodes. And I had to set the correct path to the dependency jar.

So this solved it:

```<code>spark.jars=./target/scala-2.1.1/xdf.jar
</code>```

Title: Where is spark loading it's jars from?

Body:
When specifying a jar at "spark.jars", and running on a standalone spark, without spark-submit. Where is the jar loaded from?

I have a Spring application that performs some spark operations on a Spark standalone running in Docker.

My application relies on various libraries such as MySQL JDBC, ElasticSearch, etc, and thus it fails running on the cluster which doesn't have them.

I assembled my jar with all its dependencies and moved it to the /jars directory in Docker. But still no luck.

13:28:42.577 [Executor task launch worker-0] INFO org.apache.spark.executor.Executor - Fetching spark://192.168.99.1:58290/jars/xdf-1.0.jar with timestamp 1499088505128
13:28:42.614 [dispatcher-event-loop-0] INFO org.apache.spark.executor.Executor - Executor is trying to kill task 0.3 in stage 1.0 (TID 7)
13:28:42.698 [Executor task launch worker-0] DEBUG org.apache.spark.network.client.TransportClient - Sending stream request for /jars/xdf-1.0.jar to /192.168.99.1:58290
13:28:42.741 [shuffle-client-7-1] DEBUG org.apache.spark.rpc.netty.NettyRpcEnv - Error downloading stream /jars/xdf-1.0.jar.
java.lang.RuntimeException: Stream '/jars/xdf-1.0.jar' was not found.

Now I noticed that it's looking for the jar on the driver host but I don't understand where it's trying to deploy it from.
Any one has an
idea where it's looking for that jar.

Body:
I figured it out. The jars are loaded from the driver node.
So, I didn't need to move my jar to the spark nodes. And I had to set the correct path to the dependency jar.

So this solved it:

spark.jars=./target/scala-2.1.1/xdf.jar


问:
Angular - Wait until I receive data before loading template
I have a component that renders several components dynamically, with this template:

```<code><div [saJquiAccordion]="{active: group.value['collapsed']}" *ngFor="let group of filterGroupsTemplate | keysCheckDisplay;">
    <div>
        <h4>{{group.key | i18n}}</h4>
        <form id="ibo-{{group.key}}" class="form-horizontal" autocomplete="off" style="overflow: initial">
            <fieldset *ngFor="let field of group.value | keys">
                <ng-container *ngComponentOutlet="fieldSets[field.value.template];
                                    ngModuleFactory: smartadminFormsModule;"></ng-container>
            </fieldset>
        </form>
    </div>
</div>
</code>```

The thing is that the data needed to fill those components I'm getting it from an API call:

```<code>      this.getFiltersSubscription = this.getFilters().subscribe(
            (filters) => {
                this.filters = filters;
                log.info('API CALL. getting filters');

                // Sending data to fieldform components
                this.iboService.updateIBOsRankList(filters['iboRank'].data);
                this.iboService.updateIBOsNewsletterOptions(filters['iboNewsletter'].data);
                this.iboService.updateIBOsTotalOrders(filters['iboTotalOrders'].data);
            }
        );
</code>```

So, once I have my data, I'm triggering a service Observable which my components are subscribed to, and they will then process the gathered data.

PROBLEM

If the API call is made before all components load, I'll be triggering these service methods passing data but nobody will be subscribed to those Observables.

An approach would be to:

Load data first, and only when I have the data loaded, I'll render the template and, therefore, render all these components dynamically and only then I'll be triggering these service methods (Observables).

I don't want to make an API call for each component, because it can be like 60 components, I'll rather loose abstraction fo code but I prefer to do something like this:

```<code>// Listens to field's init and creates the fieldset triggering a service call that will be listened by the field component
        this.iboService.initIBOsFilters$.subscribe(
            (fieldName) => {
                if (fieldName === 'IBOsRankSelectorFieldComponent') {
                    log.data('inside initIBOsFilters$ subscription, calling updateIBOsFilters()', fieldName);
                    this.iboService.updateIBOsRankList(this.filters['iboRank'].data); // HERE I'M PASSING DATA TO THE COMPONENT RENDERED DYNAMICALY. BUT IF this.filters IS UNDEFINED, IT BREAKS
                }
            }
        );
</code>```

In order to do this, I need to ensure that this.filters is defined and thus, I come to conclusion:

How can I wait until API call ends and this.filters is defined before rendering my template html?

Sorry if my question is a bit long, if you need any more details just let me know.

Thanks!

答:
You could use a resolver to ensure those data are loaded (or your filters have been initialized) before the route is activated.

https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

https://angular.io/api/router/Resolve

Body:
I have a component that renders several components dynamically, with this template:

{{group.key | i18n}}

        <form id="ibo-{{group.key}}" class="form-horizontal" autocomplete="off" style="overflow: initial">
            <fieldset *ngFor="let field of group.value | keys">
                <ng-container *ngComponentOutlet="fieldSets[field.value.template];
                                    ngModuleFactory: smartadminFormsModule;"></ng-container>
            </fieldset>
        </form>

The thing is that the data needed to fill those components I'm getting it from an API call:

      this.getFiltersSubscription = this.getFilters().subscribe(
            (filters) => {
                this.filters = filters;
                log.info('API CALL. getting filters');

                // Sending data to fieldform components
                this.iboService.updateIBOsRankList(filters['iboRank'].data);
                this.iboService.updateIBOsNewsletterOptions(filters['iboNewsletter'].data);
                this.iboService.updateIBOsTotalOrders(filters['iboTotalOrders'].data);
            }
        );

So, once I have my data, I'm triggering a service Observable which my components are subscribed to, and they will then process the gathered data.

PROBLEM

If the API call is made before all components load, I'll be triggering these service methods passing data but nobody will be subscribed to those Observables.

An approach would be to:

Load data first, and only when I have the data loaded, I'll render the template and, therefore, render all these components dynamically and only then I'll be triggering these service methods (Observables).

I don't want to make an API call for each component, because it can be like 60 components, I'll rather loose abstraction fo code but I prefer to do something like this:

// Listens to field's init and creates the fieldset triggering a service call that will be listened by the field component
        this.iboService.initIBOsFilters$.subscribe(
            (fieldName) => {
                if (fieldName === 'IBOsRankSelectorFieldComponent') {
                    log.data('inside initIBOsFilters$ subscription, calling updateIBOsFilters()', fieldName);
                    this.iboService.updateIBOsRankList(this.filters['iboRank'].data); // HERE I'M PASSING DATA TO THE COMPONENT RENDERED DYNAMICALY. BUT IF this.filters IS UNDEFINED, IT BREAKS
                }
            }
        );

In order to do this, I need to ensure that this.filters is defined and thus, I come to conclusion:

How can I wait until API call ends and this.filters is defined before rendering my template html?

Sorry if my question is a bit long, if you need any more details just let me know.

Thanks!


问:
how can I get the String from hashCode
I am working on a project where I had got my password field value's hashCode and stored that hashCode in DB for security purposes.Now I want to recover the password from the hashCode.How can I do it? Is it possible to get the String value back from the hashCode?If it is not, can anyone suggest me a better way to store my password in anyother format?

答:
not a good idea, hashCode should never ever be used as identifier to proof equality of objects...

consider this:

```<code>System.out.println("Aa".hashCode());
System.out.println("BB".hashCode());
</code>```

both have the same HashCode 2112 but are holding completely different information

Title: how can I get the String from hashCode

Body:
not a good idea, hashCode should never ever be used as identifier to proof equality of objects...

consider this:

System.out.println("Aa".hashCode());
System.out.println("BB".hashCode());

both have the same HashCode 2112 but are holding completely different information


问:
Numpy's float32 and float comparisons
Continuing from Difference between Python float and numpy float32:

```<code>import numpy as np

a = 58682.7578125
print(type(a), a)
float_32 = np.float32(a)
print(type(float_32), float_32)
print(float_32 == a)
</code>```

Prints:

```<code><class 'float'> 58682.7578125
<class 'numpy.float32'> 58682.8
True
</code>```

I fully understand that comparing floats for equality is not a good idea but still shouldn't this be False (we're talking about differences in the first decimal digit, not in 0.000000001) ? Is it system dependent ? Is this behavior somewhere documented ?

EDIT: Well it's the third decimal:

```<code>print(repr(float_32), repr(a))
# 58682.758 58682.7578125
</code>```

but can I trust repr ? How are those stored internally in the final end ?

EDIT2: people insist that printing float_32 with more precision will give me its representation. However as I already commented according to nympy's docs:

the % formatting operator requires its arguments to be converted to standard python types

and:

```<code>print(repr(float(float_32)))
</code>```

prints

58682.7578125

An interesting insight is given by @MarkDickinson here, apparently repr should be faithful (then he says it's not faithful for np.float32).

So let me reiterate my question as follows:

How can I get at the exact internal representation of float_32 and a in the example ? If these are the same, then problem solved if not,

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ? I 'd guess that it upcasts float_32 to float although @WillemVanOnsem suggests in the comments it's the other way round

My python version:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32

答:
The same value is stored internally, only it doesn't show all digits with a print

Try:

```<code> print "%0.8f" % float_32
</code>```

See related Printing numpy.float64 with full precision

Title: Numpy's float32 and float comparisons

Body:
Continuing from Difference between Python float and numpy float32:

import numpy as np

a = 58682.7578125
print(type(a), a)
float_32 = np.float32(a)
print(type(float_32), float_32)
print(float_32 == a)

Prints:

<class 'float'> 58682.7578125
<class 'numpy.float32'> 58682.8
True

I fully understand that comparing floats for equality is not a good idea but still shouldn't this be False (we're talking about differences in the first decimal digit, not in 0.000000001) ? Is it system dependent ? Is this behavior somewhere documented ?

EDIT: Well it's the third decimal:

print(repr(float_32), repr(a))
# 58682.758 58682.7578125

but can I trust repr ? How are those stored internally in the final end ?

EDIT2: people insist that printing float_32 with more precision will give me its representation. However as I already commented according to nympy's docs:

the % formatting operator requires its arguments to be converted to standard python types

and:

print(repr(float(float_32)))

prints

58682.7578125

An interesting insight is given by @MarkDickinson here, apparently repr should be faithful (then he says it's not faithful for np.float32).

So let me reiterate my question as follows:

How can I get at the exact internal representation of float_32 and a in the example ? If these are the same, then problem solved if not,

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ? I 'd guess that it upcasts float_32 to float although @WillemVanOnsem suggests in the comments it's the other way round

My python version:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32

Body:
The same value is stored internally, only it doesn't show all digits with a print

Try:

 print "%0.8f" % float_32

See related Printing numpy.float64 with full precision


问:
Ajax call does not work, when call the Web Api Get Method. Have you know, what i missed?
I Have a get method in ValuesController in Server side, here am using MVC 4 Web  Api

The Method

```<code>[HttpGet]
        public List<Product> Get()
        {
            return productRepository.ListOfProducts().ToList();
        }
</code>```

and i have call this method via ajax

```<code>$.ajax({
            url: "http://localhost:57260/api/values",
            type: "GET",
            dataType: 'json',
            success: function (data) {
                alert("Ramesh is a yummy ;)");
                for (var i = 0; i < data.length; i++) {
                    $("<tr></tr><td></td>" + data[i].Name + "</td><td></td>" + data[i].Address + "</td><td></td>" + data[i].DOB + "</td></tr>").appendTo("#tbPerson");
                }
            },
            error: function (msg) {
                alert("Ramesh is a fool");
            }
        });
</code>```

This ajax method always go to failure function, does not go to success method

But when i type the url in browser, then it's return json data. See this screen..

BUT Why ajax does not work? It's very strange...

Regard's, Ramesh.

Update :

I can't see console error details, because am using window mobile app, So it's running on the mobile emulator

答:
This will work.</p>

```<code>$.ajax({
    url: "http://localhost:57260/api/values",
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" },
    function (data) {
        alert("Ramesh is a yummy ;)");
        for (var i = 0; i < data.length; i++) {
            $("<tr></tr><td></td>" + data[i].Name + "</td><td></td>" + data[i].Address + "</td><td></td>" + data[i].DOB + "</td></tr>").appendTo("#tbPerson");
        }
    },
    error: function (msg) {
        alert("Ramesh is a fool");
    }
});
</code>```

Body:
I Have a get method in ValuesController in Server side, here am using MVC 4 Web  Api

The Method

[HttpGet]
        public List<Product> Get()
        {
            return productRepository.ListOfProducts().ToList();
        }

and i have call this method via ajax

$.ajax({
            url: "http://localhost:57260/api/values",
            type: "GET",
            dataType: 'json',
            success: function (data) {
                alert("Ramesh is a yummy ;)");
                for (var i = 0; i < data.length; i++) {
                    $("

	" + data[i].Name + "		" + data[i].Address + "		" + data[i].DOB + "
").appendTo("#tbPerson");
                }
            },
            error: function (msg) {
                alert("Ramesh is a fool");
            }
        });

This ajax method always go to failure function, does not go to success method

But when i type the url in browser, then it's return json data. See this screen..

BUT Why ajax does not work? It's very strange...

Regard's, Ramesh.

Update :

I can't see console error details, because am using window mobile app, So it's running on the mobile emulator

Body:
This will work.

$.ajax({
    url: "http://localhost:57260/api/values",
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" },
    function (data) {
        alert("Ramesh is a yummy ;)");
        for (var i = 0; i < data.length; i++) {
            $("<tr></tr><td></td>" + data[i].Name + "</td><td></td>" + data[i].Address + "</td><td></td>" + data[i].DOB + "</td></tr>").appendTo("#tbPerson");
        }
    },
    error: function (msg) {
        alert("Ramesh is a fool");
    }
});


问:
ES6 pass an object to constructor and set property
Look at the below example:

```<code>class Parent {
    constructor({ parentOnlyArg = 'default value' } = {}) {
        this.parentOnlyArg = parentOnlyArg;
    }
}

class Child extends Parent {
    // this class and also any class inheriting from it
    constructor({ visibleStyle = 'inline' } = {}) {

        // I want to pass argument to super as an object
        super(/** args **/);

        this.visibleStyle = visibleStyle;
    }
}

class Child2 extends Parent {
    // Specifying parentOnlyArg as default will change the behaviour
    constructor({ parentOnlyArg = 'another parent value',
                  someOther = 'value' } = {}) {

        // I want to pass argument to super as an object
        super(/** args **/);

        this.someOther = someOther;
    }
}
</code>```

Is it possible to pass on the constructor argument to super?

Seems like it was simpler than I thought

```<code>super(...arguments);
</code>```

I can then create Child using

```<code>var c1 = new Child(); // c.parentOnlyArg = 'default value'
var c2 = new Child2(); // c.parentOnlyArg = 'another parent value'
var c3 = new Child({ parentOnlyArg: 'changed again' }); // c.parentOnlyArg = 'changed again'
</code>```

答:
You could use object destructuring with rest properties. It is not yet implemented by browsers, but BabelJs can transpile it.

function assertEmpty(obj) {
  if (Object.keys(obj).length > 0) {
    throw new Error("Unexpected parameters");
  }
}

class A {
  constructor({ a = "foo", ...rest } = {}) {
    assertEmpty(rest);
    console.log("new A " + a);
  }
}

class B extends A {
  constructor({ b = "bar", ...rest } = {}) {
    super(rest);
    console.log("new B " + b);
  }
}

new B({a:2}); // prints 'new A 2', 'new B bar'
new B({a:4, b:5, c:6}); // throws 'Unexpected parameters'```
</div>
</div>
</p>

<p>In the above snippet parent classes don't see the params consumed by the descendants. If you have problems with that you can do it either as @Bergi or @loganfsmyth suggested. For example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class A {
  constructor(params = {}) {
    const { a = "foo" } = params;
    console.log("a=" + a);
  }
}

class B extends A {
  constructor(params = {}) {
    const { b = "bar" } = params;
    super(params);
    console.log("b=" + b);
  }
}

new B({a:2}); // prints a=2 b=bar
new B({b:5}); // prints a=foo b=5</code>```

Body:
Look at the below example:

class Parent {
    constructor({ parentOnlyArg = 'default value' } = {}) {
        this.parentOnlyArg = parentOnlyArg;
    }
}

class Child extends Parent {
    // this class and also any class inheriting from it
    constructor({ visibleStyle = 'inline' } = {}) {

        // I want to pass argument to super as an object
        super(/** args **/);

        this.visibleStyle = visibleStyle;
    }
}

class Child2 extends Parent {
    // Specifying parentOnlyArg as default will change the behaviour
    constructor({ parentOnlyArg = 'another parent value',
                  someOther = 'value' } = {}) {

        // I want to pass argument to super as an object
        super(/** args **/);

        this.someOther = someOther;
    }
}

Is it possible to pass on the constructor argument to super?

Seems like it was simpler than I thought

super(...arguments);

I can then create Child using

var c1 = new Child(); // c.parentOnlyArg = 'default value'
var c2 = new Child2(); // c.parentOnlyArg = 'another parent value'
var c3 = new Child({ parentOnlyArg: 'changed again' }); // c.parentOnlyArg = 'changed again'

Body:
You could use object destructuring with rest properties. It is not yet implemented by browsers, but <a href="http://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=react%2Cstage-2&targets=&browsers=&builtIns=false&debug=false&experimental=false&loose=false&spec=false&code_lz=GYVwdgxgLglg9mABAQwM6oKYCcoFEC2ADlAJ4AUcARgFYCUiA3gFCKIzCJkDyNG0AdAGsMJVBRq1-AGwxgA5lAAWiAHyIADPWatWSrHADuiMBiO4s-rGQBEAVRMAPQnygYAJokLIsyfBldYqNa0ANwsiAC-TFFMEFJoqIgAgozhEAioUFgg0HBWDMgAvNbAcHDWADSI_DVYGJkRhQwRWuGsCdh4RKRkdZmhbYjpYKhwMtJwcjYmRinWiADUKAOsUTFxCYgAQogYDq5gbokp2kMZWTlQeWQMlMWU3pXVtfVQjc2tOoioIM5WfVAVjphqNxlJJtNTNtEPMlpQgWsmEiZtsbsgAFwAJhaYRRWzR6IALFVKOiAKxVCDogBsOKRQA&playground=true" rel="nofollow noreferrer">BabelJs can transpile it.

function assertEmpty(obj) {
  if (Object.keys(obj).length > 0) {
    throw new Error("Unexpected parameters");
  }
}

class A {
  constructor({ a = "foo", ...rest } = {}) {
    assertEmpty(rest);
    console.log("new A " + a);
  }
}

class B extends A {
  constructor({ b = "bar", ...rest } = {}) {
    super(rest);
    console.log("new B " + b);
  }
}

new B({a:2}); // prints 'new A 2', 'new B bar'
new B({a:4, b:5, c:6}); // throws 'Unexpected parameters'

In the above snippet parent classes don't see the params consumed by the descendants. If you have problems with that you can do it either as @Bergi or @loganfsmyth suggested. For example:

class A {
  constructor(params = {}) {
    const { a = "foo" } = params;
    console.log("a=" + a);
  }
}

class B extends A {
  constructor(params = {}) {
    const { b = "bar" } = params;
    super(params);
    console.log("b=" + b);
  }
}

new B({a:2}); // prints a=2 b=bar
new B({b:5}); // prints a=foo b=5


问:
Automatic Persistence : Unable to bring up cache with web console generated models : Failed to register query type exception is thrown
I used the new Web console to generate the models/artifacts to be used for automatic persistence.

But when i bring up a Spring Boot server with IgniteSpringBean it fails due to a 'query registration issue', below is the stack trace.

I suspect from searching online that some word used in a column is not being accepted by H2 but couldn't figure that out from the exception...does anyone have a clue?

```<code>**SEVERE: Got exception while starting (will rollback startup routine).
class org.apache.ignite.IgniteCheckedException: Failed to register query type: QueryTypeDescriptorImpl [space=DcmEmpCache, name=Emp, tblName=null, fields={}, idxs={}, fullTextIdx=null, keyCls=class java.lang
.String, valCls=class java.lang.Object, keyTypeName=java.lang.String, valTypeName=com.brocade.dcm.domain.model.Emp, valTextIdx=false, typeId=0, affKey=null, keyFieldName=null, valFieldName=null, obsolete=fal
se]**
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.registerType(IgniteH2Indexing.java:1866)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.registerCache0(GridQueryProcessor.java:1306)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.onCacheStart0(GridQueryProcessor.java:756)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.onCacheStart(GridQueryProcessor.java:817)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.startCache(GridCacheProcessor.java:1265)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.onKernalStart(GridCacheProcessor.java:898)
        at org.apache.ignite.internal.IgniteKernal.start(IgniteKernal.java:1013)
        at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start0(IgnitionEx.java:1895)
        at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start(IgnitionEx.java:1647)
        at org.apache.ignite.internal.IgnitionEx.start0(IgnitionEx.java:1075)
        at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:573)
        at org.apache.ignite.IgniteSpring.start(IgniteSpring.java:66)
        at org.apache.ignite.IgniteSpringBean.afterPropertiesSet(IgniteSpringBean.java:159)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.brocade.dcm.server.ObjectCacheMgrApplication.main(ObjectCacheMgrApplication.java:12)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)

**Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE ""DcmEmpCache"".EMP (_KEY VARCHAR VISIBLE[*] NOT NULL,_VAL OTHER VISIBLE,_VER OTHER INVISIBLE) ENGINE ""org.apache.ignite.
internal.processors.query.h2.IgniteH2Indexing$H2TableEngine"" "; expected "(, FOR, UNSIGNED, NOT, NULL, AS, DEFAULT, GENERATED, NOT, NULL, AUTO_INCREMENT, BIGSERIAL, SERIAL, IDENTITY, NULL_TO_DEFAULT, SEQUEN
CE, SELECTIVITY, COMMENT, CONSTRAINT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
CREATE TABLE "DcmEmpCache".Emp (_key VARCHAR VISIBLE NOT NULL,_val OTHER VISIBLE,_ver OTHER INVISIBLE) engine "org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing$H2TableEngine" [42001-193]**
        at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
        at org.h2.message.DbException.getSyntaxError(DbException.java:205)
        at org.h2.command.Parser.getSyntaxError(Parser.java:537)
        at org.h2.command.Parser.read(Parser.java:3186)
        at org.h2.command.Parser.readIfMore(Parser.java:885)
        at org.h2.command.Parser.parseCreateTable(Parser.java:6043)
        at org.h2.command.Parser.parseCreate(Parser.java:4238)
        at org.h2.command.Parser.parsePrepared(Parser.java:362)
        at org.h2.command.Parser.parse(Parser.java:317)
        at org.h2.command.Parser.parse(Parser.java:293)
        at org.h2.command.Parser.prepareCommand(Parser.java:254)
        at org.h2.engine.Session.prepareLocal(Session.java:561)
        at org.h2.engine.Session.prepareCommand(Session.java:502)
        at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1203)
        at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170)
        at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing$H2TableEngine.createTable(IgniteH2Indexing.java:3975)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.createTable(IgniteH2Indexing.java:2006)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.registerType(IgniteH2Indexing.java:1859)
        ... 64 more
</code>```

Below is my table schema,

```<code>**CREATE TABLE dcm.emp
(
id text NOT NULL,
ename text,
job text,
mgr text,
hiredate date,
sal integer,
comm integer,
deptid text,
CONSTRAINT pk_emp PRIMARY KEY (id),
CONSTRAINT fk_deptid FOREIGN KEY (deptid)
REFERENCES dcm.dept (id) MATCH SIMPLE
ON UPDATE RESTRICT ON DELETE CASCADE
)
WITH (
  OIDS=FALSE
);
ALTER TABLE dcm.emp
OWNER TO postgres;**
</code>```

Regards,

Muthu

UPDATE (Aug 08 2017) : I still get errors with the latest 2.1 version,

```<code>INFO: Started cache [name=ignite-sys-cache, memoryPolicyName=sysMemPlc, mode=REPLICATED, atomicity=TRANSACTIONAL]
Aug 03, 2017 12:34:36 PM org.apache.ignite.logger.java.JavaLogger error
SEVERE: Failed to reinitialize local partitions (preloading will be stopped): GridDhtPartitionExchangeId [topVer=AffinityTopologyVersion [topVer=1, minorTopVer=0], nodeId=e9b2cf46, evt=NODE_JOINED]
class org.apache.ignite.IgniteCheckedException: Failed to register query type: QueryTypeDescriptorImpl [cacheName=DeptCache, name=Dept, tblName=DEPT, fields={DNAME=class java.lang.String, LOC=class java.lang
.String, DEPTID=class java.lang.String}, idxs={}, fullTextIdx=null, keyCls=class java.lang.String, valCls=class java.lang.Object, keyTypeName=java.lang.String, valTypeName=com.brocade.dcm.domain.model.Dept,
valTextIdx=false, typeId=1038936471, affKey=null, keyFieldName=deptid, valFieldName=null, obsolete=false]
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.registerType(IgniteH2Indexing.java:1532)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.registerCache0(GridQueryProcessor.java:1424)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.onCacheStart0(GridQueryProcessor.java:784)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.onCacheStart(GridQueryProcessor.java:845)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.startCache(GridCacheProcessor.java:1185)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.prepareCacheStart(GridCacheProcessor.java:1884)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.startCachesOnLocalJoin(GridCacheProcessor.java:1755)
        at org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture.init(GridDhtPartitionsExchangeFuture.java:619)
        at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body(GridCachePartitionExchangeManager.java:1901)
        at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:110)
        at java.lang.Thread.run(Unknown Source)
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE ""DEPTS"".""DEPT"" (_KEY VARCHAR INVISIBLE[*] NOT NULL,_VAL OTHER INVISIBLE,_VER OTHER INVISIBLE,""DNAME"" VARCHAR,""LOC""
 VARCHAR,""DEPTID"" VARCHAR) ENGINE ""org.apache.ignite.internal.processors.query.h2.H2TableEngine"" "; expected "(, FOR, UNSIGNED, NOT, NULL, AS, DEFAULT, GENERATED, NOT, NULL, AUTO_INCREMENT, BIGSERIAL, SE
RIAL, IDENTITY, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
CREATE TABLE "DEPTS"."DEPT" (_KEY VARCHAR INVISIBLE NOT NULL,_VAL OTHER INVISIBLE,_VER OTHER INVISIBLE,"DNAME" VARCHAR,"LOC" VARCHAR,"DEPTID" VARCHAR) engine "org.apache.ignite.internal.processors.query.h2.H
2TableEngine" [42001-193]
        at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
        at org.h2.message.DbException.getSyntaxError(DbException.java:205)
        at org.h2.command.Parser.getSyntaxError(Parser.java:537)
        at org.h2.command.Parser.read(Parser.java:3186)
        at org.h2.command.Parser.readIfMore(Parser.java:885)
        at org.h2.command.Parser.parseCreateTable(Parser.java:6043)
        at org.h2.command.Parser.parseCreate(Parser.java:4238)
        at org.h2.command.Parser.parsePrepared(Parser.java:362)
        at org.h2.command.Parser.parse(Parser.java:317)
        at org.h2.command.Parser.parse(Parser.java:293)
        at org.h2.command.Parser.prepareCommand(Parser.java:254)
        at org.h2.engine.Session.prepareLocal(Session.java:561)
        at org.h2.engine.Session.prepareCommand(Session.java:502)
        at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1203)
        at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170)
        at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
        at org.apache.ignite.internal.processors.query.h2.H2TableEngine.createTable(H2TableEngine.java:68)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.createTable(IgniteH2Indexing.java:1606)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.registerType(IgniteH2Indexing.java:1525)
        ... 10 more
</code>```

Any clue?

答:
Muthu,

I reproduced this issue and created issue in Apache Ignite JIRA.

I will fix this shortly. Fix will be available in next ignite-2.1 release.

Body:
I used the new Web console to generate the models/artifacts to be used for automatic persistence.

But when i bring up a Spring Boot server with IgniteSpringBean it fails due to a 'query registration issue', below is the stack trace.

I suspect from searching online that some word used in a column is not being accepted by H2 but couldn't figure that out from the exception...does anyone have a clue?

**SEVERE: Got exception while starting (will rollback startup routine).
class org.apache.ignite.IgniteCheckedException: Failed to register query type: QueryTypeDescriptorImpl [space=DcmEmpCache, name=Emp, tblName=null, fields={}, idxs={}, fullTextIdx=null, keyCls=class java.lang
.String, valCls=class java.lang.Object, keyTypeName=java.lang.String, valTypeName=com.brocade.dcm.domain.model.Emp, valTextIdx=false, typeId=0, affKey=null, keyFieldName=null, valFieldName=null, obsolete=fal
se]**
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.registerType(IgniteH2Indexing.java:1866)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.registerCache0(GridQueryProcessor.java:1306)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.onCacheStart0(GridQueryProcessor.java:756)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.onCacheStart(GridQueryProcessor.java:817)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.startCache(GridCacheProcessor.java:1265)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.onKernalStart(GridCacheProcessor.java:898)
        at org.apache.ignite.internal.IgniteKernal.start(IgniteKernal.java:1013)
        at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start0(IgnitionEx.java:1895)
        at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start(IgnitionEx.java:1647)
        at org.apache.ignite.internal.IgnitionEx.start0(IgnitionEx.java:1075)
        at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:573)
        at org.apache.ignite.IgniteSpring.start(IgniteSpring.java:66)
        at org.apache.ignite.IgniteSpringBean.afterPropertiesSet(IgniteSpringBean.java:159)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.brocade.dcm.server.ObjectCacheMgrApplication.main(ObjectCacheMgrApplication.java:12)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)

**Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE ""DcmEmpCache"".EMP (_KEY VARCHAR VISIBLE[*] NOT NULL,_VAL OTHER VISIBLE,_VER OTHER INVISIBLE) ENGINE ""org.apache.ignite.
internal.processors.query.h2.IgniteH2Indexing$H2TableEngine"" "; expected "(, FOR, UNSIGNED, NOT, NULL, AS, DEFAULT, GENERATED, NOT, NULL, AUTO_INCREMENT, BIGSERIAL, SERIAL, IDENTITY, NULL_TO_DEFAULT, SEQUEN
CE, SELECTIVITY, COMMENT, CONSTRAINT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
CREATE TABLE "DcmEmpCache".Emp (_key VARCHAR VISIBLE NOT NULL,_val OTHER VISIBLE,_ver OTHER INVISIBLE) engine "org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing$H2TableEngine" [42001-193]**
        at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
        at org.h2.message.DbException.getSyntaxError(DbException.java:205)
        at org.h2.command.Parser.getSyntaxError(Parser.java:537)
        at org.h2.command.Parser.read(Parser.java:3186)
        at org.h2.command.Parser.readIfMore(Parser.java:885)
        at org.h2.command.Parser.parseCreateTable(Parser.java:6043)
        at org.h2.command.Parser.parseCreate(Parser.java:4238)
        at org.h2.command.Parser.parsePrepared(Parser.java:362)
        at org.h2.command.Parser.parse(Parser.java:317)
        at org.h2.command.Parser.parse(Parser.java:293)
        at org.h2.command.Parser.prepareCommand(Parser.java:254)
        at org.h2.engine.Session.prepareLocal(Session.java:561)
        at org.h2.engine.Session.prepareCommand(Session.java:502)
        at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1203)
        at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170)
        at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing$H2TableEngine.createTable(IgniteH2Indexing.java:3975)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.createTable(IgniteH2Indexing.java:2006)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.registerType(IgniteH2Indexing.java:1859)
        ... 64 more

Below is my table schema,

**CREATE TABLE dcm.emp
(
id text NOT NULL,
ename text,
job text,
mgr text,
hiredate date,
sal integer,
comm integer,
deptid text,
CONSTRAINT pk_emp PRIMARY KEY (id),
CONSTRAINT fk_deptid FOREIGN KEY (deptid)
REFERENCES dcm.dept (id) MATCH SIMPLE
ON UPDATE RESTRICT ON DELETE CASCADE
)
WITH (
  OIDS=FALSE
);
ALTER TABLE dcm.emp
OWNER TO postgres;**

Regards,

Muthu

UPDATE (Aug 08 2017) : I still get errors with the latest 2.1 version,

INFO: Started cache [name=ignite-sys-cache, memoryPolicyName=sysMemPlc, mode=REPLICATED, atomicity=TRANSACTIONAL]
Aug 03, 2017 12:34:36 PM org.apache.ignite.logger.java.JavaLogger error
SEVERE: Failed to reinitialize local partitions (preloading will be stopped): GridDhtPartitionExchangeId [topVer=AffinityTopologyVersion [topVer=1, minorTopVer=0], nodeId=e9b2cf46, evt=NODE_JOINED]
class org.apache.ignite.IgniteCheckedException: Failed to register query type: QueryTypeDescriptorImpl [cacheName=DeptCache, name=Dept, tblName=DEPT, fields={DNAME=class java.lang.String, LOC=class java.lang
.String, DEPTID=class java.lang.String}, idxs={}, fullTextIdx=null, keyCls=class java.lang.String, valCls=class java.lang.Object, keyTypeName=java.lang.String, valTypeName=com.brocade.dcm.domain.model.Dept,
valTextIdx=false, typeId=1038936471, affKey=null, keyFieldName=deptid, valFieldName=null, obsolete=false]
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.registerType(IgniteH2Indexing.java:1532)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.registerCache0(GridQueryProcessor.java:1424)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.onCacheStart0(GridQueryProcessor.java:784)
        at org.apache.ignite.internal.processors.query.GridQueryProcessor.onCacheStart(GridQueryProcessor.java:845)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.startCache(GridCacheProcessor.java:1185)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.prepareCacheStart(GridCacheProcessor.java:1884)
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.startCachesOnLocalJoin(GridCacheProcessor.java:1755)
        at org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture.init(GridDhtPartitionsExchangeFuture.java:619)
        at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body(GridCachePartitionExchangeManager.java:1901)
        at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:110)
        at java.lang.Thread.run(Unknown Source)
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE ""DEPTS"".""DEPT"" (_KEY VARCHAR INVISIBLE[*] NOT NULL,_VAL OTHER INVISIBLE,_VER OTHER INVISIBLE,""DNAME"" VARCHAR,""LOC""
 VARCHAR,""DEPTID"" VARCHAR) ENGINE ""org.apache.ignite.internal.processors.query.h2.H2TableEngine"" "; expected "(, FOR, UNSIGNED, NOT, NULL, AS, DEFAULT, GENERATED, NOT, NULL, AUTO_INCREMENT, BIGSERIAL, SE
RIAL, IDENTITY, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
CREATE TABLE "DEPTS"."DEPT" (_KEY VARCHAR INVISIBLE NOT NULL,_VAL OTHER INVISIBLE,_VER OTHER INVISIBLE,"DNAME" VARCHAR,"LOC" VARCHAR,"DEPTID" VARCHAR) engine "org.apache.ignite.internal.processors.query.h2.H
2TableEngine" [42001-193]
        at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
        at org.h2.message.DbException.getSyntaxError(DbException.java:205)
        at org.h2.command.Parser.getSyntaxError(Parser.java:537)
        at org.h2.command.Parser.read(Parser.java:3186)
        at org.h2.command.Parser.readIfMore(Parser.java:885)
        at org.h2.command.Parser.parseCreateTable(Parser.java:6043)
        at org.h2.command.Parser.parseCreate(Parser.java:4238)
        at org.h2.command.Parser.parsePrepared(Parser.java:362)
        at org.h2.command.Parser.parse(Parser.java:317)
        at org.h2.command.Parser.parse(Parser.java:293)
        at org.h2.command.Parser.prepareCommand(Parser.java:254)
        at org.h2.engine.Session.prepareLocal(Session.java:561)
        at org.h2.engine.Session.prepareCommand(Session.java:502)
        at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1203)
        at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170)
        at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
        at org.apache.ignite.internal.processors.query.h2.H2TableEngine.createTable(H2TableEngine.java:68)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.createTable(IgniteH2Indexing.java:1606)
        at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.registerType(IgniteH2Indexing.java:1525)
        ... 10 more

Any clue?


问:
Eclipse CDT formatting - wrap after operator
I would like to know how to achieve this in EclipseCDT formater:

Input:

```<code>if ((example1 + example1 < example2) || (example3 + example4 < example5) || (example1 + example1 < example2))
{
     printf("sth");
}
</code>```

Expected:

```<code>if ((example1 + example1 < example2) || (example3 + example4 < example5) ||
    (example1 + example1 < example2))
{
   printf("sth");
}
</code>```

or

```<code>if ((example1 + example1 < example2) ||
    (example3 + example4 < example5) ||
    (example1 + example1 < example2))
{
   printf("sth");
}
</code>```

Eclipse gives me this(wrap before operator):

```<code>if ((example1 + example1 < example2)
   || (example3 + example4 < example5)
   || (example1 + example1 < example2))
{
    printf("sth");
}
</code>```

There is another option, clang-formatter but I cannot use it now.

答:
This feature is available in other versions of Eclipse (for instance the standard Java one), but not in Eclipse CDT.

A request was opened in Bugzilla, you should probably upvote it if you are interested in having this feature added to the CDT product.

Body:
I would like to know how to achieve this in EclipseCDT formater:

Input:

if ((example1 + example1 < example2) || (example3 + example4 < example5) || (example1 + example1 < example2))
{
     printf("sth");
}

Expected:

if ((example1 + example1 < example2) || (example3 + example4 < example5) ||
    (example1 + example1 < example2))
{
   printf("sth");
}

or

if ((example1 + example1 < example2) ||
    (example3 + example4 < example5) ||
    (example1 + example1 < example2))
{
   printf("sth");
}

Eclipse gives me this(wrap before operator):

if ((example1 + example1 < example2)
   || (example3 + example4 < example5)
   || (example1 + example1 < example2))
{
    printf("sth");
}

There is another option, clang-formatter but I cannot use it now.


问:
Specflow table column binding prevent Nulls
Given the following code:

```<code>public class Bob {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

Feature: Bob checker

Scenario: Check Bob
  Given I have the following Bob
     | Name   | Age | Hieght |
     | Robert | 63  | 1.87   |
  When . . . .
  Then . . . .

[Given(@"I have the following Bob")]
public void IHaveTheFollowingBob(Table table) {
    var bob = table.CreateInstance<Bob>();
}
</code>```

You'l notice the word 'Height' is not spelt correctly in the table.  The CreateInstance method will still work but the 'Height' on the Bob object will be 0 or for reference type, null.

Is there a way to make SpecFlow fail if the column doesn't bind to the Type provided.  Thanks

答:
I should RTFM. table.CompareToInstance(bob); Will fail if the Property is not there or is not populated the correctly.  If you use this in conjuction with table.CreateInstance you will get failures where there are nulls.  Leaving Q&A here just in case anyone else has brain fail.

SpecFlow Assist Helper, CompareToInstance

If you have have complex types you can represent them in the table and use IValueRetrieverand IValueComparer extensions

For example consider the following micky mouse code:

```<code>public class Bob {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

public class BobModel {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

Feature: Bob checker

Scenario: Check Bob
  Given I have the following Bob
     | Name   | Age | Hieght |
     | Robert | 63  | 1.87   |
  When I map this to the model
  Then Bob the model looks like this
     | Name   | Age | Height |
     | Robert | 63  | 1.87   |

[Given(@"I have the following Bob")]
public void IHaveTheFollowingBob(Table table) {
    var bob = table.CreateInstance<Bob>();
}

[When(@"I map this to the model")]
public void IMapThisToTheModel() {
   sut = production.Map(bob);
}

[Then(@"Bob the model looks like this") {
public void BobTheModelLooksLikeThis(Table table) {
   table.CompareToInstance<BobModel>(sut);
}
</code>```

In this instance if there was a typo in the second table it would fail saying it can't find the property.  If there is a typo in the first table then this will still be null but the assertion will fail. No false positives

Body:
Given the following code:

public class Bob {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

Feature: Bob checker

Scenario: Check Bob
  Given I have the following Bob
     | Name   | Age | Hieght |
     | Robert | 63  | 1.87   |
  When . . . .
  Then . . . .

[Given(@"I have the following Bob")]
public void IHaveTheFollowingBob(Table table) {
    var bob = table.CreateInstance<Bob>();
}

You'l notice the word 'Height' is not spelt correctly in the table.  The CreateInstance method will still work but the 'Height' on the Bob object will be 0 or for reference type, null.

Is there a way to make SpecFlow fail if the column doesn't bind to the Type provided.  Thanks

Body:
I should RTFM. table.CompareToInstance(bob); Will fail if the Property is not there or is not populated the correctly.  If you use this in conjuction with table.CreateInstance you will get failures where there are nulls.  Leaving Q&A here just in case anyone else has brain fail.

SpecFlow Assist Helper, CompareToInstance

If you have have complex types you can represent them in the table and use IValueRetrieverand IValueComparer extensions

For example consider the following micky mouse code:

public class Bob {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

public class BobModel {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

Feature: Bob checker

Scenario: Check Bob
  Given I have the following Bob
     | Name   | Age | Hieght |
     | Robert | 63  | 1.87   |
  When I map this to the model
  Then Bob the model looks like this
     | Name   | Age | Height |
     | Robert | 63  | 1.87   |

[Given(@"I have the following Bob")]
public void IHaveTheFollowingBob(Table table) {
    var bob = table.CreateInstance<Bob>();
}

[When(@"I map this to the model")]
public void IMapThisToTheModel() {
   sut = production.Map(bob);
}

[Then(@"Bob the model looks like this") {
public void BobTheModelLooksLikeThis(Table table) {
   table.CompareToInstance<BobModel>(sut);
}

In this instance if there was a typo in the second table it would fail saying it can't find the property.  If there is a typo in the first table then this will still be null but the assertion will fail. No false positives


问:
Creating an array using folder names using Bash
How can I create an array consists of folder names?
For example, I have set of folders with names A, B, C, and I want to create the array arr=(A B C).

I tried this:

```<code>arr=$(ls ~/Desktop/C\ study/seydtb )
</code>```

But after that when I create files using this arr

```<code>for ((i=0; i<${#arr[@]}; i++)); do
    touch ${arr[$i]}.sey
</code>```

I get this:

```<code>A B C.sey
</code>```

Only the last one has the .sey suffix.

答:
Do not use ls, if you need globbing.

```<code>a=(~/Desktop/C\ study/seydtb/*)
for i in "${a[@]}"; do
  echo $i
done
</code>```

Body:
How can I create an array consists of folder names?
For example, I have set of folders with names A, B, C, and I want to create the array arr=(A B C).

I tried this:

arr=$(ls ~/Desktop/C\ study/seydtb )

But after that when I create files using this arr

for ((i=0; i<${#arr[@]}; i++)); do
    touch ${arr[$i]}.sey

I get this:

A B C.sey

Only the last one has the .sey suffix.

Body:
Do not use ls, if you need globbing.

a=(~/Desktop/C\ study/seydtb/*)
for i in "${a[@]}"; do
  echo $i
done


问:
How to Get Array Inside stdClass
I am trying to decode with json
http://digitsolutions4u.com/apps_services/statuslist.php?catid=1
like this

```<code><?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "```";
print_r($data);
echo "```";
?>
</code>```

i want to get all "statusdesc" Values after decode.
I am getting results something like this

```<code>stdClass Object
(
    [posts] => Array
        (
            [0] => stdClass Object
                (
                    [statusid] => 1329
                    [statusdesc] => love86.jpg
                )
)
)
</code>```

i just want to list out all statusdesc available on the page like
love86.jpg
love87.jpg
love88.jpg
and so on. Anyone can provide me solution(code)  for this? I have tried several threads, but no success.

Title: How to Get Array Inside stdClass

Body:
I am trying to decode with json
http://digitsolutions4u.com/apps_services/statuslist.php?catid=1
like this

<?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "
";
print_r($data);
echo "
";
?>

i want to get all "statusdesc" Values after decode.
I am getting results something like this

stdClass Object
(
    [posts] => Array
        (
            [0] => stdClass Object
                (
                    [statusid] => 1329
                    [statusdesc] => love86.jpg
                )
)
)

i just want to list out all statusdesc available on the page like
love86.jpg
love87.jpg
love88.jpg
and so on. Anyone can provide me solution(code)  for this? I have tried several threads, but no success.


问:
Setting up an Mlogit in R with many observations for each category
I'm trying to use Mlogit in R, I'm a little new to logits, and I'm having trouble setting up my problem in the Mlogit framework. I'm actually not entirely sure that mlogit is the right approach. Here is an analogous problem.

Consider a baseball dataset, with an outcome variable that takes on "out" "single" "double" "triple" and "homerun." For explanatory variables, we have the name of the batter, the name of the pitcher, and the stadium. There are hundreds of observations for each batter, including many with the batter facing the same pitcher.

I figured this is definitely a multinomial logit because I have multiple categorical outcomes, but I am not sure because all of the documentation seems to be dealing with "choices" between alternatives, which this isn't really. I tried to start my logit model by having a factor variable for the hitter, another one for the pitcher, and another one for the stadium. When I tried this in R, I get

Error in row.names<-.data.frame(*tmp*, value = value) :  invalid 'row.names' length

With some googling I think maybe it is expecting only one observation for each combination of hitter, pitcher, and park? Maybe not? What am I doing wrong? How should I set this up?

Edit:
Example of data here

https://docs.google.com/spreadsheets/d/19fiq_QEMj4nAPcTqIRxeaYNPgqeHxKAEuPrfHMeIJ7o/edit?usp=sharing

答:
Here are some suggestions on how you can start analyzing your data.

```<code># Your dataset
dts <- structure(list(outcome = c(1L, 1L, 2L, 3L, 1L, 3L, 2L, 3L, 3L,
3L, 3L, 1L, 2L, 2L, 2L, 1L, 3L, 2L, 2L, 2L, 1L, 2L, 3L, 2L, 2L,
2L, 2L, 1L, 1L, 2L, 3L, 2L, 3L, 1L, 2L, 2L, 3L, 2L, 3L, 3L, 3L,
2L, 1L, 1L, 1L, 2L, 3L, 2L, 1L), hitter = structure(c(3L, 3L,
3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("james",
"jill", "john"), class = "factor"), pitcher = structure(c(3L,
3L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 2L, 2L, 2L, 2L, 2L, 3L, 1L, 1L,
2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 3L, 2L, 1L, 2L, 3L, 2L,
3L, 2L, 1L, 1L, 2L, 2L, 1L, 3L, 3L, 1L, 2L, 2L, 1L, 1L, 2L, 2L
), .Label = c("bill", "bob", "brett"), class = "factor"), place = structure(c(3L,
3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 5L,
5L, 5L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L
), .Label = c("ca", "co", "dc", "ny", "tn"), class = "factor")), .Names = c("outcome",
"hitter", "pitcher", "place"), class = "data.frame", row.names = c(NA,
-49L))

# Estimation of a multinomial logistic regression model
library(mlogit)
dts.wide <- mlogit.data(dts, choice="outcome", shape="wide")
fit.mlogit <- mlogit(outcome ~ 1 | hitter+pitcher+place, data=dts.wide)

# Results
library(stargazer)
stargazer(fit.mlogit, type="text")

# Model coefficients with standard errors and statistical significance (stars)
==========================================
                   Dependent variable:
               ---------------------------
                         outcome
------------------------------------------
2:(intercept)            19.456
                       (3,056.626)

3:(intercept)            35.179
                       (4,172.540)

2:hitterjill             -17.543
                       (3,056.625)

3:hitterjill             -33.117
                       (4,172.540)

2:hitterjohn             -0.188
                         (0.996)

3:hitterjohn             -1.410
                         (1.056)

2:pitcherbob             -0.070
                         (1.005)

3:pitcherbob             -1.270
                         (1.091)

2:pitcherbrett           -0.908
                         (1.063)

3:pitcherbrett           -2.284*
                         (1.257)

2:placeco                -1.655
                         (1.557)

3:placeco                -17.688
                       (2,840.270)

2:placedc                -19.428
                       (3,056.626)

3:placedc                -34.479
                       (4,172.540)

2:placeny                -18.802
                       (3,056.625)

3:placeny                -32.873
                       (4,172.540)

2:placetn                -18.885
                       (3,056.626)

3:placetn                -32.140
                       (4,172.540)

------------------------------------------
Observations               49
R2                        0.155
Log Likelihood           -44.605
LR Test             16.388 (df = 18)
==========================================
Note:          *p<0.1; **p<0.05; ***p<0.01
</code>```

More details on the estimation of multinomial logistic models in R are available here.

Body:
Here are some suggestions on how you can start analyzing your data.

# Your dataset
dts <- structure(list(outcome = c(1L, 1L, 2L, 3L, 1L, 3L, 2L, 3L, 3L,
3L, 3L, 1L, 2L, 2L, 2L, 1L, 3L, 2L, 2L, 2L, 1L, 2L, 3L, 2L, 2L,
2L, 2L, 1L, 1L, 2L, 3L, 2L, 3L, 1L, 2L, 2L, 3L, 2L, 3L, 3L, 3L,
2L, 1L, 1L, 1L, 2L, 3L, 2L, 1L), hitter = structure(c(3L, 3L,
3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("james",
"jill", "john"), class = "factor"), pitcher = structure(c(3L,
3L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 2L, 2L, 2L, 2L, 2L, 3L, 1L, 1L,
2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 3L, 2L, 1L, 2L, 3L, 2L,
3L, 2L, 1L, 1L, 2L, 2L, 1L, 3L, 3L, 1L, 2L, 2L, 1L, 1L, 2L, 2L
), .Label = c("bill", "bob", "brett"), class = "factor"), place = structure(c(3L,
3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 5L,
5L, 5L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L
), .Label = c("ca", "co", "dc", "ny", "tn"), class = "factor")), .Names = c("outcome",
"hitter", "pitcher", "place"), class = "data.frame", row.names = c(NA,
-49L))

# Estimation of a multinomial logistic regression model
library(mlogit)
dts.wide <- mlogit.data(dts, choice="outcome", shape="wide")
fit.mlogit <- mlogit(outcome ~ 1 | hitter+pitcher+place, data=dts.wide)

# Results
library(stargazer)
stargazer(fit.mlogit, type="text")

# Model coefficients with standard errors and statistical significance (stars)
==========================================
                   Dependent variable:
               ---------------------------
                         outcome
------------------------------------------
2:(intercept)            19.456
                       (3,056.626)

3:(intercept)            35.179
                       (4,172.540)

2:hitterjill             -17.543
                       (3,056.625)

3:hitterjill             -33.117
                       (4,172.540)

2:hitterjohn             -0.188
                         (0.996)

3:hitterjohn             -1.410
                         (1.056)

2:pitcherbob             -0.070
                         (1.005)

3:pitcherbob             -1.270
                         (1.091)

2:pitcherbrett           -0.908
                         (1.063)

3:pitcherbrett           -2.284*
                         (1.257)

2:placeco                -1.655
                         (1.557)

3:placeco                -17.688
                       (2,840.270)

2:placedc                -19.428
                       (3,056.626)

3:placedc                -34.479
                       (4,172.540)

2:placeny                -18.802
                       (3,056.625)

3:placeny                -32.873
                       (4,172.540)

2:placetn                -18.885
                       (3,056.626)

3:placetn                -32.140
                       (4,172.540)

------------------------------------------
Observations               49
R2                        0.155
Log Likelihood           -44.605
LR Test             16.388 (df = 18)
==========================================
Note:          *p<0.1; **p<0.05; ***p<0.01

More details on the estimation of multinomial logistic models in R are available here.


问:
How to find the index of an item in an array of class in Swift?
Well first of all we all know that finding an index of an array is easy but I got stump finding an index of an item in an array which contains multiple structs.

This is my class:

```<code>class Patient{
private var id: Int
private var name: String
private var gender: String
private var mileage: Double

//global variable
var globalPatientID:Int{
    return id
}
var globalPatientName:String{
    return name
}
var globalPatientGender:String{
    return gender
}
var globalPatientMileAge:Double{
    return mileage
}

init(id:Int, name:String, gender:String, mileage:Double){
    self.id = id
    self.name = name
    self.gender = gender
    self.mileage = mileage
    }
}
</code>```

This is my array:

```<code>let AppUserID = prefs.objectForKey("AppUserID")

        for var i=0; i<nou; ++i{
            numberOfUsersExisting = nou

            if (AppUserID as? String == json[0][i]["App_ID"].stringValue){
                print("Assigning AppUserID")
                appUserMileage = json[0][i]["Mileage"].doubleValue
            }

            pSample += [Patient(id: json[0][i]["ID"].intValue, name: json[0][i]["Name"].stringValue, gender: json[0][i]["Gender"].stringValue, mileage: json[0][i]["Mileage"].doubleValue)]

            pSample.sortInPlace({$0.globalPatientMileAge < $1.globalPatientMileAge})
        }
</code>```

So pSample is initially a blank array and it appends a class of items through a loop.

The sortInPlace function helps me to sort pSample based on globalPatientMilaAge.

So this got me thinking, how do I get the index of my AppUserID(which I cast it as a String) from the array of class?

I tried using this function but it doesn't seems working because I'm looping through classes instead of items inside a class.

```<code>appUserRanking = pSample.indexOf("\(AppUserID)")
</code>```

答:
In Swift 3 and above mapping works like this</p>

```<code>appUserRanking  = pSample.index(where: {$0.globalPatientID == AppUserID})
</code>```

Body:
Well first of all we all know that finding an index of an array is easy but I got stump finding an index of an item in an array which contains multiple structs.

This is my class:

class Patient{
private var id: Int
private var name: String
private var gender: String
private var mileage: Double

//global variable
var globalPatientID:Int{
    return id
}
var globalPatientName:String{
    return name
}
var globalPatientGender:String{
    return gender
}
var globalPatientMileAge:Double{
    return mileage
}

init(id:Int, name:String, gender:String, mileage:Double){
    self.id = id
    self.name = name
    self.gender = gender
    self.mileage = mileage
    }
}

This is my array:

let AppUserID = prefs.objectForKey("AppUserID")

        for var i=0; i<nou; ++i{
            numberOfUsersExisting = nou

            if (AppUserID as? String == json[0][i]["App_ID"].stringValue){
                print("Assigning AppUserID")
                appUserMileage = json[0][i]["Mileage"].doubleValue
            }

            pSample += [Patient(id: json[0][i]["ID"].intValue, name: json[0][i]["Name"].stringValue, gender: json[0][i]["Gender"].stringValue, mileage: json[0][i]["Mileage"].doubleValue)]

            pSample.sortInPlace({$0.globalPatientMileAge < $1.globalPatientMileAge})
        }

So pSample is initially a blank array and it appends a class of items through a loop.

The sortInPlace function helps me to sort pSample based on globalPatientMilaAge.

So this got me thinking, how do I get the index of my AppUserID(which I cast it as a String) from the array of class?

I tried using this function but it doesn't seems working because I'm looping through classes instead of items inside a class.

appUserRanking = pSample.indexOf("\(AppUserID)")

Body:
In Swift 3 and above mapping works like this

appUserRanking  = pSample.index(where: {$0.globalPatientID == AppUserID})


答:
Hashing is an one-way function (it should be at least), so you cannot recover the password from the hash.

However, you can apply the same hashing to any string and compare it to the hash of the password, so you can check if they match.

With good hashing, the chances of having two strings with the same hash are quite low, so you can compare the hash of the password (which you can store) and the hash of another string to determine if they are the same.

Another point is that hashCode is not a good way to produce such hashes, as we can easily having two objects with same hashCode. You can use implementations such as PBKDF2, BCrypt, etc.

Title: how can I get the String from hashCode

Body: I am working on a project where I had got my password field value's hashCode and stored that hashCode in DB for security purposes.Now I want to recover the password from the hashCode.How can I do it? Is it possible to get the String value back from the hashCode?If it is not, can anyone suggest me a better way to store my password in anyother format?


问:
How to make a diference of money with respect to currency rate movements
I want to make a diffrence of currency rate movements between May and June expressed in total amount of loan people borrowed in CZK (Czech Koruna) with relation to EUR.
e.g.: People have borrowed from my company money in a amount of 27M CZK (corresponding to 1M EUR) in May, which is only 0.89M EUR in June due to the currency rate movements.

I've come with:

```<code>    SELECT
    SUM((
       SELECT Rate
       FROM s96.CurrencyRates
       WHERE (YEAR(Date)=2017) AND (MONTH(Date)=5)
       ) * t.ApprovedLoanAmount)
      -
    SUM((
       SELECT Rate
       FROM s96.CurrencyRates
       WHERE (YEAR(Date)=2017) AND (MONTH(Date)=6)
       ) * t.ApprovedLoanAmount)
    AS currChange
FROM(
        SELECT ApprovedLoanAmount
       FROM dim.Contract con
          JOIN dim.Calendar cal ON con.CreateDateID = cal.DateId
       WHERE (cal.CalendarYear = 2017) AND (cal.MonthOfYear = 5)
      ) t
</code>```

which returns:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Any help would be aprreciated.

答:
I don't know how your exact tables look, so think of this more like a snippet than copy/paste solution:

```<code>SELECT
  SUM(ApprovedLoanAmount) AS ApprovedLoanAmountCZK
, SUM(ApprovedLoanAmountEUR_May) AS ApprovedLoanAmountEUR_May
, SUM(ApprovedLoanAmountEUR_June) AS ApprovedLoanAmountEUR_June
, SUM(ApprovedLoanAmountEUR_May) - SUM(ApprovedLoanAmountEUR_June) AS CurrChange
FROM
(
   SELECT ApprovedLoanAmount
   , ApprovedLoanAmount * (SELECT Rate
                           FROM s96.CurrencyRates rM
                           WHERE rM.Date = cal.Date -- date of contract?
                          AND rM.Currency = 'EUR' -- if you have other currencies rates in same table
   ) AS ApprovedLoanAmountEUR_May
   , ApprovedLoanAmount * (SELECT Rate
                        FROM s96.CurrencyRates rJ
                        WHERE rJ.Date = '20170630'
                        AND rJ.Currency = 'EUR'
   ) AS ApprovedLoanAmountEUR_June
   FROM dim.Contract con
   JOIN dim.Calendar cal ON con.CreateDateID = cal.DateId
   WHERE (cal.CalendarYear = 2017) AND (cal.MonthOfYear = 5)
) t
</code>```

Make sure both Rate subqueries return only one row each

Replace cal.Date and rM.Currency with your exact columns

Replace cal.Date with '20170531' if you want rate on end of May instead on contract date

Body:
I want to make a diffrence of currency rate movements between May and June expressed in total amount of loan people borrowed in CZK (Czech Koruna) with relation to EUR.
e.g.: People have borrowed from my company money in a amount of 27M CZK (corresponding to 1M EUR) in May, which is only 0.89M EUR in June due to the currency rate movements.

I've come with:

    SELECT
    SUM((
       SELECT Rate
       FROM s96.CurrencyRates
       WHERE (YEAR(Date)=2017) AND (MONTH(Date)=5)
       ) * t.ApprovedLoanAmount)
      -
    SUM((
       SELECT Rate
       FROM s96.CurrencyRates
       WHERE (YEAR(Date)=2017) AND (MONTH(Date)=6)
       ) * t.ApprovedLoanAmount)
    AS currChange
FROM(
        SELECT ApprovedLoanAmount
       FROM dim.Contract con
          JOIN dim.Calendar cal ON con.CreateDateID = cal.DateId
       WHERE (cal.CalendarYear = 2017) AND (cal.MonthOfYear = 5)
      ) t

which returns:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Any help would be aprreciated.

Body:
I don't know how your exact tables look, so think of this more like a snippet than copy/paste solution:

SELECT
  SUM(ApprovedLoanAmount) AS ApprovedLoanAmountCZK
, SUM(ApprovedLoanAmountEUR_May) AS ApprovedLoanAmountEUR_May
, SUM(ApprovedLoanAmountEUR_June) AS ApprovedLoanAmountEUR_June
, SUM(ApprovedLoanAmountEUR_May) - SUM(ApprovedLoanAmountEUR_June) AS CurrChange
FROM
(
   SELECT ApprovedLoanAmount
   , ApprovedLoanAmount * (SELECT Rate
                           FROM s96.CurrencyRates rM
                           WHERE rM.Date = cal.Date -- date of contract?
                          AND rM.Currency = 'EUR' -- if you have other currencies rates in same table
   ) AS ApprovedLoanAmountEUR_May
   , ApprovedLoanAmount * (SELECT Rate
                        FROM s96.CurrencyRates rJ
                        WHERE rJ.Date = '20170630'
                        AND rJ.Currency = 'EUR'
   ) AS ApprovedLoanAmountEUR_June
   FROM dim.Contract con
   JOIN dim.Calendar cal ON con.CreateDateID = cal.DateId
   WHERE (cal.CalendarYear = 2017) AND (cal.MonthOfYear = 5)
) t

Make sure both Rate subqueries return only one row each

Replace cal.Date and rM.Currency with your exact columns

Replace cal.Date with '20170531' if you want rate on end of May instead on contract date