问:
How can I allow a private insecure registry to be used inside a minikube node?
I know there are about a thousand answers to various permutations of this question but none of the fifteen or so that I've tried have worked.

I'm running on Mac OS Sierra and using Minikube 0.17.1 as well as kubectl 1.5.3.

We run our own private Docker registry that is insecure as it is not open to the internet. (This is not my choice or in my control so it's not open for discussion). This is my first foray into Kubernetes and actually container orchestration altogether. I also have a very intermediate level of knowledge about Docker in general so I'm drowning in terminology/platform soup here.

When I execute

```<code>kubectl run perf-ui --image=X.X.X.X/performance/perf-ui:master
</code>```

I see

image pull failed for X.X.X.X/performance/perf-ui:master, this may be because there are no credentials on this request.  details: (Error response from daemon: Get https://X.X.X.X/v1/_ping: dial tcp X.X.X.X:443: getsockopt: connection refused)

We have an Ubuntu box that accesses the same registry (not using Kubernetes, just Docker) that works just fine. This is likely due to

DOCKER_OPTS="--insecure-registry X.X.X.X"

being in /etc/default/docker.

I made a similar change using the UI of Docker for Mac. I don't know where this change persisted in a config file. After this change a docker pull worked on my laptop!!! Again, this is just using Docker not Kubernetes. The interesting part is I got the same "Connection refused error" (as it tries to access via HTTPS) on my Mac as I get in the Minikube VM and after the change the pull worked. I feel like I'm on to something there.

After sshing into minikube (the VM created my minikube start) using

```<code>minikube ssh
</code>```

I added the following content to /var/lib/boot2docker/profile

```<code>export EXTRA_ARGS="$EXTRA_ARGS --insecure-registry 10.129.100.3
export DOCKER_OPTS="$DOCKER_OPTS --insecure-registry 10.129.100.3
</code>```

As you can infer, nothing has worked. I know I've tried other things but they too have failed.

I know this isn't the most comprehensive explanation but I've been digging into this for the past 4 hours.

The bottom line is docker pulls work from our Ubuntu box with the config file setup correctly and from my Mac with the setting configured properly.

How can I enable the same setting in my "Linux 2.6" VM that was created by Minikube?

If someone knows the answer I would be forever grateful.

Thank you in advance!

答:
Thank you to Janos for your alternative solution. I'm confident that is the right choice for some use cases.

It turns out that what I needed was a good night sleep and the following command to start Minikube in the first place:

```<code>minikube start --insecure-registry="X.X.X.X"
</code>```

@intelfx says that adding a port won't be necessary. I'm inclined to believe them but if your registry is on a non-standard port just keep it in mind in case things still aren't working.

In the end it was, in fact, a matter of telling Docker to use an insecure registry but it was not clear how to tell this to Docker when I was not controlling it directly.

I know that seems simple but after you've tried a hundred things you're almost hallucinating so you're not in a great state to make rational decisions. I'm sorry for the dumb post but I'm willing to bet this will help at least one person one day, which makes it worth it.

Thanks SO!

Body:
I know there are about a thousand answers to various permutations of this question but none of the fifteen or so that I've tried have worked.

I'm running on Mac OS Sierra and using Minikube 0.17.1 as well as kubectl 1.5.3.

We run our own private Docker registry that is insecure as it is not open to the internet. (This is not my choice or in my control so it's not open for discussion). This is my first foray into Kubernetes and actually container orchestration altogether. I also have a very intermediate level of knowledge about Docker in general so I'm drowning in terminology/platform soup here.

When I execute

kubectl run perf-ui --image=X.X.X.X/performance/perf-ui:master

I see

image pull failed for X.X.X.X/performance/perf-ui:master, this may be because there are no credentials on this request.  details: (Error response from daemon: Get https://X.X.X.X/v1/_ping: dial tcp X.X.X.X:443: getsockopt: connection refused)

We have an Ubuntu box that accesses the same registry (not using Kubernetes, just Docker) that works just fine. This is likely due to

DOCKER_OPTS="--insecure-registry X.X.X.X"

being in /etc/default/docker.

I made a similar change using the UI of Docker for Mac. I don't know where this change persisted in a config file. After this change a docker pull worked on my laptop!!! Again, this is just using Docker not Kubernetes. The interesting part is I got the same "Connection refused error" (as it tries to access via HTTPS) on my Mac as I get in the Minikube VM and after the change the pull worked. I feel like I'm on to something there.

After sshing into minikube (the VM created my minikube start) using

minikube ssh

I added the following content to /var/lib/boot2docker/profile

export EXTRA_ARGS="$EXTRA_ARGS --insecure-registry 10.129.100.3
export DOCKER_OPTS="$DOCKER_OPTS --insecure-registry 10.129.100.3

As you can infer, nothing has worked. I know I've tried other things but they too have failed.

I know this isn't the most comprehensive explanation but I've been digging into this for the past 4 hours.

The bottom line is docker pulls work from our Ubuntu box with the config file setup correctly and from my Mac with the setting configured properly.

How can I enable the same setting in my "Linux 2.6" VM that was created by Minikube?

If someone knows the answer I would be forever grateful.

Thank you in advance!

Body:
Thank you to Janos for your alternative solution. I'm confident that is the right choice for some use cases.

It turns out that what I needed was a good night sleep and the following command to start Minikube in the first place:

minikube start --insecure-registry="X.X.X.X"

@intelfx says that adding a port won't be necessary. I'm inclined to believe them but if your registry is on a non-standard port just keep it in mind in case things still aren't working.

In the end it was, in fact, a matter of telling Docker to use an insecure registry but it was not clear how to tell this to Docker when I was not controlling it directly.

I know that seems simple but after you've tried a hundred things you're almost hallucinating so you're not in a great state to make rational decisions. I'm sorry for the dumb post but I'm willing to bet this will help at least one person one day, which makes it worth it.

Thanks SO!


来源: stackexchange

问:
Is it possible that Hive table as source and Oracle table as target in Informatica developer tool with hive environment?
I want to use HIVE table as a source and Oracle table as target in my Informatica developer tool mapping with hive environment. Mean I want to run my Informatcia developer tool mapping in HIVE mode. Is it possible if yes then please let me know the steps.

Thanks

答:
Yes, it is possible, You just need to change the execution engine.
Refer to Informatica BDM help document for the detailed steps</p>

ContentLicense: CC BY-SA 3.0


问:
Understanding geocoding in Javascript
OK, I have Google maps setup in a jQuery app. (V3).  I can geocode maps all day long.

So, I thought I'd be smart and move the actual geocode function into, well, a function.

Here is the function I am using:

```

    function geocode(address) {
        var self = this;
        geocoder.geocode( { 'address': address }, function(results, status) {
            console.log(status);
            if (status == google.maps.GeocoderStatus.OK) {
                return results[0].geometry.location;
            } else { return null; }
        });
        return "WTF?";
    }
```

The "WTF" is a joke that you will see in a moment.

Now, later on in my code, I try to call the function like so:

```
var start_latlng;
start_latlng = geocode(start_address);

console.log(start_latlng);
```

What I get in the console is:

```
WTF?
OK
```

Notice the "WTF" is BEFORE the "OK" even though I print the "OK" within the function.  (the console.log(status) )

My guess is because the geocoding needs a little time to return and the function continues on before returning the first geocoded value.

Does anyone have any suggestions on how to improve this so that my "start_latlng" contains the expected values?

Thanks for any pointers.

* EDIT **

Here is what I ended up doing.

I call the function like so:

```
        geocode(start_address, function(data) {
            start_latlng = data;
            console.log(start_latlng);
        });
```

And here is the new function (not finished but you get the idea)

```
    function geocode(address, callback) {
        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                callback(results[0].geometry.location);
            }
            else {
                callback("Error");
            }
        });
    }
```

Works like a charm.  :-)

Thanks for the tips and helping me think better.

答: The geocoder appears to be working asynchronously, so the result is not surprising. What I mean is, execution flows past the point of the geocoder invocation, thus the function returns and subsequently the geocoder returns its result - which is why you get the output in that order.</p>

Title: Understanding geocoding in Javascript

Body:
OK, I have Google maps setup in a jQuery app. (V3).  I can geocode maps all day long.

So, I thought I'd be smart and move the actual geocode function into, well, a function.

Here is the function I am using:

    function geocode(address) {
        var self = this;
        geocoder.geocode( { 'address': address }, function(results, status) {
            console.log(status);
            if (status == google.maps.GeocoderStatus.OK) {
                return results[0].geometry.location;
            } else { return null; }
        });
        return "WTF?";
    }

The "WTF" is a joke that you will see in a moment.

Now, later on in my code, I try to call the function like so:

var start_latlng;
start_latlng = geocode(start_address);

console.log(start_latlng);

What I get in the console is:

WTF?
OK

Notice the "WTF" is BEFORE the "OK" even though I print the "OK" within the function.  (the console.log(status) )

My guess is because the geocoding needs a little time to return and the function continues on before returning the first geocoded value.

Does anyone have any suggestions on how to improve this so that my "start_latlng" contains the expected values?

Thanks for any pointers.

* EDIT **

Here is what I ended up doing.

I call the function like so:

        geocode(start_address, function(data) {
            start_latlng = data;
            console.log(start_latlng);
        });

And here is the new function (not finished but you get the idea)

    function geocode(address, callback) {
        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                callback(results[0].geometry.location);
            }
            else {
                callback("Error");
            }
        });
    }

Works like a charm.  :-)

Thanks for the tips and helping me think better.

ContentLicense: CC BY-SA 2.5


问:
Count number of times a value appears (and append it in EVERY row) in R
so I want to count the number of times each value appears in a vector and to create a new vector, of EQUAL length, to bind it with the initial one. So my solution cannot be the table function as it returns only the unique values and the times they appear. I need in each row of the initial vector to append its number of appearences. I have found a solution but I got a big database with ~800k rows and it runs for like 10 min. Does anyone know how to perform this task more efficiently? I include an example.Thanks

```<code>df<-as.data.frame(sample(1:100, 800000, replace = T))
df[2]<-rep(1,nrow(df))
names(df)<-c("Numbers","Count")

df$Count<-pbapply(df,1,function(x) length(which(df$Numbers==df$Numbers[x])))
</code>```

P.S. I have used to pbapply function to keep track of the progress.

答:
This will do the trick:</p>

```<code>df<-data.frame(Numbers=sample(1:100, 800000, replace = T))

Count <- ddply(df, .(Numbers), summarize, Count=length(Numbers)) #Unique values and how many times they appear

Indices<-match(df$Numbers, Count$Numbers) #Use match to add counts to data frame
df$Count <- Count$Count[Indices]
</code>```

Body:
so I want to count the number of times each value appears in a vector and to create a new vector, of EQUAL length, to bind it with the initial one. So my solution cannot be the table function as it returns only the unique values and the times they appear. I need in each row of the initial vector to append its number of appearences. I have found a solution but I got a big database with ~800k rows and it runs for like 10 min. Does anyone know how to perform this task more efficiently? I include an example.Thanks

df<-as.data.frame(sample(1:100, 800000, replace = T))
df[2]<-rep(1,nrow(df))
names(df)<-c("Numbers","Count")

df$Count<-pbapply(df,1,function(x) length(which(df$Numbers==df$Numbers[x])))

P.S. I have used to pbapply function to keep track of the progress.

Body:
This will do the trick:

df<-data.frame(Numbers=sample(1:100, 800000, replace = T))

Count <- ddply(df, .(Numbers), summarize, Count=length(Numbers)) #Unique values and how many times they appear

Indices<-match(df$Numbers, Count$Numbers) #Use match to add counts to data frame
df$Count <- Count$Count[Indices]


问:
Test the behavior of a java web service for multiple concurrent requests
How do I test the behavior of a java restful web service in case of multiple concurrent requests? Is there any 3rd party tool that can be leveraged?

The service accepts POST method. It expects a couple of parameters in it's request body and produces the response in the form of JSON.

The functionality of the service is to perform database read operations using the request body parameters and populate the fetched data in the JSON.

答:
I would recommend one of the following:

SoapUI - superior tool for web service testing. Has limited load testing capabilities. However it does not scale (no clustered mode is available) and has quite poor reporting (all you get is average, min and max response times)

Apache JMeter - multiprotocol load testing tool, supports web services load testing as well. Has better load capabilities and ways to define the load patterns and can represent load test results via HTML Reporting Dashboard. Check out Testing SOAP/REST Web Services Using JMeter article to learn how to conduct a web service load test using JMeter.


问:
Angular directive to update height of multiple elements to match the tallest
I'm fairly new to Angular's directives and am trying to figure out the proper way to use them. I'm using an ng-repeat to populate a list of elements. Once the repeater is loaded I want to look at each element and find which one is the tallest (has the most text in it) and then force all of the elements to that size.

A way of accomplishing this in jQuery would be like so:

```<code>var tallest = 0;
// Loop through each element
$('.element-class').each(function () {
    var thisHeight = $(this).height();
    if (thisHeight > tallest)
        tallest = thisHeight;
});
// Apply height to all elements
$('.element-class').height(tallest);
</code>```

Would someone be able to instruct me as to how i might accomplish this with a directive (or another more fitting Angular way). The repeater looks something like this.

```<code><div class="element-class" ng-repeat="item in items">
    <div class="element-title" ng-bind="item.title"></div>
    <p class="element-text" ng-bind="item.description"></p>
</div>
</code>```

答:
ragamufin's solution works like a charm (thank you!)

But if you plan on filtering or adding new element in the middle of the repeat, you should loose that 'if' in the end of the 'equalizeHeightAdd' directive (otherwise it won't resize itself) and implement a remove function on the controller and remove elements if they are destroyed:

```<code>    .directive('equalizeHeight', equalizeHeight)
    .directive('equalizeHeightAdd', equalizeHeightAdd);

    equalizeHeight.$inject = ['$timeout'];

    /* @ngInject */
    function equalizeHeight() {
        var directive = {
            bindToController: true,
            controller: ControllerName,
            controllerAs: 'vm',
            link: link,
            restrict: 'A',
            scope: {}
        };
        return directive;

        function link(scope, element, attrs) {

        }
    }

    ControllerName.$inject = ['$window', '$timeout'];

    /* @ngInject */
    function ControllerName($window, $timeout) {
        var elements = [];
        this.addElement = addElement;
        this.removeElement = removeElement;
        this.resize = resize;

        activate();

        function activate() {
            angular.element($window).on('resize', function () {
                angular.forEach(elements, function(el){
                    el[0].style.height = null;
                });
                resize();
            });
        }

        function addElement(element){
            elements.push(element);
            console.log(elements.length);
        }

        function removeElement(element){
            elements.splice(elements.indexOf(element),1);
        }

        // resize elements once the last element is found
        function resize(){
            $timeout(function(){
                // find the tallest
                var tallest = 0, height;
                angular.forEach(elements, function(el){
                    height = el[0].offsetHeight;
                    if(height > tallest)
                        tallest = height;
                });
                // resize
                angular.forEach(elements, function(el){
                    el[0].style.height = tallest + 'px';
                });
            }, 0);
        }
    }

    /* @ngInject */
    function equalizeHeightAdd(){
        return {
            restrict: 'A',
            require: '^^equalizeHeight',
            link: function(scope, element, attrs, ctrl_for){
                // add element to list of elements
                ctrl_for.addElement(element);
                ctrl_for.resize();
                element.on('$destroy', function () {
                    ctrl_for.removeElement(element);
                    ctrl_for.resize();
                });
            }
        };
    }
</code>```

Sorry, I can not add comment to his answer, because of the lack of reputations, but I think this is a pretty important addition. Also sorry for the different formating, but this is how I use it in my project, but basically it's the same.

Body:
I'm fairly new to Angular's directives and am trying to figure out the proper way to use them. I'm using an ng-repeat to populate a list of elements. Once the repeater is loaded I want to look at each element and find which one is the tallest (has the most text in it) and then force all of the elements to that size.

A way of accomplishing this in jQuery would be like so:

var tallest = 0;
// Loop through each element
$('.element-class').each(function () {
    var thisHeight = $(this).height();
    if (thisHeight > tallest)
        tallest = thisHeight;
});
// Apply height to all elements
$('.element-class').height(tallest);

Would someone be able to instruct me as to how i might accomplish this with a directive (or another more fitting Angular way). The repeater looks something like this.

Body:
ragamufin's solution works like a charm (thank you!)

But if you plan on filtering or adding new element in the middle of the repeat, you should loose that 'if' in the end of the 'equalizeHeightAdd' directive (otherwise it won't resize itself) and implement a remove function on the controller and remove elements if they are destroyed:

    .directive('equalizeHeight', equalizeHeight)
    .directive('equalizeHeightAdd', equalizeHeightAdd);

    equalizeHeight.$inject = ['$timeout'];

    /* @ngInject */
    function equalizeHeight() {
        var directive = {
            bindToController: true,
            controller: ControllerName,
            controllerAs: 'vm',
            link: link,
            restrict: 'A',
            scope: {}
        };
        return directive;

        function link(scope, element, attrs) {

        }
    }

    ControllerName.$inject = ['$window', '$timeout'];

    /* @ngInject */
    function ControllerName($window, $timeout) {
        var elements = [];
        this.addElement = addElement;
        this.removeElement = removeElement;
        this.resize = resize;

        activate();

        function activate() {
            angular.element($window).on('resize', function () {
                angular.forEach(elements, function(el){
                    el[0].style.height = null;
                });
                resize();
            });
        }

        function addElement(element){
            elements.push(element);
            console.log(elements.length);
        }

        function removeElement(element){
            elements.splice(elements.indexOf(element),1);
        }

        // resize elements once the last element is found
        function resize(){
            $timeout(function(){
                // find the tallest
                var tallest = 0, height;
                angular.forEach(elements, function(el){
                    height = el[0].offsetHeight;
                    if(height > tallest)
                        tallest = height;
                });
                // resize
                angular.forEach(elements, function(el){
                    el[0].style.height = tallest + 'px';
                });
            }, 0);
        }
    }

    /* @ngInject */
    function equalizeHeightAdd(){
        return {
            restrict: 'A',
            require: '^^equalizeHeight',
            link: function(scope, element, attrs, ctrl_for){
                // add element to list of elements
                ctrl_for.addElement(element);
                ctrl_for.resize();
                element.on('$destroy', function () {
                    ctrl_for.removeElement(element);
                    ctrl_for.resize();
                });
            }
        };
    }

Sorry, I can not add comment to his answer, because of the lack of reputations, but I think this is a pretty important addition. Also sorry for the different formating, but this is how I use it in my project, but basically it's the same.


问:
Implementing a hierarchical tree editor with mxGraph
I would like to implement an editor for dialogue trees with mxGraph.

I started out with the workfloweditor example [1] and try to customize the code to my needs. Drawing the graph using the subprocess template as nodes and directed connectors works perfectly. However, the graph hierarchy seems to be missing: The tooltip always shows "Children: 0", no matter how many nodes I connect. Same happens in the original sample code.

How can I explicitly configure the graph to follow a hierarchical parent-children layout?

[1] https://jgraph.github.io/mxgraph/javascript/examples/editors/workfloweditor.html

答:
The children are not what I think you think.

What is a children? These are cells with current cell as a parent. What is a parent ? Try that : Add a box, right click on it and click "enter group". You are now inside in sub-process if you like. Place a few boxes there, then right click on the canvas "exit group". Now you have a parent cell with children cells.

What you are trying to do is to read the connections between your boxes. Have a look at how to traverse the graph or you can implement manually too, it's fairly straightforward.


问:
PHP unexpected end of file happens in online testing environment, but doesn't happen in development environment
After I pulled the last code updates to an AWS instance where a test environment is running, a page displayed HTTP Error 500. I'm using CodeIgniter and the AWS instance was set to run as "production" (SetEnv CI_ENV production on .htaccess), so I changed that to "development" to display PHP error messagens. That's when I get the following mesage.

An uncaught Exception was encountered

Type: ParseError

Message: syntax error, unexpected end of file

Filename: /var/www/html/flip/application/views/flip_list.php

Line Number: 58

Backtrace:

File: /var/www/html/flip/application/controllers/Flip.php
  Line: 131
  Function: view

File: /var/www/html/flip/index.php
  Line: 315
  Function: require_once

On my localhost environment it does not happen, the page is displayed without errors or warnings.

Localhost is running PHP 7.0.15-0ubuntu0.16.04.4. And the AWS instance is running PHP 7.0.14 on CentOS. CodeIgniter version is 3.1.3.

I checked flip_list.php and Flip.php, but I didn't find where the problem is.

The controller file (Flip.php) is 350+ lines long, so I'm posting it on a pastebin: https://pastebin.com/agyMuf1T

Below the code of the view (flip_list.php):

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<?php
$first = true;
$second = false;
foreach ($editions->result() as $edition) {
    $edition_hash = $this->flip->encrypt_decrypt_edition_id($edition->edition_id, 'encrypt');

    $date = date_create($edition->edition_date);
    $date = date_format($date, 'd\/m\/Y');

    if( $first ) {
        $first = false;
        $second = true;
    ?>
    <div class="latest">
        <div class="item">
            <a href="<?php echo base_url('flip/'.$slug.'/view/'.$edition_hash); ?>" class="view-edition">
                <img src="<?php echo $edition->edition_cover; ?>" class="edition-cover">
                <span>Edição <?php echo $date; ?></span>
                <span>Número <?php echo $edition->edition_number; ?></span>
            </a>
        </div>
    </div>
    <?php
    }
    else {
    if( $second ) {
        $second = false;
    ?>
    <div class="editions">
    <div class="d-flex flex-row align-content-stretch flex-wrap">
    <?
    }
    ?>
        <div class="item">
            <a href="<?php echo base_url('flip/'.$slug.'/view/'.$edition_hash); ?>" class="view-edition">
                <img src="<?php echo $edition->edition_cover; ?>" class="edition-cover">
                <span><?php echo $date; ?></span>
            </a>
        </div>
    <?php
    }
} // foreach
?>
    </div><!-- .d-flex -->
    </div><!-- .editions -->
</code>```

I'd like some help debbuging this. Thanks!

答:
Unexpected end of file in server may happens as normally live server are on linux. And you may be testing on windows server so while transferring file it may be modified as windows and linux have different mechanism to denote new line. So, set as following(in Filezilla FTP Client):
Go to Transfer > Transfer type > select Binary and again upload all of your view files.

Body:
After I pulled the last code updates to an AWS instance where a test environment is running, a page displayed HTTP Error 500. I'm using CodeIgniter and the AWS instance was set to run as "production" (SetEnv CI_ENV production on .htaccess), so I changed that to "development" to display PHP error messagens. That's when I get the following mesage.

An uncaught Exception was encountered

Type: ParseError

Message: syntax error, unexpected end of file

Filename: /var/www/html/flip/application/views/flip_list.php

Line Number: 58

Backtrace:

File: /var/www/html/flip/application/controllers/Flip.php
  Line: 131
  Function: view

File: /var/www/html/flip/index.php
  Line: 315
  Function: require_once

On my localhost environment it does not happen, the page is displayed without errors or warnings.

Localhost is running PHP 7.0.15-0ubuntu0.16.04.4. And the AWS instance is running PHP 7.0.14 on CentOS. CodeIgniter version is 3.1.3.

I checked flip_list.php and Flip.php, but I didn't find where the problem is.

The controller file (Flip.php) is 350+ lines long, so I'm posting it on a pastebin: https://pastebin.com/agyMuf1T

Below the code of the view (flip_list.php):

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<?php
$first = true;
$second = false;
foreach ($editions->result() as $edition) {
    $edition_hash = $this->flip->encrypt_decrypt_edition_id($edition->edition_id, 'encrypt');

    $date = date_create($edition->edition_date);
    $date = date_format($date, 'd\/m\/Y');

    if( $first ) {
        $first = false;
        $second = true;
    ?>

            <a href="<?php echo base_url('flip/'.$slug.'/view/'.$edition_hash); ?>" class="view-edition">
                <img src="<?php echo $edition->edition_cover; ?>" class="edition-cover">
                Edição <?php echo $date; ?>
                Número <?php echo $edition->edition_number; ?>

    <?php
    }
    else {
    if( $second ) {
        $second = false;
    ?>

    <?
    }
    ?>

            <a href="<?php echo base_url('flip/'.$slug.'/view/'.$edition_hash); ?>" class="view-edition">
                <img src="<?php echo $edition->edition_cover; ?>" class="edition-cover">
                <?php echo $date; ?>

    <?php
    }
} // foreach
?>

I'd like some help debbuging this. Thanks!


问:
Inno Setup: Keep existing 32-bit installation path for upgrades, use 64-bit path for new installations
Our application now supports 64-bit natively and therefore should be installed below the C:\Program Files directory by default. For that reason we set these two directives:

```<code>ArchitecturesInstallIn64BitMode=x64
DefaultDirName={pf}\{#ProductName}
</code>```

This works without any issues so far!

The problem is that we do have a lot existent installations of our product when it was still 32-bit only and therefore correctly installed below C:\Program Files (x86).

Normally Inno Setup detects an existent installation and uses the same installation path, if it finds one. But this seems not to work when changed from 32-bit to 64-bit mode - probably because now a different uninstall registry key is used.

Is there still a way to tell Inno Setup to use the existent 32-bit installation path, if the application was installed already (to perform an update) and only use the 64-bit one if it is a new installation?

答:
I do not think you can have Inno Setup do this for you automatically.

But you can copy the 32-bit registry key to 64-bit when initializing the installer, to allow Inno Setup find it. Of course, you have to rollback the copy, if the installation is cancelled.

#define AppId "My Program"

[Setup]
AppId={#AppId}
DefaultDirName={pf}\My Program
ArchitecturesInstallIn64BitMode=x64
```
<pre class="lang-pascal prettyprint-override"><code>[Code]

const
  UninstallKey =
    'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{#AppId}_is1';

var
  Rollback64Key: Boolean;
  RootKey32: Integer;
  RootKey64: Integer;

procedure Copy32BitUninstallKeyTo64bit;
var
  I: Integer;
  ValueNames: TArrayOfString;
  ValueName: string;
  ValueStr: string;
  ValueDWord: Cardinal;
  Success: Boolean;
begin
  if RegKeyExists(HKCU64, UninstallKey) or
     RegKeyExists(HKLM64, UninstallKey) then
  begin
    Log('64-bit uninstall key found, leaving as it is');
  end
    else
  begin
    if RegKeyExists(HKCU32, UninstallKey) then
    begin
      Log('32-bit HKCU uninstall key found, will copy it to the 64-bit key');
      RootKey32 := HKCU32;
      RootKey64 := HKCU64;
    end
      else
    if RegKeyExists(HKLM32, UninstallKey) then
    begin
      Log('32-bit HKLM uninstall key found, will copy it to the 64-bit key');
      RootKey32 := HKLM32;
      RootKey64 := HKLM64;
    end
      else
    begin
      Log('No 32-bit uninstall key found');
      RootKey32 := 0;
      RootKey64 := 0;
    end;

    if RootKey32 <> 0 then
    begin
      if not RegGetValueNames(RootKey32, UninstallKey, ValueNames) then
      begin
        Log('Cannot list 32-bit uninstall key values');
      end
        else
      begin
        I := 0;
        Success := True;
        while (I < GetArrayLength(ValueNames)) and Success do
        begin
          ValueName := ValueNames[I];
          if RegQueryStringValue(
               RootKey32, UninstallKey, ValueName, ValueStr) then
          begin
            if not RegWriteStringValue(
                     RootKey64, UninstallKey, ValueName, ValueStr) then
            begin
              Log(Format('Error copying "%s" string value', [ValueName]));
              Success := False;
            end
              else
            begin
              Log(Format('Copied "%s" string value', [ValueName]));
            end;
          end
            else
          if RegQueryDWordValue(
               RootKey32, UninstallKey, ValueName, ValueDWord) then
          begin
            if not RegWriteDWordValue(
                     RootKey64, UninstallKey, ValueName, ValueDWord) then
            begin
              Log(Format('Error copying "%s" dword value', [ValueName]));
              Success := False;
            end
              else
            begin
              Log(Format('Copied "%s" dword value', [ValueName]));
            end;
          end
            else
          begin
            // All uninstall values written by Inno Setup are
            // either string or dword
            Log(Format('Value "%s" is neither string nor dword', [ValueName]));
            Success := False;
          end;

          I := I + 1;
        end;

        if Success then
        begin
          Log('Copied 32-bit uninstall key to 64-bit');
          Rollback64Key := True;
        end
          else
        begin
          if not RegDeleteKeyIncludingSubkeys(RootKey64, UninstallKey) then
          begin
            Log('Failed to copy 32-bit uninstall key to 64-bit, ' +
                'and also failed to rollback the changes');
          end
            else
          begin
            Log('Failed to copy 32-bit uninstall key to 64-bit, ' +
                'rolled back the changes');
          end;
        end;
      end;
    end;
  end;
end;

function InitializeSetup(): Boolean;
begin
  if IsWin64 then
  begin
    Copy32BitUninstallKeyTo64bit;
  end;

  Result := True;
end;

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep = ssPostInstall then
  begin
    if Rollback64Key then
    begin
      Log('Installation finished, removing obsolete 32-bit key');
      Rollback64Key := False;

      if not RegDeleteKeyIncludingSubkeys(RootKey32, UninstallKey) then
      begin
        Log('Failed to remove obsolete 32-bit uninstall key');
      end
        else
      begin
        Log('Removed obsolete 32-bit uninstall key');
      end;
    end;
  end;
end;

procedure DeinitializeSetup();
begin
  if Rollback64Key then
  begin
    Log('Installation cancelled, rolling back cloned 64-bit uninstall key');

    if not RegDeleteKeyIncludingSubkeys(RootKey64, UninstallKey) then
    begin
      Log('Failed to roll back cloned 64-bit uninstall key');
    end
      else
    begin
      Log('Rolled back cloned 64-bit uninstall key');
    end;
  end;
end;
</code>```

(Needs Unicode version of Inno Setup – The only version as of Inno Setup 6)

Body:
Our application now supports 64-bit natively and therefore should be installed below the C:\Program Files directory by default. For that reason we set these two directives:

ArchitecturesInstallIn64BitMode=x64
DefaultDirName={pf}\{#ProductName}

This works without any issues so far!

The problem is that we do have a lot existent installations of our product when it was still 32-bit only and therefore correctly installed below C:\Program Files (x86).

Normally Inno Setup detects an existent installation and uses the same installation path, if it finds one. But this seems not to work when changed from 32-bit to 64-bit mode - probably because now a different uninstall registry key is used.

Is there still a way to tell Inno Setup to use the existent 32-bit installation path, if the application was installed already (to perform an update) and only use the 64-bit one if it is a new installation?

Body:
I do not think you can have Inno Setup do this for you automatically.

But you can copy the 32-bit registry key to 64-bit when initializing the installer, to allow Inno Setup find it. Of course, you have to rollback the copy, if the installation is cancelled.

#define AppId "My Program"

[Setup]
AppId={#AppId}
DefaultDirName={pf}\My Program
ArchitecturesInstallIn64BitMode=x64

[Code]

const
  UninstallKey =
    'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{#AppId}_is1';

var
  Rollback64Key: Boolean;
  RootKey32: Integer;
  RootKey64: Integer;

procedure Copy32BitUninstallKeyTo64bit;
var
  I: Integer;
  ValueNames: TArrayOfString;
  ValueName: string;
  ValueStr: string;
  ValueDWord: Cardinal;
  Success: Boolean;
begin
  if RegKeyExists(HKCU64, UninstallKey) or
     RegKeyExists(HKLM64, UninstallKey) then
  begin
    Log('64-bit uninstall key found, leaving as it is');
  end
    else
  begin
    if RegKeyExists(HKCU32, UninstallKey) then
    begin
      Log('32-bit HKCU uninstall key found, will copy it to the 64-bit key');
      RootKey32 := HKCU32;
      RootKey64 := HKCU64;
    end
      else
    if RegKeyExists(HKLM32, UninstallKey) then
    begin
      Log('32-bit HKLM uninstall key found, will copy it to the 64-bit key');
      RootKey32 := HKLM32;
      RootKey64 := HKLM64;
    end
      else
    begin
      Log('No 32-bit uninstall key found');
      RootKey32 := 0;
      RootKey64 := 0;
    end;

    if RootKey32 <> 0 then
    begin
      if not RegGetValueNames(RootKey32, UninstallKey, ValueNames) then
      begin
        Log('Cannot list 32-bit uninstall key values');
      end
        else
      begin
        I := 0;
        Success := True;
        while (I < GetArrayLength(ValueNames)) and Success do
        begin
          ValueName := ValueNames[I];
          if RegQueryStringValue(
               RootKey32, UninstallKey, ValueName, ValueStr) then
          begin
            if not RegWriteStringValue(
                     RootKey64, UninstallKey, ValueName, ValueStr) then
            begin
              Log(Format('Error copying "%s" string value', [ValueName]));
              Success := False;
            end
              else
            begin
              Log(Format('Copied "%s" string value', [ValueName]));
            end;
          end
            else
          if RegQueryDWordValue(
               RootKey32, UninstallKey, ValueName, ValueDWord) then
          begin
            if not RegWriteDWordValue(
                     RootKey64, UninstallKey, ValueName, ValueDWord) then
            begin
              Log(Format('Error copying "%s" dword value', [ValueName]));
              Success := False;
            end
              else
            begin
              Log(Format('Copied "%s" dword value', [ValueName]));
            end;
          end
            else
          begin
            // All uninstall values written by Inno Setup are
            // either string or dword
            Log(Format('Value "%s" is neither string nor dword', [ValueName]));
            Success := False;
          end;

          I := I + 1;
        end;

        if Success then
        begin
          Log('Copied 32-bit uninstall key to 64-bit');
          Rollback64Key := True;
        end
          else
        begin
          if not RegDeleteKeyIncludingSubkeys(RootKey64, UninstallKey) then
          begin
            Log('Failed to copy 32-bit uninstall key to 64-bit, ' +
                'and also failed to rollback the changes');
          end
            else
          begin
            Log('Failed to copy 32-bit uninstall key to 64-bit, ' +
                'rolled back the changes');
          end;
        end;
      end;
    end;
  end;
end;

function InitializeSetup(): Boolean;
begin
  if IsWin64 then
  begin
    Copy32BitUninstallKeyTo64bit;
  end;

  Result := True;
end;

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep = ssPostInstall then
  begin
    if Rollback64Key then
    begin
      Log('Installation finished, removing obsolete 32-bit key');
      Rollback64Key := False;

      if not RegDeleteKeyIncludingSubkeys(RootKey32, UninstallKey) then
      begin
        Log('Failed to remove obsolete 32-bit uninstall key');
      end
        else
      begin
        Log('Removed obsolete 32-bit uninstall key');
      end;
    end;
  end;
end;

procedure DeinitializeSetup();
begin
  if Rollback64Key then
  begin
    Log('Installation cancelled, rolling back cloned 64-bit uninstall key');

    if not RegDeleteKeyIncludingSubkeys(RootKey64, UninstallKey) then
    begin
      Log('Failed to roll back cloned 64-bit uninstall key');
    end
      else
    begin
      Log('Rolled back cloned 64-bit uninstall key');
    end;
  end;
end;

(Needs Unicode version of Inno Setup – The only version as of Inno Setup 6)

ContentLicense: CC BY-SA 4.0


问:
SSIS - need help on processing data
I am new to SSIS.  I have been given a task to load data from flat files to Oracle Target table.  Some how i was able to do this.  But i have another requirement to check the flat file data for existence before inserting to the target.

Can you please throw some idea(s) which transformation to use?

Using SSIS 2008 (using with Attunity Oracle drivers)
Oracle 11g target

thanks in advance

答:
If you want to check the existence before inserting, you need to use a LookUp transformation. It will check a value inside the table and you have this 2 options:

If it doesn´t, you can redirect not matching rows, and send the row to the destination table.

IF IT DOES EXIST, you can either ignore it or save that row on a flat file.

LookUp Transformation also gives you the option to use the Cache Memory:

Full Cache: the database is queried and 'memorizes' the data BEFORE
doing any transformation or insert into it.

Partial Cache: uses a partial cache, and if no match is found,
queries the database.

No Cache: It does not maintain a Lookup cache, so it queries the
database for every row proccessed.

You can find more detailed information about LookUp Transformation here

Hope it was what you were looking for

Title: SSIS - need help on processing data


问:
Get a reference to currently active dataSource in Spring Boot
I want to implement db data init via DataSourceInitializer.

I have these as methods just below my Spring Boot main method, but it seems that it doesn't get executed at all (I tried with intentional removal of characters just to trigger an error which would confirm the execution. Nothing happened.):

```<code>@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource getDataSource() {

    // i was hoping this was going to pull my current datasource, as
    // defined in application.properties
    return DataSourceBuilder
            .create()
            .build();
}

@Bean
public DataSourceInitializer dataSourceInitializer() {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));

    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();

    // the call to the above method
    dataSourceInitializer.setDataSource(getDataSource());

    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

    return dataSourceInitializer;
}
</code>```

UPDATE: This question was aimed at getting a reference to the dataSource in use. This question explains how to init the data in a very simple way:
DataSourceInitializer is not working on Spring boot 1.2

答:
If you have a datasource already created it will be in the spring container, so:

```<code>@Autowired
DataSource dataSource;
</code>```

Should do it.

Body:
I want to implement db data init via DataSourceInitializer.

I have these as methods just below my Spring Boot main method, but it seems that it doesn't get executed at all (I tried with intentional removal of characters just to trigger an error which would confirm the execution. Nothing happened.):

@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource getDataSource() {

    // i was hoping this was going to pull my current datasource, as
    // defined in application.properties
    return DataSourceBuilder
            .create()
            .build();
}

@Bean
public DataSourceInitializer dataSourceInitializer() {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));

    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();

    // the call to the above method
    dataSourceInitializer.setDataSource(getDataSource());

    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

    return dataSourceInitializer;
}

UPDATE: This question was aimed at getting a reference to the dataSource in use. This question explains how to init the data in a very simple way:
DataSourceInitializer is not working on Spring boot 1.2

Body:
If you have a datasource already created it will be in the spring container, so:

@Autowired
DataSource dataSource;

Should do it.


问:
Use index of summation as the order of derivation
Given some function f, I want to compute the following sum using sympy:

In general I want to use the index of summation as the order of differentiation of the function but I could not find out how to do it with sympy.

答:
```<code>import sympy as sp

x = sp.symbols('x')
f = sp.Function('f')

n = 2
sum([f(x).diff(x,i) for i in range(n+1)])
</code>```

f(x) + Derivative(f(x), x) + Derivative(f(x), x, x)

Body:
import sympy as sp

x = sp.symbols('x')
f = sp.Function('f')

n = 2
sum([f(x).diff(x,i) for i in range(n+1)])

f(x) + Derivative(f(x), x) + Derivative(f(x), x, x)


问:
How to test SOAP Services?
How do you guys Test your SOAP Services? Do you use Tools like soapUI or do you write Unit Tests?
Just wanted to hear some opinions, what you prefer, what the advantages or disadvantages of both approaches are? And if someone writes Unit Tests, can you give me an example how to write those???

Edit: I developed a lot of REST services, which I usually tested using JUnit and a REST Client Framework. So when the REST Service was deployed, I was able to invoke those services with as a JUnit Test using a http connection. Is there something similiar in SOAP too? Does anyone have an example code for a SOAP Client?

答: I've written a small library which does most of the heavy lifting of unit-testing SOAP services. Basically you'll get mockito mocks which are easy to work with.</p>

Title: How to test SOAP Services?


问:
How to get a specific item inside the key using android
How to only retrieve email addresses inside the key, not all the items. I have an items Name and Email, but I only want to retrieve EMAIL.

example:

```<code>Email: HOTMAIL
Email: GMAIL
</code>```

答:
Assuming that the user emails are unique, you can query the users records by its email value as follows:</p>

```<code>final String email = "hani.mehdi@email.com";

ValueEventListener onFindListener = new ValueEventListener() {

    @Override
    public void onCancelled(DatabaseError error) {
        Log.e(TAG, error.getMessage());
    }

    @Override
    public void onDataChange(DataSnapshot snapshot) {
        Map<String, User> result = snapshot.getValue(Map.class);
        if (result.contains(email) {
            User user = result.get(email);
            Log.i(TAG, user.toString());
        } else {
            Log.d(TAG, "Not found: " + email);
        }
    }

};

DatabaseReference userReference = database.getReference("users")
    .orderByChild("email")
    .equalTo(email)
    .addListenerForSingleValueEvent(onFindListener);
</code>```

Body:
How to only retrieve email addresses inside the key, not all the items. I have an items Name and Email, but I only want to retrieve EMAIL.

example:

Email: HOTMAIL
Email: GMAIL

Body:
Assuming that the user emails are unique, you can query the users records by its email value as follows:

final String email = "hani.mehdi@email.com";

ValueEventListener onFindListener = new ValueEventListener() {

    @Override
    public void onCancelled(DatabaseError error) {
        Log.e(TAG, error.getMessage());
    }

    @Override
    public void onDataChange(DataSnapshot snapshot) {
        Map<String, User> result = snapshot.getValue(Map.class);
        if (result.contains(email) {
            User user = result.get(email);
            Log.i(TAG, user.toString());
        } else {
            Log.d(TAG, "Not found: " + email);
        }
    }

};

DatabaseReference userReference = database.getReference("users")
    .orderByChild("email")
    .equalTo(email)
    .addListenerForSingleValueEvent(onFindListener);


问:
How to build .ipa for React Native?
I come to React Native development without previous experience in iOS development. I want to build release. .ipa file - ideally from the command line but the official documentation Running On Device is very brief.

I was able to deploy applications on my iPhone manually via XCode but still, I can't find any "release IPA" file. I have updated my code with #ifdef DEBUG directives to make it more generic.

Is there a way to build an application in release mode only via the command-line? If no, what is "the official" way to generate an RN application?

I am currently using RN 0.20.

答:
You have to set Scheme to Release.

From docs you have two ways.

To do this, go to Product → Scheme → Edit Scheme (cmd + <), make sure you're in the Run tab from the side, and set the Build Configuration dropdown to Release.

or

You can also use the React Native CLI to perform this operation using the option --configuration with the value Release (e.g. react-native run-ios --configuration Release).

Then you can generate your archive as usual.

https://facebook.github.io/react-native/docs/running-on-device.html#building-your-app-for-production

Title: How to build .ipa for React Native?


问:
hibernate's objects eating up jboss's jvm heap
am seeing consistent Out of Memory Exceptions due to Hibernate objects consuming over 50% of the heap. (over 500M) Am using EntityManager for persistence

PersitanceBag and Collection Entry are some of them and there are some HashMaps as well contributed by Hibernate.

Please advise if there is any procedure to get rid of them after all the persistance.

Thanks in advance, cheers,

raj

EDIT:

will using em.clear() help or have any side effects?

EDIT 2:

em.clear() helped and dint have any 'side-effects'... there was a huge chunk of memory returned back to the heap after this call

答:
the code is running in production environment for quite some time and em.clear is helping out without any side-effects...

thanks,

rajan


问:
c++ failed to specialize function template 'iterator_traits'
im trying to compile a school assignment but im getting an error, and since there is no qualified teacher available at uni at this hour, i've come here for help.

im getting a error stating: "Error  C2893   Failed to specialize function template 'iterator_traits<_Iter>::difference_type std::distance(_InIt,_InIt)'" line 22

i have no clue as to why this error occurs.

code:

```<code>#pragma once
// ttt.h

#ifndef TTT_H
#define TTT_H

#include <tuple>
#include <array>
#include <vector>
#include <ctime>
#include <random>
#include <iterator>
#include <iostream>

enum class Player { X, O, None };
using Move = int;
using State = std::array<Player, 9>;

// used to get a random element from a container
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
    std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
    std::advance(start, dis(g));
    return start;
}

template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
    static std::random_device rd;
    static std::mt19937 gen(rd());
    return select_randomly(start, end, gen);
}

std::ostream &operator<<(std::ostream &os, const State &state);
std::ostream &operator<<(std::ostream &os, const Player &player);

Player getCurrentPlayer(const State &state);
State doMove(const State &state, const Move &m);
Player getWinner(const State &state);
std::vector<Move> getMoves(const State &state);

#endif // TTT_H
</code>```

function call":

```<code>State mcTrial(const State &board)
{
    State currentBoard = board;
    std::vector<Move> possibleMoves = getMoves(currentBoard);
    while (possibleMoves.size() > 0) {
        int move = select_randomly(0, (int)possibleMoves.size() -1);
        Move m = possibleMoves[move];
        currentBoard = doMove(currentBoard, m);
        possibleMoves = getMoves(currentBoard);
    }
return currentBoard;
}
</code>```

答: You should pass iterators to select_randomly, not indexes. Here is the proper function call: std::vector<Move>::iterator it = select_randomly(possibleMoves.begin(), possibleMoves.end()); To learn more about iterators visit http://www.cprogramming.com/tutorial/stl/iterators.html

Body:
im trying to compile a school assignment but im getting an error, and since there is no qualified teacher available at uni at this hour, i've come here for help.

im getting a error stating: "Error  C2893   Failed to specialize function template 'iterator_traits<_Iter>::difference_type std::distance(_InIt,_InIt)'" line 22

i have no clue as to why this error occurs.

code:

#pragma once
// ttt.h

#ifndef TTT_H
#define TTT_H

#include <tuple>
#include <array>
#include <vector>
#include <ctime>
#include <random>
#include <iterator>
#include <iostream>

enum class Player { X, O, None };
using Move = int;
using State = std::array<Player, 9>;

// used to get a random element from a container
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
    std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
    std::advance(start, dis(g));
    return start;
}

template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
    static std::random_device rd;
    static std::mt19937 gen(rd());
    return select_randomly(start, end, gen);
}

std::ostream &operator<<(std::ostream &os, const State &state);
std::ostream &operator<<(std::ostream &os, const Player &player);

Player getCurrentPlayer(const State &state);
State doMove(const State &state, const Move &m);
Player getWinner(const State &state);
std::vector<Move> getMoves(const State &state);

#endif // TTT_H

function call":

State mcTrial(const State &board)
{
    State currentBoard = board;
    std::vector<Move> possibleMoves = getMoves(currentBoard);
    while (possibleMoves.size() > 0) {
        int move = select_randomly(0, (int)possibleMoves.size() -1);
        Move m = possibleMoves[move];
        currentBoard = doMove(currentBoard, m);
        possibleMoves = getMoves(currentBoard);
    }
return currentBoard;
}


问:
Spark dataset reduce with null values?
I'm creating data frame with this code:

```<code>  val data = List(
    List(444.1235D),
    List(67.5335D),
    List(69.5335D),
    List(677.5335D),
    List(47.5335D),
    List(null)
  )

  val rdd = sparkContext.parallelize(data).map(Row.fromSeq(_))
  val schema = StructType(Array(
    StructField("value", DataTypes.DoubleType, true)
  ))

  val df = sqlContext.createDataFrame(rdd, schema)
</code>```

Then I apply my udf to it:

```<code>val multip: Dataset[Double] = df.select(doubleUdf(df("value"))).as[Double]
</code>```

and then I'm trying to use reduce on this dataset:

```<code>val multipl = multip.reduce(_ * _)
</code>```

And here I got 0.0 as a result.
Also I tried to filter nulls out

```<code>val multipl = multip.filter(_ != null).reduce(_ * _)
</code>```

with the same result.
If I remove null value from data everything works as it should. How can I make reduce work with null values?

My udf is defined like this:

```<code>val doubleUdf: UserDefinedFunction = udf((v: Any) => Try(v.toString.toDouble).toOption)
</code>```

答:
I'll answer with a strong assumption that your doubleUdf function converts values to doubles, and rather than using an Option wrapper for nulls you are turning nulls into 0.0. So, if you want to keep the logic to drop nulls, then filter BEFORE anything else:</p>

```<code>df.na.drop.select(doubleUdf(df("value"))).as[Double]
</code>```

Title: Spark dataset reduce with null values?

Body:
I'm creating data frame with this code:

  val data = List(
    List(444.1235D),
    List(67.5335D),
    List(69.5335D),
    List(677.5335D),
    List(47.5335D),
    List(null)
  )

  val rdd = sparkContext.parallelize(data).map(Row.fromSeq(_))
  val schema = StructType(Array(
    StructField("value", DataTypes.DoubleType, true)
  ))

  val df = sqlContext.createDataFrame(rdd, schema)

Then I apply my udf to it:

val multip: Dataset[Double] = df.select(doubleUdf(df("value"))).as[Double]

and then I'm trying to use reduce on this dataset:

val multipl = multip.reduce(_ * _)

And here I got 0.0 as a result.
Also I tried to filter nulls out

val multipl = multip.filter(_ != null).reduce(_ * _)

with the same result.
If I remove null value from data everything works as it should. How can I make reduce work with null values?

My udf is defined like this:

val doubleUdf: UserDefinedFunction = udf((v: Any) => Try(v.toString.toDouble).toOption)

Body:
I'll answer with a strong assumption that your doubleUdf function converts values to doubles, and rather than using an Option wrapper for nulls you are turning nulls into 0.0. So, if you want to keep the logic to drop nulls, then filter BEFORE anything else:

df.na.drop.select(doubleUdf(df("value"))).as[Double]


问:
Is there any way to figure out where memory block of my software starts and what size does he have?
Hell'o
I use win10. Have to write a software to dynamically managed arrays. I have some idea to do this so. I must know (if it's possible) where mem block of my software starts (void pointer) and how big is it (I presume it fits dynamically).</p>

答:
GetModuleInformation() from the Windows API will give you what you are asking for.  This will give you back a MODULEINFO structure that contains the base address and size of your program in memory.

But you don't need this kind of info just to manage dynamic arrays, so either there is more to your question than you've asked here, or you are likely asking the wrong question...


问:
How to get lat and long coordinates from address string
I have a MKMapView that has a UISearchBar on the top, and I want the user to be able to type a address, and to find that address and drop a pin on it. What I don't know is how to turn the address string into longitude and latitude, so I can make a CLLocation object. Does anyone know how I can do this?

答:
```<code>func geoCodeUsingAddress(address: NSString) -> CLLocationCoordinate2D {
    var latitude: Double = 0
    var longitude: Double = 0
    let addressstr : NSString = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=\(address)" as NSString
    let urlStr  = addressstr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    let searchURL: NSURL = NSURL(string: urlStr! as String)!
    do {
        let newdata = try Data(contentsOf: searchURL as URL)
        if let responseDictionary = try JSONSerialization.jsonObject(with: newdata, options: []) as? NSDictionary {
            print(responseDictionary)
            let array = responseDictionary.object(forKey: "results") as! NSArray
            let dic = array[0] as! NSDictionary
            let locationDic = (dic.object(forKey: "geometry") as! NSDictionary).object(forKey: "location") as! NSDictionary
            latitude = locationDic.object(forKey: "lat") as! Double
            longitude = locationDic.object(forKey: "lng") as! Double
        } catch {
        }
    }
    var center = CLLocationCoordinate2D()
    center.latitude = latitude
    center.longitude = longitude
    return center
}
</code>```


问:
searching huge text file
I have a text file consisting of ~40 million of lines in the form of a key/value, I want to retrieve the values given the key within seconds (2-3) max, I don't have enough memory to store all of them in JVM memory as a hashmap, can I use system storage + some indexing to achieve that ?
i've been reading about lucene, but not sure if it's what am looking for.</p>

答:
Lucene is for free text search. The quickest solution if you don't have to use the text file would be to use a database. 40 million records is a lot, but even so finding a single record using a unique index (on the key) should be much faster than 2-3 seconds. You can use an embedded database like HSQLDB, just make sure that you configure it to use disk storage!

If you need to keep the text file, create a TreeMap from key to offset into the file if you can afford to store that in memory. Sounds messy though.

Title: searching huge text file


问:
How Can I ALTER COLUMN to NOT NULL and ADD PRIMARY KEY in the same SQL
I have a column my_id which is already set as varchar(50) NULL. Now I want to alter it to NOT NULL and add it as primary key for that table. Since there is no other primary keys yet.
I have written like below.

```<code>ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);
</code>```

But I get an error:

Cannot define PRIMARY KEY constraint on nullable column in table 'my_details'. Could not create constraint. See previous errors.

How to write a single query for this?

答:
if this is an existing table with nulls in the my_id column then you have to update the column to remove the nulls first

```<code>CREATE TABLE my_details ( my_id varchar(50) NULL )
GO

INSERT INTO dbo.my_details ( my_id ) VALUES (NULL  )
GO

ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;
GO
</code>```

Gives you this error

Msg 515, Level 16, State 2, Line 9 Cannot insert the value NULL into
  column 'my_id', table 'xStuff.dbo.my_details'; column does not allow
  nulls. UPDATE fails.

trying to add a primary key gives you this

```<code>ALTER TABLE my_details
ADD PRIMARY KEY (my_id);
GO
</code>```

Msg 8111, Level 16, State 1, Line 16 Cannot define PRIMARY KEY
  constraint on nullable column in table 'my_details'. Msg 1750, Level
  16, State 0, Line 16 Could not create constraint. See previous errors.

However

place an update in between and this change works

```<code>CREATE TABLE my_details ( my_id varchar(50) NULL );
GO

INSERT INTO dbo.my_details ( my_id ) VALUES (NULL  );
GO

UPDATE dbo.my_details SET my_id = '' WHERE my_id IS NULL;
GO

ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;
GO

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);
GO
</code>```

Body:
I have a column my_id which is already set as varchar(50) NULL. Now I want to alter it to NOT NULL and add it as primary key for that table. Since there is no other primary keys yet.
I have written like below.

ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);

But I get an error:

Cannot define PRIMARY KEY constraint on nullable column in table 'my_details'. Could not create constraint. See previous errors.

How to write a single query for this?

Body:
if this is an existing table with nulls in the my_id column then you have to update the column to remove the nulls first

CREATE TABLE my_details ( my_id varchar(50) NULL )
GO

INSERT INTO dbo.my_details ( my_id ) VALUES (NULL  )
GO

ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;
GO

Gives you this error

Msg 515, Level 16, State 2, Line 9 Cannot insert the value NULL into
  column 'my_id', table 'xStuff.dbo.my_details'; column does not allow
  nulls. UPDATE fails.

trying to add a primary key gives you this

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);
GO

Msg 8111, Level 16, State 1, Line 16 Cannot define PRIMARY KEY
  constraint on nullable column in table 'my_details'. Msg 1750, Level
  16, State 0, Line 16 Could not create constraint. See previous errors.

However

place an update in between and this change works

CREATE TABLE my_details ( my_id varchar(50) NULL );
GO

INSERT INTO dbo.my_details ( my_id ) VALUES (NULL  );
GO

UPDATE dbo.my_details SET my_id = '' WHERE my_id IS NULL;
GO

ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;
GO

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);
GO


问:
Open the same window.location.origin in a new tab without cache
Framework: Angular 1.4.8

I want to create a new tab which takes the same window.location.origin that the old tab has. But I want to ensure that data is loaded from the server and not from cache.

There is a method to open the new tab: window.open(window.location.origin).

But I can't find any option which disables cache in the API reference. I am looking for an option similar to forcedReload in the window.location.reload method.

答:
Try to add these meta tags to the page. It helps to load the page without using cache. I hope the project is in ASP.NET</p>

```<code><!-- HTTP 1.1 -->
<meta http-equiv="Cache-Control" content="no-store"/>
<!-- HTTP 1.0 -->
<meta http-equiv="Pragma" content="no-cache"/>
<!-- Prevents caching at the Proxy Server -->
<meta http-equiv="Expires" content="0"/>
</code>```

Body:
Try to add these meta tags to the page. It helps to load the page without using cache. I hope the project is in ASP.NET

<!-- HTTP 1.1 -->
<meta http-equiv="Cache-Control" content="no-store"/>
<!-- HTTP 1.0 -->
<meta http-equiv="Pragma" content="no-cache"/>
<!-- Prevents caching at the Proxy Server -->
<meta http-equiv="Expires" content="0"/>


问:
How to assign values to Nested Json array
I am using C#. I want the Json array in the below structure

```<code>"bed_configurations": [
           [{
             "type": "standard",
             "code": 3,
             "count": 1
             },
             {
              "type": "custom",
              "name": "Loft",
              "count": 1
             }]
        ]
</code>```

Please any one can help me..

答:
Your best approach would be to create a class that resembles this structure, and use Newtonsoft.JSON to serialize/deserialize the object to/from a json string.

```<code>public class BedConfiguration
{
    [JsonProperty("type")]
    public string Type {get; set;}
    [JsonProperty("code")]
    public int Code {get; set;}
    [JsonProperty("count")]
    public int Count {get; set;}
}
</code>```

And the whole json string is simply an array, within an array, of the class above (strangely). So you could populate a list of these BedConfigurationand then serialize them:

```<code>var configs = new List<List<BedConfiguration>>();
//Populate the list programmatically.
var json = JsonConvert.SerializeObject(configs);
</code>```

Similarly, you can turn the json string back into a list:

```<code>var configs = JsonConvert.DeserializeObject<List<List<BedConfiguration>>>(json);
</code>```

Body:
I am using C#. I want the Json array in the below structure

"bed_configurations": [
           [{
             "type": "standard",
             "code": 3,
             "count": 1
             },
             {
              "type": "custom",
              "name": "Loft",
              "count": 1
             }]
        ]

Please any one can help me..

Body:
Your best approach would be to create a class that resembles this structure, and use Newtonsoft.JSON to serialize/deserialize the object to/from a json string.

public class BedConfiguration
{
    [JsonProperty("type")]
    public string Type {get; set;}
    [JsonProperty("code")]
    public int Code {get; set;}
    [JsonProperty("count")]
    public int Count {get; set;}
}

And the whole json string is simply an array, within an array, of the class above (strangely). So you could populate a list of these BedConfigurationand then serialize them:

var configs = new List<List<BedConfiguration>>();
//Populate the list programmatically.
var json = JsonConvert.SerializeObject(configs);

Similarly, you can turn the json string back into a list:

var configs = JsonConvert.DeserializeObject<List<List<BedConfiguration>>>(json);


问:
ZeroMQ XPUB/XSUB Serious Flaw?
It seems as though the XPUB/XSUB socket types have a serious flaw that is difficult to work around:

This is my implementation of that center node:

```<code>#include <zmq.hpp>

int main()
{
    zmq::context_t context(1);

    //Incoming publications come here
    zmq::socket_t sub(context, ZMQ_XSUB);
    sub.bind("ipc://subscriber.ipc");

    //Outgoing publications go out through here.
    zmq::socket_t pub(context, ZMQ_XPUB);
    pub.bind("ipc://publisher.ipc");

    zmq::proxy(sub, pub, nullptr);

    return 0;
}
</code>```

The problem is, of course, slow joiner syndrome. If I connect a new publisher to XSUB and publish some messages, they disappear into the void:

```<code>#include "zhelpers.hpp"

int main () {
    //  Prepare our context and publisher
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUB);
    publisher.connect("ipc://subscriber.ipc");

    s_sendmore (publisher, "B");
    s_send (publisher, "Disappears into the void!!");

    return 0;
}
</code>```

However, if I sleep(1) after connecting to XSUB, it magically works:

```<code>#include "zhelpers.hpp"

int main () {
    //  Prepare our context and publisher
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUB);
    publisher.connect("ipc://subscriber.ipc");

    sleep(1);
    s_sendmore (publisher, "B");
    s_send (publisher, "Magically works!!");

    return 0;
}
</code>```

The Guide claims there is a simple solution to this "slow joiners" syndrome, but then never delivers a working synchronized XSUB/XPUB implementation. After much searching it looks like most people are just sleeping, which is really bad.

Why hasn't this ever been fixed? Are there any known workarounds? All my google queries just point me back to the guide...

答:
I found one workaround here, and that is to use PUSH/PULL on the publisher side, and PUB/SUB on the subscriber side. The new topology looks like this:

This is the code you need for the center node:

```<code>#include <zmq.hpp>

int main()
{
    zmq::context_t context(1);

    //Incoming publications come here
    zmq::socket_t sub(context, ZMQ_PULL);
    sub.bind("ipc://subscriber.ipc");

    //Outgoing publications go out through here.
    zmq::socket_t pub(context, ZMQ_PUB);
    pub.bind("ipc://publisher.ipc");

    zmq::proxy(sub, pub, nullptr);

    return 0;
}
</code>```

And then for publishers:

```<code>#include "zhelpers.hpp"

int main () {
    //  Prepare our context and publisher
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUSH);
    publisher.connect("ipc://subscriber.ipc");

    s_sendmore (publisher, "B");
    s_send (publisher, "No sleep!");

    return 0;
}
</code>```

This solution seems to work fairly well, and I hope people chime in if they see any downsides to it. If I come across a better answer, I'll post here.

Title: ZeroMQ XPUB/XSUB Serious Flaw?

Body:
It seems as though the XPUB/XSUB socket types have a serious flaw that is difficult to work around:

This is my implementation of that center node:

#include <zmq.hpp>

int main()
{
    zmq::context_t context(1);

    //Incoming publications come here
    zmq::socket_t sub(context, ZMQ_XSUB);
    sub.bind("ipc://subscriber.ipc");

    //Outgoing publications go out through here.
    zmq::socket_t pub(context, ZMQ_XPUB);
    pub.bind("ipc://publisher.ipc");

    zmq::proxy(sub, pub, nullptr);

    return 0;
}

The problem is, of course, slow joiner syndrome. If I connect a new publisher to XSUB and publish some messages, they disappear into the void:

#include "zhelpers.hpp"

int main () {
    //  Prepare our context and publisher
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUB);
    publisher.connect("ipc://subscriber.ipc");

    s_sendmore (publisher, "B");
    s_send (publisher, "Disappears into the void!!");

    return 0;
}

However, if I sleep(1) after connecting to XSUB, it magically works:

#include "zhelpers.hpp"

int main () {
    //  Prepare our context and publisher
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUB);
    publisher.connect("ipc://subscriber.ipc");

    sleep(1);
    s_sendmore (publisher, "B");
    s_send (publisher, "Magically works!!");

    return 0;
}

The Guide claims there is a simple solution to this "slow joiners" syndrome, but then never delivers a working synchronized XSUB/XPUB implementation. After much searching it looks like most people are just sleeping, which is really bad.

Why hasn't this ever been fixed? Are there any known workarounds? All my google queries just point me back to the guide...

Body:
I found one workaround here, and that is to use PUSH/PULL on the publisher side, and PUB/SUB on the subscriber side. The new topology looks like this:

This is the code you need for the center node:

#include <zmq.hpp>

int main()
{
    zmq::context_t context(1);

    //Incoming publications come here
    zmq::socket_t sub(context, ZMQ_PULL);
    sub.bind("ipc://subscriber.ipc");

    //Outgoing publications go out through here.
    zmq::socket_t pub(context, ZMQ_PUB);
    pub.bind("ipc://publisher.ipc");

    zmq::proxy(sub, pub, nullptr);

    return 0;
}

And then for publishers:

#include "zhelpers.hpp"

int main () {
    //  Prepare our context and publisher
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUSH);
    publisher.connect("ipc://subscriber.ipc");

    s_sendmore (publisher, "B");
    s_send (publisher, "No sleep!");

    return 0;
}

This solution seems to work fairly well, and I hope people chime in if they see any downsides to it. If I come across a better answer, I'll post here.


问:
Visual Studio 2017 Community -- C#7 ref returns working but not intellisense
So, I've installed VS 2017, imported all my projects and was ready to try out all the new features of C# 7.  Most work.

The problematic one for me has been the new ref returns feature.  The puzzling thing is, they work!  They compile and produce the expected results.  The problem I've been having (in a C# 7 class library project targeting .NET 4.6.2 with AnyCPU as the target) is intellisense, the autoformatter, the auto-complete and resharper all think they don't work.  (Even though they compile and behave as expected).

```<code>public static class SomeClass
{
    public static ref int GetIntByReference()
    {
        //Compiles and does what it promises -
        //returns _someInt by reference
        return ref _someInt;
    }
    private static int _someInt = 15;
}
</code>```

I get a red squiggly between static and ref with a little "unexpected token" tool-tip.  Another squiggly under the word ref on the return line with a tool-tip explaining that a semi-colon is expected.  Finally, a squiggly appears under _someInt in the return line indicating that "only assignment, call, increment, decrement, await expression, and new object expression can be used as a statement"

So ... anyone else run into this?  The temporary squigglies I can live with, but the autoformat and complete is so hosed, I'm not going to use this feature until there is some kind of resolution.  If anyone else has encountered this problem and found a solution, I'd appreciate it if you'd let me know what you did.

答:
I found the same thing to be true in VS 2017. I had been able to do a Resharper "Repair" using the install tool and that worked for about 2 weeks, but now with the latest VS 2017 patch released the other day, it's gotten worse. I've repaird visual studio 2017, I've repaired resharper with the latest, and XAML intellisense just doesn't work. I've tried disabling Resharper intellisense in the resharper options, and nothing works.

So what I did to get this working is to simply disable Resharper from Tools and Extensions and restart Visual Studio 2017. Everything works perfectly now, except I can't use Resharper. This is the only thing I've found that works, for what it's worth.  I feel your pain.

Body:
So, I've installed VS 2017, imported all my projects and was ready to try out all the new features of C# 7.  Most work.

The problematic one for me has been the new ref returns feature.  The puzzling thing is, they work!  They compile and produce the expected results.  The problem I've been having (in a C# 7 class library project targeting .NET 4.6.2 with AnyCPU as the target) is intellisense, the autoformatter, the auto-complete and resharper all think they don't work.  (Even though they compile and behave as expected).

public static class SomeClass
{
    public static ref int GetIntByReference()
    {
        //Compiles and does what it promises -
        //returns _someInt by reference
        return ref _someInt;
    }
    private static int _someInt = 15;
}

I get a red squiggly between static and ref with a little "unexpected token" tool-tip.  Another squiggly under the word ref on the return line with a tool-tip explaining that a semi-colon is expected.  Finally, a squiggly appears under _someInt in the return line indicating that "only assignment, call, increment, decrement, await expression, and new object expression can be used as a statement"

So ... anyone else run into this?  The temporary squigglies I can live with, but the autoformat and complete is so hosed, I'm not going to use this feature until there is some kind of resolution.  If anyone else has encountered this problem and found a solution, I'd appreciate it if you'd let me know what you did.


问:
ExtJs: How can I select first item of Radiogroup on button click event
I have a radiogroup and on button click event I want to set the first item of radiogroup to be selected. I have tried below code, but it is not working:

```<code>Ext.create('Ext.panel.Panel',{
    items: [
    {
                title: "Types",
                items: {
                    xtype: "radiogroup",
                    name: "type",
                    columns: 2,
                    vertical: true,
                    items: [{
                        xtype: "radio",
                        boxLabel: "Vertical",
                        inputValue: "2",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout",

                    }, {
                        xtype: "radio",
                        boxLabel: "Horizontal",
                        inputValue: "1",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }, {
                        xtype: "radio",
                        boxLabel: "Auto",
                        inputValue: "0",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }]
                }
            }
    , {
        xtype: 'button',
        text: 'Reset',
        handler: function (button) {
            Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

        }
    }],
    renderTo: Ext.getBody()
});
</code>```

Above code is not working. I have also tried below code. But it also doesn't work:

```<code>var radioGroup = this.settingsFields.down(_.replace('[name="id"]', 'id', id));
radioGroup.select(radioGroup.getStore().getAt(0));
</code>```

答:
Fiddle

You need to add radiogroup in query

```<code>Ext.ComponentQuery.query('radiogroup[name="type"]'[0].items.items[0].setValue(true);
</code>```

Body:
I have a radiogroup and on button click event I want to set the first item of radiogroup to be selected. I have tried below code, but it is not working:

Ext.create('Ext.panel.Panel',{
    items: [
    {
                title: "Types",
                items: {
                    xtype: "radiogroup",
                    name: "type",
                    columns: 2,
                    vertical: true,
                    items: [{
                        xtype: "radio",
                        boxLabel: "Vertical",
                        inputValue: "2",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout",

                    }, {
                        xtype: "radio",
                        boxLabel: "Horizontal",
                        inputValue: "1",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }, {
                        xtype: "radio",
                        boxLabel: "Auto",
                        inputValue: "0",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }]
                }
            }
    , {
        xtype: 'button',
        text: 'Reset',
        handler: function (button) {
            Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

        }
    }],
    renderTo: Ext.getBody()
});

Above code is not working. I have also tried below code. But it also doesn't work:

var radioGroup = this.settingsFields.down(_.replace('[name="id"]', 'id', id));
radioGroup.select(radioGroup.getStore().getAt(0));

Body:
Fiddle

You need to add radiogroup in query

Ext.ComponentQuery.query('radiogroup[name="type"]'[0].items.items[0].setValue(true);


问:
Xamarin - apk App Size
So, after all the hard-work developing the app using Xamarin.Forms, when I tried to create a release build today, I was shocked to see the app size is ~25MB - ~31MB (after SDK Only Linking, ProGuard, Creating apk for each abi). My resource folder is only in KBs. The apk actually was just 5MB in debug mode and was so happy to see it. I later realized that this is because of the option "Use Shared Runtime" which we are not supposed to use in Release Mode.

I then tried creating a blank Xamarin.Android app, but the release build with Linking SDK & User Assemblies, ProGuard, APK for each abi is still ~8MB to ~13MB.

Per the below link the minimum size is 2.9MB with the Hello World app, however I am unable to create such size. https://developer.xamarin.com/guides/android/advanced_topics/application_package_sizes/

For my app and the blank app I created, the necessary dlls seem to be high (example mscorlib.dll is 2.2mb etc, where as the link says after linking it will become 1 mb) Here is what I see as my assembly folder after extracting the apk

In one of the recent Microsoft tech conferences I happened to know that "9 News" app (link below) was built using xamarin, and the creators were present on the stage. However I was surprised with it's app size. It is only 5.85 MB. I am unsure how that is achieved?

Can any one help me with these?

https://play.google.com/store/apps/details?id=nineNewsAlerts.nine.com

I am also curious to know if Microsoft doing something to improve app package sizes? Or will this be resolved if they bring .NET core to xamarin?

答:
Xamarin Android APK files have a larger size than usual because they include the Xamarin libraries, that translate C# code to Java code, to run in Android OS.

Using the following options, you can reduce the APK size:

Configuration: Active (Release).

Platform: Active (Any CPU). These are necessary to build your APK for the Google Play Store.

Use Shared Runtime: false. If you set it to true, the APK will use Mono Runtime to execute. The Mono Runtime is installed automatically when debugging through USB, but not in the Release APK. If Mono Runtime is not installed in the device and this option is set to true in the Release APK, the app will crash.

Generate one package (.apk) per selected ABI: false. Create your APK for as many platforms as possible, for compatibility reasons.

Enable Multi-Dex: true, but you can set it to false if your app is not very complex (that is, has less than 65536 variables or methods, see here).

Enable developer instrumentation (debugging and profiling): false for Release APK.

Linking: SDK and User Assemblies. This will make the Xamarin compiler to remove all unused classes from SDK and your code, reducing the APK size.

Supported architectures: Select all, for compatibility reasons.

Here is a print screen example:

Title: Xamarin - apk App Size


问:
When should I use getActivity() and getContext() from a Fragment?
I was wondering when should I use getActivity() and getContext() from a Fragment? and why not using getActivity always. Is there any situation where getActivity could fail?</p>

答:
Not sure there is a getActivityContext() method, but as far as the difference between getContext() and getActivity(), there really isn't one other than the type you get back from the call.  From the source the v4 Fragment, it's just a convenience method that casts the Context to an Activity or FragmentActivity before returning, and it's similar for the normal Fragment class.

```<code>/**
 * Return the {@link Context} this fragment is currently associated with.
 */
public Context getContext() {
    return mHost == null ? null : mHost.getContext();
}

/**
 * Return the {@link FragmentActivity} this fragment is currently associated with.
 * May return {@code null} if the fragment is associated with a {@link Context}
 * instead.
 */
final public FragmentActivity getActivity() {
    return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}
</code>```

Also, an Activity is a Context, so there's not much of a difference.

Body:
Not sure there is a getActivityContext() method, but as far as the difference between getContext() and getActivity(), there really isn't one other than the type you get back from the call.  From the source the v4 Fragment, it's just a convenience method that casts the Context to an Activity or FragmentActivity before returning, and it's similar for the normal Fragment class.

/**
 * Return the {@link Context} this fragment is currently associated with.
 */
public Context getContext() {
    return mHost == null ? null : mHost.getContext();
}

/**
 * Return the {@link FragmentActivity} this fragment is currently associated with.
 * May return {@code null} if the fragment is associated with a {@link Context}
 * instead.
 */
final public FragmentActivity getActivity() {
    return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}

Also, an Activity is a Context, so there's not much of a difference.


问:
Offline Vector Tile Package Style
Is there currently a way to swap out styles of an offline local Vector Tile Package (.vtpk) without ArcGIS Pro?  I'm open to accomplishing this programatically with the ArcGIS Runtime SDK for .NET (WPF).  The goal is to maintain a single copy instead of two copies of a vector tile package with differing styles.

Thank you

答: ArcGIS Runtime doesn't have support for custom styles with .vtpk files at the moment. Unfortunately you have to use the 2 file approach with different default styles defined for now (release 100.0). That said, we are working to get a proper support for the offline styles to the runtime in next releases.

Title: Offline Vector Tile Package Style


问:
ASP.net MVC DropDownListFor or DropDownList with Strongly Typed ViewModel
I'm looking for an example of using DropDownListFor with a strongly typed view model. I have searched extensively and cannot find a good up to date example. </p>

答:
```<code><%= Html.DropDownListFor(m => m.Property,
    new SelectList(your_collection, "key", "code", Model.Property), "") %>
</code>```

<p>"key" and "code" are properties of your Collection objects and the empty "" at the end is an optional label.</p>

Body:
<%= Html.DropDownListFor(m => m.Property,
    new SelectList(your_collection, "key", "code", Model.Property), "") %>

"key" and "code" are properties of your Collection objects and the empty "" at the end is an optional label.


问:
Is my dropdown menu (on change submit function) crawlable?
i have the following function to switch between the FAQ categorys.

```<code><form name="choose_faq" action="" method="post">
        <select name="cat" onChange="document.choose_faq.submit()">
          <option value="">- {FAQNAME} -</option>
          <!-- BEGIN faqs -->
          <option value="{faqs.ID}"></option>
          <!-- END faqs -->
        </select>
      </form>
</code>```

The crawler from Visual SEO Studio dont use the dropdown menu to crawl the children pages. But what is with the googlebot, can he crawl the dropdown?

Kindly regards!

答:
Yes, Googlebot can see your options when crawling your page.

Google bot starts with reading your robots.txt file and obeys your blocking requests.  It also reads the <title> tag in your  and your <meta name="description"> tag.  Finally, it reads all of your content.

From: https://blog.kissmetrics.com/the-way-google-scans/

Googlebot can also see your content delivered by javascript.  It has been doing so since 2008 and has been improving its capacity to do so ever since.

From: http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157

Body:
i have the following function to switch between the FAQ categorys.

<form name="choose_faq" action="" method="post">
        <select name="cat" onChange="document.choose_faq.submit()">
          <option value="">- {FAQNAME} -</option>

          <option value="{faqs.ID}"></option>

        </select>
      </form>

The crawler from Visual SEO Studio dont use the dropdown menu to crawl the children pages. But what is with the googlebot, can he crawl the dropdown?

Kindly regards!

Body:
Yes, Googlebot can see your options when crawling your page.

Google bot starts with reading your robots.txt file and obeys your blocking requests.  It also reads the <title> tag in your <head> and your <meta name="description"> tag.  Finally, it reads all of your content.

From: https://blog.kissmetrics.com/the-way-google-scans/

Googlebot can also see your content delivered by javascript.  It has been doing so since 2008 and has been improving its capacity to do so ever since.

From: http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157


问:
Symfony instance fails to see directories as writable
I've been filtering through google to try to find an answer to this, but I still can't find one that fixes my issue.  I have migrated a website to a new server.  The framework is Symfony 2.8 on php5.6 using Nginx and PHP-FPM.

Here is a screenshot of the config.php page.

To resolve this, i've tried...

Changing the user for Nginx and php-fpm to both the user I log in with and Nginx, both didn't work

I've opened up the privileges on the cache and log folder to 777 within the app folder, and that didn't work, nope.

I've tried assigning the cache and logs folder to nginx:nginx, no go.

I've manually assigned app.php, app_dev.php, and the console file to have the umask(0000) and umask(0002), nope.

Restarted the Nginx service and php-fpm service after each change, nodda.

I've restarted the entire server thinking something might be stuck, but you guessed it. No!

That leaves me here.  I've gone through everything that I can think of and it baffles me that Symfony still won't recognize the directory as writable.  It seems like the most simple thing, but... nope.

Anything will help, please pass anything along.

答:
After countless hours of research and scraping the internet for details, I have found the answer!  I'm posting it here in case someone else is having the same issue... and hopefully I can save them some time.  This took up two days of my life that i'll never get back.

For whatever reason, SELinux was causing this error.  I came across this issue on superuser stack exchange, and it told me to temporarily disable SELinux to test.  After running sudo setenforce 0 everything came back up.  I then completely disabled it and everything has been working fine since.

This happened suddenly and i'm still unsure of the reason.  The site worked for about a week before this was triggered.


问:
Remove all punctuation from string, except if it's between digits
I have a text that contains words and numbers. I'll give a representative example of the text:

```<code>string = "This is a 1example of the text. But, it only is 2.5 percent of all data"
</code>```

I'd like to convert it to something like:

```<code>"This is a  1 example of the text But it only is  2.5  percent of all data"
</code>```

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

```<code>item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item
</code>```

The result is :

```<code> >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"
</code>```

I'm almost there but can't figure out that last peace.

答:
I am out of touch with Python, but have some insight into the regexps.
My I suggest the usage of or?
I would use this regexp: "(\d+)([a-zA-Z])|([a-zA-Z])(\d+)", and then as the replacement string use:  "\1 \2"
If some corner cases plague you, you can pass the back-reference to a procedure, and then deal 1-by-1, probably by checking if your "\1\2" can translate to float. TCL has such built-in functionality, Python should too.

Body:
I have a text that contains words and numbers. I'll give a representative example of the text:

string = "This is a 1example of the text. But, it only is 2.5 percent of all data"

I'd like to convert it to something like:

"This is a  1 example of the text But it only is  2.5  percent of all data"

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item

The result is :

 >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"

I'm almost there but can't figure out that last peace.