问:
TypeError: 'tuple' object cannot be interpreted as an integer"
I'm trying to make a super basic evolution simulator to generate ten random "creatures" that are each a number value and then give them a random "mutation" but it keeps throwing me this error: "for i in range(creatures):
TypeError: 'tuple' object cannot be interpreted as an integer"</p>

```<code>import random
from random import randint

creatures = (random.randint(1, 10), random.randint(1, 10))

print(creatures)

for i in range(creatures):
    mutation = random.randint(1, 2)
    newEvolution = creatures[i] + mutation

print("New evolution", newEvolution)
</code>```

答:
creatures is a tuple and range is looking for an integer. To iterate over a tuple, just do:

```<code>for c in creatures:
    mutation = random.randint(1, 2)
    newEvolution = c + mutation
</code>```

Body:
I'm trying to make a super basic evolution simulator to generate ten random "creatures" that are each a number value and then give them a random "mutation" but it keeps throwing me this error: "for i in range(creatures):
TypeError: 'tuple' object cannot be interpreted as an integer"

import random
from random import randint

creatures = (random.randint(1, 10), random.randint(1, 10))

print(creatures)

for i in range(creatures):
    mutation = random.randint(1, 2)
    newEvolution = creatures[i] + mutation

print("New evolution", newEvolution)

Body:
creatures is a tuple and range is looking for an integer. To iterate over a tuple, just do:

for c in creatures:
    mutation = random.randint(1, 2)
    newEvolution = c + mutation


来源: stackexchange

问:
How do you send a docusign envelope later after it is created using PHP sdk
I'm trying to send an envelope after it is created because I'm adding a redirect url to recipients view.

I am unable to find a way to send the envelope except at createEnvelope function which depends on $envelop_definition->setStatus("sent");

I am using DocuSign PHP sdk

```<code>$envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
$envelop_definition->setEmailSubject($subject);
$envelop_definition->setTemplateId($templateid);
$envelop_definition->setTemplateRoles($templateRoles);
//$envelop_definition->setStatus("sent");

$options = new \DocuSign\eSign\Api\EnvelopesApi\CreateEnvelopeOptions();
$options->setCdseMode(null);
$options->setMergeRolesOnDraft(null);

// create and send the envelope (aka signature request)
$envelop_summary = $envelopeApi->createEnvelope($accountId, $envelop_definition, $options);
$envelop_summary = json_decode($envelop_summary);
if(!empty($envelop_summary)){
// set the returnURL
$envelope_id = $envelop_summary->envelopeId;
$url = 'http://www.mywebsite.com/docusign/helloworld.html?envelope_id=' . $envelope_id;

foreach ($recipients->getSigners() as $recipient) {
     $recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest();
     // set where the recipient is re-directed once they are done signing
     recipient_view_request->setReturnUrl($url);
}
</code>```

答:
DocuSign PHP SDK users:</p>

```<code>$envelopeApi->update($accountId, $envelope_id, json_encode(['status' => 'sent']));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to send an envelope after it is created because I'm adding a redirect url to recipients view.

I am unable to find a way to send the envelope except at createEnvelope function which depends on $envelop_definition->setStatus("sent");

I am using DocuSign PHP sdk

$envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
$envelop_definition->setEmailSubject($subject);
$envelop_definition->setTemplateId($templateid);
$envelop_definition->setTemplateRoles($templateRoles);
//$envelop_definition->setStatus("sent");

$options = new \DocuSign\eSign\Api\EnvelopesApi\CreateEnvelopeOptions();
$options->setCdseMode(null);
$options->setMergeRolesOnDraft(null);

// create and send the envelope (aka signature request)
$envelop_summary = $envelopeApi->createEnvelope($accountId, $envelop_definition, $options);
$envelop_summary = json_decode($envelop_summary);
if(!empty($envelop_summary)){
// set the returnURL
$envelope_id = $envelop_summary->envelopeId;
$url = 'http://www.mywebsite.com/docusign/helloworld.html?envelope_id=' . $envelope_id;

foreach ($recipients->getSigners() as $recipient) {
     $recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest();
     // set where the recipient is re-directed once they are done signing
     recipient_view_request->setReturnUrl($url);
}

Body:
DocuSign PHP SDK users:

$envelopeApi->update($accountId, $envelope_id, json_encode(['status' => 'sent']));


问:
Remove filename from URLs
I need to remove just filename (Ex.: 'number.pdf') from a URL:

http://URL.com/S01/000/users/info/4512.pdf

http://URL.com/S0152/01009/users/old/info/007401.pdf

http://URL.com/S45012/0000/users/info/14.pdf

http://URL.com/S450101/0/users/new/info/7895409.pdf

http://URL.com/S01/0000/users/info/1045.pdf

http://URL.com/S004/9082-00/users/areas-latam-co/info/65471.pdf

http://URL.com/S004/9082-246/users/areas-us/info/1530.pdf

Finally, I'd like get just this:

http://URL.com/S01/000/users/info/

http://URL.com/S0152/01009/users/old/info/

http://URL.com/S45012/0000/users/info/

http://URL.com/S450101/0/users/new/info/

http://URL.com/S01/0000/users/info/

http://URL.com/S004/9082-00/users/areas-latam-co/info/

http://URL.com/S004/9082-246/users/areas-us/info/

How Can i do it?

Any idea? Who say I?

答:
This can be easily done with os.path.dirname().

Example:

```<code>import os

print(os.path.dirname('http://URL.com/S01/000/users/info/4512.pdf'))
</code>```

Output:

```<code>http://URL.com/S01/000/users/info
</code>```

Title: Remove filename from URLs

Body:
This can be easily done with os.path.dirname().

Example:

import os

print(os.path.dirname('http://URL.com/S01/000/users/info/4512.pdf'))

Output:

http://URL.com/S01/000/users/info


问:
How is the state from the DynamoDB table used while starting a Kinesis consumer application?
From the docs, it  is clear that when a KCL application is started with TRIM_HORIZON as the iterator type, the records are read from the start of the stream. The docs also mention that the state of the application is maintained in the DynamoDB table by using checkpointing.

However I do not find any reference where how this DynamoDB table information is used by KCL application.

In specific my problem is as follows -
I have stream with retention period of 168 hours which is a lot of data. Say my KCL(started with iterator at TRIM_HORIZON) was in sync with the incoming data and was processing records at the end of the stream and chekcpointing at regular intervals. Now if I restart my KCL, will it start from the beginning of the stream to read the data (168 hours before) but still use DynamoDB table to see the checkpoint and skip to the latest records or is the checkpoint information not used at all and the stream is read from the start irrespective?

In the latter case, it is unnecessary reprocessing of huge amount of data.

Should I be manually using the sequence number from the DynamoDB table to get the shard iterator?

答:
When a KCL application is restarted, it automatically restores its state from DynamoDB table, so you don't need to do anything manually. Processing continues from the last checkpoint that was made before restart, so be ready to process few duplicate items if the restart occurred unexpectedly and the application didn't have a chance to checkpoint before exit (though there may be other reasons for duplicates)

When restarting, be sure to provide the same application name as you did on the previous start. Otherwise KCL would treat this situation as creating a new separate application, would create a new DynamoDB table and start entirely independent processing.


问:
How to disable generated navigation properties in Linqpad?
For look up tables with 1:1 relationships, LinqPad generates a property that points back to the collection of objects that use the lookup value.  How to disable this?

It's causing problems when I try to serialize tables using Newtonsoft.JSON.

答:
You can't prevent LINQPad from generating these properties, but you can tell Newtonsoft not to serialize them, with IContractResolver:

http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size

Write your contract resolver class in the My Extensions query, so it will be available to all queries. In the CreateProperties method, where you filter the properties, you'll need to apply a condition on the property type to exclude navigation properties. The following will exclude all n:1 and 1:1 properties:

```<code>public class FlatResolver : DefaultContractResolver
{
  public static JsonSerializerSettings Settings =
    new JsonSerializerSettings { ContractResolver = new FlatResolver() };

  protected override IList<JsonProperty> CreateProperties (Type type, MemberSerialization memberSerialization)
  {
    IList<JsonProperty> properties = base.CreateProperties (type, memberSerialization);

    properties = properties
      .Where (p => !p.PropertyType.GetCustomAttributes (typeof (System.Data.Linq.Mapping.TableAttribute)).Any())
      .ToList();

    return properties;
  }
}
</code>```

And then to serialize, just do this:

```<code>JsonConvert.SerializeObject (myObject, FlatResolver.Settings).Dump();
</code>```

You can use similar logic to exclude 1:n, by checking for an IEnumerable of an entity type.

Body:
You can't prevent LINQPad from generating these properties, but you can tell Newtonsoft not to serialize them, with IContractResolver:

http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size

Write your contract resolver class in the My Extensions query, so it will be available to all queries. In the CreateProperties method, where you filter the properties, you'll need to apply a condition on the property type to exclude navigation properties. The following will exclude all n:1 and 1:1 properties:

public class FlatResolver : DefaultContractResolver
{
  public static JsonSerializerSettings Settings =
    new JsonSerializerSettings { ContractResolver = new FlatResolver() };

  protected override IList<JsonProperty> CreateProperties (Type type, MemberSerialization memberSerialization)
  {
    IList<JsonProperty> properties = base.CreateProperties (type, memberSerialization);

    properties = properties
      .Where (p => !p.PropertyType.GetCustomAttributes (typeof (System.Data.Linq.Mapping.TableAttribute)).Any())
      .ToList();

    return properties;
  }
}

And then to serialize, just do this:

JsonConvert.SerializeObject (myObject, FlatResolver.Settings).Dump();

You can use similar logic to exclude 1:n, by checking for an IEnumerable of an entity type.


问:
Get value of data-timestamp attribute
In my Chrome extension, I'm trying to get info from a page (the value of "data-timestamp": 1490893300813) via a content script, but the result shows 'null'.

//content script:

  var tsx = document.getElementsByClassName("date");
  var i;
  const ts = new Array;
  for (i = 0; i < tsx.length; i++) {
    var ts[i] = tsx[i].getAttribute("data-timestamp");
    console.log("Timestamp" + i + ": " + ts[i]);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--source code from page:-->

<div class="thread">
        <span data-timestamp="1490893300813" class="date">
            <span class="absolute">Do, 30.03.2017, 19:01</span>
            <span class="relative"></span>
        </span>
</div></code>```

I also noticed that the data-timestamp attribute is visible when I show source-code of the page (Ctrl+U) but it isn't visible in DevTools...

答:
You can use document.querySelector('.date') to select the element that has the date class. From there, you can get the element.dataset.timestamp to get the timestamp.

Your code could look something like:

//Get the timestamp as a number ( + is used to convert from a string to a number).
var timestamp = +document.querySelector('.date').dataset.timestamp;
console.log('Timestamp:', timestamp);

//Convert to a Date and display in ISO format for the UTC timezone.
var date = new Date(timestamp);
console.log(date.toISOString());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="thread">
        <span data-timestamp="1490893300813" class="date">
            <span class="absolute">Do, 30.03.2017, 19:01</span>
            <span class="relative"></span>
        </span>
</div></code>```

Title: Get value of data-timestamp attribute

Body:
In my Chrome extension, I'm trying to get info from a page (the value of "data-timestamp": 1490893300813) via a content script, but the result shows 'null'.

//content script:

  var tsx = document.getElementsByClassName("date");
  var i;
  const ts = new Array;
  for (i = 0; i < tsx.length; i++) {
    var ts[i] = tsx[i].getAttribute("data-timestamp");
    console.log("Timestamp" + i + ": " + ts[i]);
  }

            Do, 30.03.2017, 19:01

I also noticed that the data-timestamp attribute is visible when I show source-code of the page (Ctrl+U) but it isn't visible in DevTools...

Body:
You can use document.querySelector('.date') to select the element that has the date class. From there, you can get the element.dataset.timestamp to get the timestamp.

Your code could look something like:

//Get the timestamp as a number ( + is used to convert from a string to a number).
var timestamp = +document.querySelector('.date').dataset.timestamp;
console.log('Timestamp:', timestamp);

//Convert to a Date and display in ISO format for the UTC timezone.
var date = new Date(timestamp);
console.log(date.toISOString());

<div class="thread">
        <span data-timestamp="1490893300813" class="date">
            <span class="absolute">Do, 30.03.2017, 19:01</span>
            <span class="relative"></span>
        </span>
</div>


问:
How to do asynchronous validation with Reactive Forms (Angular2 RC3)?
I found this tutorial to do asynchronous validations. This doesn't work with RC3 (Reactive Froms) anymore.

How to do asynchronous validation here?

```<code>this.username = new FormControl( '', [ <any>Validators.required, <any>ProfileValidator.usernameTaken ]);

...

class ProfileValidator {

 static usernameTaken(control: FormControl): Promise<{[key:string]:boolean}> {

   let q = new Promise((resolve, reject) => {
     setTimeout(() => {
       resolve(null);
     }, 1000)
   });

   return q;
 }

}
</code>```

The FormControl is always invalid...

答:
The signature for the form control should have async validators as the 3rd arg like so: </p>

```<code>new FormControl( '',
    [ <any>Validators.required], //sync
    [<any>ProfileValidator.usernameTaken ] //async
    );
</code>```

Body:
I found this tutorial to do asynchronous validations. This doesn't work with RC3 (Reactive Froms) anymore.

How to do asynchronous validation here?

this.username = new FormControl( '', [ <any>Validators.required, <any>ProfileValidator.usernameTaken ]);

...

class ProfileValidator {

 static usernameTaken(control: FormControl): Promise<{[key:string]:boolean}> {

   let q = new Promise((resolve, reject) => {
     setTimeout(() => {
       resolve(null);
     }, 1000)
   });

   return q;
 }

}

The FormControl is always invalid...

Body:
The signature for the form control should have async validators as the 3rd arg like so:

new FormControl( '',
    [ <any>Validators.required], //sync
    [<any>ProfileValidator.usernameTaken ] //async
    );


问:
TypeError: descriptor 'strftime' requires a 'datetime.time' object but received a 'str'
I could run the following lines independently.

```<code> import time
 time.strftime("%Y%m%d")
</code>```

Then I put them into one class method I am defining

```<code> import time
 def method(self):
    ...
    [time.strftime("%Y%m%d") for x in range(5)]
    ...
</code>```

The list comprehension has no interaction with other lines.

then, it just threw the following error:

TypeError: descriptor 'strftime' requires a 'datetime.time' object but received a 'str'

could anyone give me a hint what is going on? Thank you.

答:
I find the solution by the following line:

```<code>from datetime import time
</code>```

instead of

```<code>import time
</code>```

Thanks a lot still.

Body:
I could run the following lines independently.

 import time
 time.strftime("%Y%m%d")

Then I put them into one class method I am defining

 import time
 def method(self):
    ...
    [time.strftime("%Y%m%d") for x in range(5)]
    ...

The list comprehension has no interaction with other lines.

then, it just threw the following error:

TypeError: descriptor 'strftime' requires a 'datetime.time' object but received a 'str'

could anyone give me a hint what is going on? Thank you.

Body:
I find the solution by the following line:

from datetime import time

instead of

import time

Thanks a lot still.


问:
Migrate website / application from IE6 to IE7 / IE8
At the moment I have to migrate a web-application (ASP.NET 2.0 with Masterpages) from IE6 to IE7/IE8. Where can I find hints and guidelines for this topic? The webapplication looks fine in IE6 but completely awful in IE7 and IE8. In IE8 I cannot see the compatibility button.

答: When moving a web application or site to operate with a different browser these situations can exist; that IE7 operates in a different jurisdiction or nation from IE6 and IE8; the laws and rules around IE7 may not allow some elements of webpage content like css or jscript or ecmascript or png or jpeg files or a different version and hosting server is required; the code or script behind NET is not fully runnable in some jurisdictions; some elements of the target computer operating system may be absent or different from the developer computer and environment; that NET is not lawful or legal in some nations.</p>

ContentLicense: CC BY-SA 2.5


问:
angularjs ng-repeat not update
I used the ng-repeat in the ion-slide and operated the array myTags in the controller，ion-slide-tab-label was custom directive.When I changed the array，ng-repeat view has not changed.If I use the method remove() and then add() the same tag,it would be error：duplicate. Here's the code.

slidingTabsDirective.js

```<code>var slidingTabsDirective = angular.module("ionic").directive('ionSlideTabs', ['$timeout', '$compile', '$interval', '$ionicSlideBoxDelegate', '$ionicScrollDelegate', '$ionicGesture', function($timeout, $compile, $interval, $ionicSlideBoxDelegate, $ionicScrollDelegate, $ionicGesture) {
return {
require: "^ionSlideBox",
restrict: 'A',
link: function(scope, element, attrs, parent) {

  var ionicSlideBoxDelegate;
  var ionicScrollDelegate;
  var ionicScrollDelegateID;

  var slideTabs;
  var indicator;

  var slider;
  var tabsBar;

  var options = {
    "slideTabsScrollable": true
  };

  var init = function() {

    if (angular.isDefined(attrs.slideTabsScrollable) && attrs.slideTabsScrollable == false) {
      options.slideTabsScrollable = false;
    }

    var tabItems = '<li ng-repeat="(key, value) in tabs" ng-click="onTabTabbed($event, {{key}})" class="slider-slide-tab" ng-bind-html="value"></li>';

    if (options.slideTabsScrollable) {
      //alert(options.slideTabsScrollable)

      ionicScrollDelegateID = "ion-slide-tabs-handle-" + Math.floor((Math.random() * 10000) + 1);
      tabsBar = angular.element('<ion-scroll delegate-handle="' + ionicScrollDelegateID + '" class="slidingTabs" direction="x" scrollbar-x="false"><ul>' + tabItems + '</ul> <div class="tab-indicator-wrapper"><div class="tab-indicator"></div></div> </ion-scroll>');

    } else {

      tabsBar = angular.element('<div class="slidingTabs"><ul>' + tabItems + '</ul> <div class="tab-indicator-wrapper"><div class="tab-indicator"></div></div> </div>');

    }

    slider = angular.element(element);

    var compiled = $compile(tabsBar);
    slider.parent().prepend(tabsBar);
    compiled(scope);

    //get Tabs DOM Elements
    indicator = angular.element(tabsBar[0].querySelector(".tab-indicator"));

    //get the slideBoxHandle
    var slideHandle = slider.attr('delegate-handle');
    var scrollHandle = tabsBar.attr('delegate-handle');

    ionicSlideBoxDelegate = $ionicSlideBoxDelegate;
    if (slideHandle) {
      ionicSlideBoxDelegate = ionicSlideBoxDelegate.$getByHandle(slideHandle);
    }

    if (options.slideTabsScrollable) {

      ionicScrollDelegate = $ionicScrollDelegate;
      if (scrollHandle) {
        ionicScrollDelegate = ionicScrollDelegate.$getByHandle(scrollHandle);
      }

    }

    addEvents();
    setTabBarWidth();
    slideToCurrentPosition();
  };

  var addEvents = function() {

    ionic.onGesture("dragleft", scope.onSlideMove, slider[0]);
    ionic.onGesture("dragright", scope.onSlideMove, slider[0]);
    ionic.onGesture("release", scope.onSlideChange, slider[0]);

  };

  var setTabBarWidth = function() {

    if (!angular.isDefined(slideTabs) || slideTabs.length == 0) {
      return false;
    }

    tabsList = tabsBar.find("ul");
    var tabsWidth = 0;

    angular.forEach(slideTabs, function(currentElement, index) {

      var currentLi = angular.element(currentElement);
      tabsWidth += currentLi[0].offsetWidth;
    });

    if (options.slideTabsScrollable) {

      angular.element(tabsBar[0].querySelector(".scroll")).css("width", tabsWidth + 1 + "px");

    } else {

      slideTabs.css("width", tabsList[0].offsetWidth / slideTabs.length + "px");
    }

    slideToCurrentPosition();
  };

  var slideToCurrentPosition = function() {

    if (!angular.isDefined(slideTabs) || slideTabs.length == 0) {
      return false;
    }

    var targetSlideIndex = ionicSlideBoxDelegate.currentIndex();

    var targetTab = angular.element(slideTabs[targetSlideIndex]);
    var targetLeftOffset = targetTab.prop("offsetLeft");
    var targetWidth = targetTab[0].offsetWidth;

    indicator.css({
      "-webkit-transition-duration": "300ms",
      "-webkit-transform": "translate(" + targetLeftOffset + "px,0px)",
      "width": targetWidth + "px"
    });

    if (options.slideTabsScrollable && ionicScrollDelegate) {
      var scrollOffset = 40;
      ionicScrollDelegate.scrollTo(targetLeftOffset - scrollOffset, 0, true);
    }

    slideTabs.removeClass("tab-active");
    targetTab.addClass("tab-active");

  };

  var setIndicatorPosition = function(currentSlideIndex, targetSlideIndex, position, slideDirection) {

    var targetTab = angular.element(slideTabs[targetSlideIndex]);

    var currentTab = angular.element(slideTabs[currentSlideIndex]);
    var targetLeftOffset = targetTab.prop("offsetLeft");

    var currentLeftOffset = currentTab.prop("offsetLeft");
    var offsetLeftDiff = Math.abs(targetLeftOffset - currentLeftOffset);

    if (currentSlideIndex == 0 && targetSlideIndex == ionicSlideBoxDelegate.slidesCount() - 1 && slideDirection == "right" ||
      targetSlideIndex == 0 && currentSlideIndex == ionicSlideBoxDelegate.slidesCount() - 1 && slideDirection == "left") {
      return;
    }

    var targetWidth = targetTab[0].offsetWidth;
    var currentWidth = currentTab[0].offsetWidth;
    var widthDiff = targetWidth - currentWidth;

    var indicatorPos = 0;
    var indicatorWidth = 0;

    if (currentSlideIndex > targetSlideIndex) {

      indicatorPos = targetLeftOffset - (offsetLeftDiff * (position - 1));
      indicatorWidth = targetWidth - ((widthDiff * (1 - position)));

    } else if (targetSlideIndex > currentSlideIndex) {

      indicatorPos = targetLeftOffset + (offsetLeftDiff * (position - 1));
      indicatorWidth = targetWidth + ((widthDiff * (position - 1)));

    }

    indicator.css({
      "-webkit-transition-duration": "0ms",
      "-webkit-transform": "translate(" + indicatorPos + "px,0px)",
      "width": indicatorWidth + "px"
    });

    if (options.slideTabsScrollable && ionicScrollDelegate) {
      var scrollOffset = 40;
      ionicScrollDelegate.scrollTo(indicatorPos - scrollOffset, 0, false);
    }

  };

  scope.onTabTabbed = function(event, index) {
    ionicSlideBoxDelegate.slide(index);
    slideToCurrentPosition();
  };

  scope.tabs = [];

  scope.addTabContent = function($content) {

    $content = $content.replace(/\“/g, '').replace(/\”/g, '');
    scope.tabs.push($content);
    scope.$apply();

    $timeout(function() {
      slideTabs = angular.element(tabsBar[0].querySelector("ul").querySelectorAll(".slider-slide-tab"));
      slideToCurrentPosition();
      setTabBarWidth();
    });

  };

  scope.onSlideChange = function(slideIndex) {
    slideToCurrentPosition();
  };

  scope.onSlideMove = function() {
    var scrollDiv = slider[0].getElementsByClassName("slider-slide");

    var currentSlideIndex = ionicSlideBoxDelegate.currentIndex();
    var currentSlide = angular.element(scrollDiv[currentSlideIndex]);
    var currentSlideLeftOffset = currentSlide.css('-webkit-transform').replace(/[^0-9\-.,]/g, '').split(',')[0];

    var targetSlideIndex = (currentSlideIndex + 1) % scrollDiv.length;
    if (currentSlideLeftOffset > slider.prop("offsetLeft")) {
      targetSlideIndex = currentSlideIndex - 1;
      if (targetSlideIndex < 0) {
        targetSlideIndex = scrollDiv.length - 1;
      }
    }
    var targetSlide = angular.element(scrollDiv[targetSlideIndex]);

    var position = currentSlideLeftOffset / slider[0].offsetWidth;
    var slideDirection = position > 0 ? "right" : "left";
    position = Math.abs(position);

    setIndicatorPosition(currentSlideIndex, targetSlideIndex, position, slideDirection);
  };

  init();
},
controller: ['$scope', function($scope) {
  this.addTab = function($content) {
    $timeout(function() {
      if ($scope.addTabContent) {
        $scope.addTabContent($content);
      }
    });
  };
}]
};
}]);

slidingTabsDirective.directive('ionSlideTabLabel', [function() {
    return {
        require: "^ionSlideTabs",
        link: function($scope, $element, $attrs, $parent) {
            $parent.addTab($attrs.ionSlideTabLabel);
        }
    };
}]);
</code>```

index.html

```<code><ion-slide-box id="slide_box" show-pager="false" ion-slide-tabs>
    <ion-slide ng-repeat="tag in myTags track by $index" ion-slide-tab-label=“{{tag.tagname}}”>
    .........
    </ion-slide>
</ion-slide-box>
</code>```

service.js

```<code>function getTags() {
  var url = xxxxxxx;

  return $http({
      method: 'GET',
      url: url
    })
    .success(function(res) {
      //console.log('is collect success');
    })
    .error(function(msg, code) {
      console.log('tag error.....', code);
    });
}
</code>```

indexCtrl.js

```<code>$scope.tags = [];
$scope.myTags = [];
$scope.moreTags = [];

function getTags() {
    ds.getTags()
        .then(function(res) {
        var traTags = [];
        var l = res.data.length;
        $scope.tags = res.data;
        traTags = angular.copy($scope.tags);
        $scope.myTags = traTags.splice(0, l / 2);
        $scope.moreTags = traTags;
    });
}

function remove(index) {
    if (!$scope.lock) {
        $scope.moreTags.unshift($scope.myTags[index]);
        $scope.myTags.splice(index, 1);
    } else {
        return;
    }
}

function add(index) {
    $scope.myTags.push($scope.moreTags[index]);
    $scope.moreTags.splice(index, 1);
}
</code>```

what should I do? please help me! Thank you!

答:
function:

```<code>function addlist(obj, item, addtype) {
      var isdata = false;
      for (var i = 0; i < obj.length; i++) {
          if (obj[i] == item) {
              isdata = true;
              break;
          }
      }
      if (!isdata) {
          if (addtype) {
              obj.push(item);
          } else {
              obj.unshift(item);
          }
      }
  }
</code>```

code:

```

        function remove(index) {
        if (!$scope.lock) {
            addlist($scope.moreTags,$scope.myTags[index],false);
            $scope.myTags.splice(index, 1);
        } else {
            return;
        }
    }
    function add(index) {
        addlist($scope.myTags,$scope.moreTags[index],true);
        $scope.moreTags.splice(index, 1);
    }

```

Title: angularjs ng-repeat not update

Body:
I used the ng-repeat in the ion-slide and operated the array myTags in the controller，ion-slide-tab-label was custom directive.When I changed the array，ng-repeat view has not changed.If I use the method remove() and then add() the same tag,it would be error：duplicate. Here's the code.

slidingTabsDirective.js

var slidingTabsDirective = angular.module("ionic").directive('ionSlideTabs', ['$timeout', '$compile', '$interval', '$ionicSlideBoxDelegate', '$ionicScrollDelegate', '$ionicGesture', function($timeout, $compile, $interval, $ionicSlideBoxDelegate, $ionicScrollDelegate, $ionicGesture) {
return {
require: "^ionSlideBox",
restrict: 'A',
link: function(scope, element, attrs, parent) {

  var ionicSlideBoxDelegate;
  var ionicScrollDelegate;
  var ionicScrollDelegateID;

  var slideTabs;
  var indicator;

  var slider;
  var tabsBar;

  var options = {
    "slideTabsScrollable": true
  };

  var init = function() {

    if (angular.isDefined(attrs.slideTabsScrollable) && attrs.slideTabsScrollable == false) {
      options.slideTabsScrollable = false;
    }

    var tabItems = '

';

    if (options.slideTabsScrollable) {
      //alert(options.slideTabsScrollable)

      ionicScrollDelegateID = "ion-slide-tabs-handle-" + Math.floor((Math.random() * 10000) + 1);
      tabsBar = angular.element('<ion-scroll delegate-handle="' + ionicScrollDelegateID + '" class="slidingTabs" direction="x" scrollbar-x="false">
' + tabItems + '

 </ion-scroll>');

    } else {

      tabsBar = angular.element('

' + tabItems + '

');

    }

    slider = angular.element(element);

    var compiled = $compile(tabsBar);
    slider.parent().prepend(tabsBar);
    compiled(scope);

    //get Tabs DOM Elements
    indicator = angular.element(tabsBar[0].querySelector(".tab-indicator"));

    //get the slideBoxHandle
    var slideHandle = slider.attr('delegate-handle');
    var scrollHandle = tabsBar.attr('delegate-handle');

    ionicSlideBoxDelegate = $ionicSlideBoxDelegate;
    if (slideHandle) {
      ionicSlideBoxDelegate = ionicSlideBoxDelegate.$getByHandle(slideHandle);
    }

    if (options.slideTabsScrollable) {

      ionicScrollDelegate = $ionicScrollDelegate;
      if (scrollHandle) {
        ionicScrollDelegate = ionicScrollDelegate.$getByHandle(scrollHandle);
      }

    }

    addEvents();
    setTabBarWidth();
    slideToCurrentPosition();
  };

  var addEvents = function() {

    ionic.onGesture("dragleft", scope.onSlideMove, slider[0]);
    ionic.onGesture("dragright", scope.onSlideMove, slider[0]);
    ionic.onGesture("release", scope.onSlideChange, slider[0]);

  };

  var setTabBarWidth = function() {

    if (!angular.isDefined(slideTabs) || slideTabs.length == 0) {
      return false;
    }

    tabsList = tabsBar.find("ul");
    var tabsWidth = 0;

    angular.forEach(slideTabs, function(currentElement, index) {

      var currentLi = angular.element(currentElement);
      tabsWidth += currentLi[0].offsetWidth;
    });

    if (options.slideTabsScrollable) {

      angular.element(tabsBar[0].querySelector(".scroll")).css("width", tabsWidth + 1 + "px");

    } else {

      slideTabs.css("width", tabsList[0].offsetWidth / slideTabs.length + "px");
    }

    slideToCurrentPosition();
  };

  var slideToCurrentPosition = function() {

    if (!angular.isDefined(slideTabs) || slideTabs.length == 0) {
      return false;
    }

    var targetSlideIndex = ionicSlideBoxDelegate.currentIndex();

    var targetTab = angular.element(slideTabs[targetSlideIndex]);
    var targetLeftOffset = targetTab.prop("offsetLeft");
    var targetWidth = targetTab[0].offsetWidth;

    indicator.css({
      "-webkit-transition-duration": "300ms",
      "-webkit-transform": "translate(" + targetLeftOffset + "px,0px)",
      "width": targetWidth + "px"
    });

    if (options.slideTabsScrollable && ionicScrollDelegate) {
      var scrollOffset = 40;
      ionicScrollDelegate.scrollTo(targetLeftOffset - scrollOffset, 0, true);
    }

    slideTabs.removeClass("tab-active");
    targetTab.addClass("tab-active");

  };

  var setIndicatorPosition = function(currentSlideIndex, targetSlideIndex, position, slideDirection) {

    var targetTab = angular.element(slideTabs[targetSlideIndex]);

    var currentTab = angular.element(slideTabs[currentSlideIndex]);
    var targetLeftOffset = targetTab.prop("offsetLeft");

    var currentLeftOffset = currentTab.prop("offsetLeft");
    var offsetLeftDiff = Math.abs(targetLeftOffset - currentLeftOffset);

    if (currentSlideIndex == 0 && targetSlideIndex == ionicSlideBoxDelegate.slidesCount() - 1 && slideDirection == "right" ||
      targetSlideIndex == 0 && currentSlideIndex == ionicSlideBoxDelegate.slidesCount() - 1 && slideDirection == "left") {
      return;
    }

    var targetWidth = targetTab[0].offsetWidth;
    var currentWidth = currentTab[0].offsetWidth;
    var widthDiff = targetWidth - currentWidth;

    var indicatorPos = 0;
    var indicatorWidth = 0;

    if (currentSlideIndex > targetSlideIndex) {

      indicatorPos = targetLeftOffset - (offsetLeftDiff * (position - 1));
      indicatorWidth = targetWidth - ((widthDiff * (1 - position)));

    } else if (targetSlideIndex > currentSlideIndex) {

      indicatorPos = targetLeftOffset + (offsetLeftDiff * (position - 1));
      indicatorWidth = targetWidth + ((widthDiff * (position - 1)));

    }

    indicator.css({
      "-webkit-transition-duration": "0ms",
      "-webkit-transform": "translate(" + indicatorPos + "px,0px)",
      "width": indicatorWidth + "px"
    });

    if (options.slideTabsScrollable && ionicScrollDelegate) {
      var scrollOffset = 40;
      ionicScrollDelegate.scrollTo(indicatorPos - scrollOffset, 0, false);
    }

  };

  scope.onTabTabbed = function(event, index) {
    ionicSlideBoxDelegate.slide(index);
    slideToCurrentPosition();
  };

  scope.tabs = [];

  scope.addTabContent = function($content) {

    $content = $content.replace(/\“/g, '').replace(/\”/g, '');
    scope.tabs.push($content);
    scope.$apply();

    $timeout(function() {
      slideTabs = angular.element(tabsBar[0].querySelector("ul").querySelectorAll(".slider-slide-tab"));
      slideToCurrentPosition();
      setTabBarWidth();
    });

  };

  scope.onSlideChange = function(slideIndex) {
    slideToCurrentPosition();
  };

  scope.onSlideMove = function() {
    var scrollDiv = slider[0].getElementsByClassName("slider-slide");

    var currentSlideIndex = ionicSlideBoxDelegate.currentIndex();
    var currentSlide = angular.element(scrollDiv[currentSlideIndex]);
    var currentSlideLeftOffset = currentSlide.css('-webkit-transform').replace(/[^0-9\-.,]/g, '').split(',')[0];

    var targetSlideIndex = (currentSlideIndex + 1) % scrollDiv.length;
    if (currentSlideLeftOffset > slider.prop("offsetLeft")) {
      targetSlideIndex = currentSlideIndex - 1;
      if (targetSlideIndex < 0) {
        targetSlideIndex = scrollDiv.length - 1;
      }
    }
    var targetSlide = angular.element(scrollDiv[targetSlideIndex]);

    var position = currentSlideLeftOffset / slider[0].offsetWidth;
    var slideDirection = position > 0 ? "right" : "left";
    position = Math.abs(position);

    setIndicatorPosition(currentSlideIndex, targetSlideIndex, position, slideDirection);
  };

  init();
},
controller: ['$scope', function($scope) {
  this.addTab = function($content) {
    $timeout(function() {
      if ($scope.addTabContent) {
        $scope.addTabContent($content);
      }
    });
  };
}]
};
}]);

slidingTabsDirective.directive('ionSlideTabLabel', [function() {
    return {
        require: "^ionSlideTabs",
        link: function($scope, $element, $attrs, $parent) {
            $parent.addTab($attrs.ionSlideTabLabel);
        }
    };
}]);

index.html

<ion-slide-box id="slide_box" show-pager="false" ion-slide-tabs>
    <ion-slide ng-repeat="tag in myTags track by $index" ion-slide-tab-label=“{{tag.tagname}}”>
    .........
    </ion-slide>
</ion-slide-box>

service.js

function getTags() {
  var url = xxxxxxx;

  return $http({
      method: 'GET',
      url: url
    })
    .success(function(res) {
      //console.log('is collect success');
    })
    .error(function(msg, code) {
      console.log('tag error.....', code);
    });
}

indexCtrl.js

$scope.tags = [];
$scope.myTags = [];
$scope.moreTags = [];

function getTags() {
    ds.getTags()
        .then(function(res) {
        var traTags = [];
        var l = res.data.length;
        $scope.tags = res.data;
        traTags = angular.copy($scope.tags);
        $scope.myTags = traTags.splice(0, l / 2);
        $scope.moreTags = traTags;
    });
}

function remove(index) {
    if (!$scope.lock) {
        $scope.moreTags.unshift($scope.myTags[index]);
        $scope.myTags.splice(index, 1);
    } else {
        return;
    }
}

function add(index) {
    $scope.myTags.push($scope.moreTags[index]);
    $scope.moreTags.splice(index, 1);
}

what should I do? please help me! Thank you!

Body:
function:

function addlist(obj, item, addtype) {
      var isdata = false;
      for (var i = 0; i < obj.length; i++) {
          if (obj[i] == item) {
              isdata = true;
              break;
          }
      }
      if (!isdata) {
          if (addtype) {
              obj.push(item);
          } else {
              obj.unshift(item);
          }
      }
  }

code:

        function remove(index) {
        if (!$scope.lock) {
            addlist($scope.moreTags,$scope.myTags[index],false);
            $scope.myTags.splice(index, 1);
        } else {
            return;
        }
    }
    function add(index) {
        addlist($scope.myTags,$scope.moreTags[index],true);
        $scope.moreTags.splice(index, 1);
    }


问:
HTTP request doesn't fire off
I am new to Angluar and was following a video tutorial to make HTTP Request and getting the response data. For some reason the code I used doesn't fire off the http.get.</p>

```<code>import { Component, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

@Injectable()
export class AppComponent {

  constructor( private http: Http ){
    console.log('Until here works');
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(data => {
      console.log('Finished');
      console.log( data );
    });
  }

}
</code>```

答:
We use Services to minimize the number of code lines and development time.

make a separate service using angular-cli command ng g s Get
this will make a new service for you.but you need to add it as a provider in app.module.ts like this.

or if you are not using anular-cli make a file get.service.ts file and follow these steps

Check this sample application i made.

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { GetService } from './get.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [GetService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

add these codes in to get.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class GetService {

  constructor(private http: Http) { }
  getData() {
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(m => m.json()
    ).subscribe(k => { console.log(k) }); // we have to subscribe for get data out
  }
}
</code>```

app.component.ts should be like this.

```<code>import { Component,Injectable } from '@angular/core';
import { Http } from '@angular/http';

import { GetService } from './get.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  constructor(private _service : GetService ){
    this._service.getData();
  }
}
</code>```

read more about services here

Title: HTTP request doesn't fire off

Body:
I am new to Angluar and was following a video tutorial to make HTTP Request and getting the response data. For some reason the code I used doesn't fire off the http.get.

import { Component, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

@Injectable()
export class AppComponent {

  constructor( private http: Http ){
    console.log('Until here works');
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(data => {
      console.log('Finished');
      console.log( data );
    });
  }

}

Body:
We use Services to minimize the number of code lines and development time.

make a separate service using angular-cli command ng g s Get
this will make a new service for you.but you need to add it as a provider in app.module.ts like this.

or if you are not using anular-cli make a file get.service.ts file and follow these steps

Check this sample application i made.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { GetService } from './get.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [GetService],
  bootstrap: [AppComponent]
})
export class AppModule { }

add these codes in to get.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class GetService {

  constructor(private http: Http) { }
  getData() {
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(m => m.json()
    ).subscribe(k => { console.log(k) }); // we have to subscribe for get data out
  }
}

app.component.ts should be like this.

import { Component,Injectable } from '@angular/core';
import { Http } from '@angular/http';

import { GetService } from './get.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  constructor(private _service : GetService ){
    this._service.getData();
  }
}

read more about services here


问:
li tree menu from array
I have array:

parent 1 is first step!

```<code>Array
(
    [0] => Array
        (
            [categoryID] => 1
            [parent] => 1
            [name] => 111
        )

    [1] => Array
        (
            [categoryID] => 2
            [parent] => 1
            [name] => 2222
        )

    [2] => Array
        (
            [categoryID] => 3
            [parent] => 2
            [name] => 3333
        )
    [3] => Array
        (
            [categoryID] => 4
            [parent] => 3
            [name] => 444
        )

)
</code>```

In result I need tree structure with ul and li elements:

```<code><ul>
 <li>111</li>
 <li>222
  <ul>
   <li>333
   <ul>
    <li>444</li>
   </ul>
   </li>
  </ul>
 </li>
</ul>
</code>```

Thanks!

答: This array looks a lot like you got it from a database. If that's the case, please just use an MVC framework. It will make your life so much easier.</p>

Title: li tree menu from array

Body:
I have array:

parent 1 is first step!

Array
(
    [0] => Array
        (
            [categoryID] => 1
            [parent] => 1
            [name] => 111
        )

    [1] => Array
        (
            [categoryID] => 2
            [parent] => 1
            [name] => 2222
        )

    [2] => Array
        (
            [categoryID] => 3
            [parent] => 2
            [name] => 3333
        )
    [3] => Array
        (
            [categoryID] => 4
            [parent] => 3
            [name] => 444
        )

)

In result I need tree structure with ul and li elements:

111

222

333

444

Thanks!


问:
Custom "nullptr", but how to understand the codes?
It's from Wikipedia, if our compiler don't support c++11 , we can implement one by ourselves , just like below:

```<code>const class nullptr_t
{
public:
    template<class T>
    inline operator T*() const
        { return 0; }

    template<class C, class T>
    inline operator T C::*() const
        { return 0; }

private:
    void operator&() const;
} nullptr = {};
</code>```

I can't understand the above codes.

----------------------update------------------

Sorry , i didn't express it clear.

```<code> template<class T>
    inline operator T*() const
        { return 0; }

 template<class C, class T>
    inline operator T C::*() const
        { return 0; }
</code>```

The above codes,i don't understand the grammar.
I never see this kind of template form before.(like "operator T C::*()")

答:
```<code>template<class T>
inline operator T*() const
    { return 0; }
</code>```

means that an object of type nullptr_t can be implicitly converted to any (non-member) pointer type.    It is simply an operator T *() function (conversion to type T *) templated for any type T.

```<code>template<class C, class T>
inline operator T C::*() const
    { return 0; }
</code>```

means that an object of type nullptr_t can be converted to a pointer to a non-static member of any class (template parameter C)  of any type (template parameter T).

Both operators are const, so cannot change the nullptr_t object.

Body:
It's from Wikipedia, if our compiler don't support c++11 , we can implement one by ourselves , just like below:

const class nullptr_t
{
public:
    template<class T>
    inline operator T*() const
        { return 0; }

    template<class C, class T>
    inline operator T C::*() const
        { return 0; }

private:
    void operator&() const;
} nullptr = {};

I can't understand the above codes.

----------------------update------------------

Sorry , i didn't express it clear.

 template<class T>
    inline operator T*() const
        { return 0; }

 template<class C, class T>
    inline operator T C::*() const
        { return 0; }

The above codes,i don't understand the grammar.
I never see this kind of template form before.(like "operator T C::*()")

Body:
template<class T>
inline operator T*() const
    { return 0; }

means that an object of type nullptr_t can be implicitly converted to any (non-member) pointer type.    It is simply an operator T *() function (conversion to type T *) templated for any type T.

template<class C, class T>
inline operator T C::*() const
    { return 0; }

means that an object of type nullptr_t can be converted to a pointer to a non-static member of any class (template parameter C)  of any type (template parameter T).

Both operators are const, so cannot change the nullptr_t object.


问:
Adjust ActiveCell.FormulaR1C1
Hi I have a question I have code that i made with macro recorder:

```<code>ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"
</code>```

how can I adjust this code so it would be somthing like thi:

```<code>'ActiveCell.Formula = Sheets("New_Order").Range(n & LastRow) + Sheets("New_Order").Range(O & LastRow) + Sheets("New_Order").Range(p & LastRow)
</code>```

I have values in a different sheet called New_Order in column N, O, P.  i want to sum these values and auto fill entire column in worksheet Registration. the complete code looks like this:

```<code> Sub Registrereren()

Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False

On Error Resume Next

Dim oWkSht As Worksheet
Dim LastColumn As Long
Dim c As Date
Dim myCell As Range
Dim LastRow As Long

Sheets("Registration").Activate

Set oWkSht = ThisWorkbook.Sheets("Registration")
LastColumn = oWkSht.Range("A" & Columns.Count).End(xlToRight).Column
LastRow = oWkSht.Range("C" & Rows.Count).End(xlUp).Row

c = Date

Set myCell = oWkSht.Range("1:1").Find(What:=c, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchOrder:=xlByColumns)

If Not myCell Is Nothing Then
    myCell.Offset(1, 0).Select

    ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"
    'ActiveCell.Formula = Sheets("New_Order").Range(n & LastRow) + Sheets("New_Order").Range(O & LastRow) + Sheets("New_Order").Range(p & LastRow)
    myCell.Offset(1, 0).Select
    Range(myCell.Offset(1), Cells(LastRow, myCell.Column)).Select
    Selection.FillDown

End If

Sheets("Main").Activate

Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub
</code>```

答:
Assuming the formula you want to enter is:

= 'New_Order'!NR + 'New_Order'!OR + 'New_Order'!PR

where R is the same row of the cell holding the formula, then use this FormulaR1C1:

= 'New_Order'!RC14 + 'New_Order'!RC15 + 'New_Order'!RC16

Replace this line:

ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"

with this line:

ActiveCell.FormulaR1C1 = "=New_Order'!RC14 + 'New_Order'!RC15 + 'New_Order'!RC16"

Title: Adjust ActiveCell.FormulaR1C1

Body:
Hi I have a question I have code that i made with macro recorder:

ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"

how can I adjust this code so it would be somthing like thi:

'ActiveCell.Formula = Sheets("New_Order").Range(n & LastRow) + Sheets("New_Order").Range(O & LastRow) + Sheets("New_Order").Range(p & LastRow)

I have values in a different sheet called New_Order in column N, O, P.  i want to sum these values and auto fill entire column in worksheet Registration. the complete code looks like this:

 Sub Registrereren()

Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False

On Error Resume Next

Dim oWkSht As Worksheet
Dim LastColumn As Long
Dim c As Date
Dim myCell As Range
Dim LastRow As Long

Sheets("Registration").Activate

Set oWkSht = ThisWorkbook.Sheets("Registration")
LastColumn = oWkSht.Range("A" & Columns.Count).End(xlToRight).Column
LastRow = oWkSht.Range("C" & Rows.Count).End(xlUp).Row

c = Date

Set myCell = oWkSht.Range("1:1").Find(What:=c, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchOrder:=xlByColumns)

If Not myCell Is Nothing Then
    myCell.Offset(1, 0).Select

    ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"
    'ActiveCell.Formula = Sheets("New_Order").Range(n & LastRow) + Sheets("New_Order").Range(O & LastRow) + Sheets("New_Order").Range(p & LastRow)
    myCell.Offset(1, 0).Select
    Range(myCell.Offset(1), Cells(LastRow, myCell.Column)).Select
    Selection.FillDown

End If

Sheets("Main").Activate

Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub


问:
how to make a windows phone app LongListSelecter with Image and strings
i made a simple long list selector app without jump header or header template.
i made it after a long journey in to the google and stack overflow. i was satisfied with it. the app contains only text blocks to show names- like first name last name phone number but i need to add photos also what would be the code how to show pictures along with names. i search a lot couldn't get a proper solution here is my code:</p>

```<code>namespace listparee6
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
            List<SpeedDial> speeddial = new List<SpeedDial>();
            speeddial.Add(new SpeedDial ( "deepu", "43" ));
            speeddial.Add(new SpeedDial ( "anoop","32" ));
            speeddial.Add(new SpeedDial ( "abhilash","76"  ));
            SpeedDialLLS.ItemsSource = speeddial;
        }

        public class SpeedDial
        {

            public string Name { get; set;}
            public String Phone { get; set; }
            public SpeedDial(string peru, string num)
            {this.Phone=num ;
            this.Name = peru;
            }
           }
    }
}
</code>```

答:
I found a better way to do that.

Project needs 3 components mainly.

xml file

xml.cs file

class file

Implications are mainly made in these file.

In XML file arrange all control
drag and drop longlistselector control

```<code><phone:LongListSelector x:Name="LLs" HorizontalAlignment="Left" Height="566" VerticalAlignment="Top" Width="401" Margin="42,144,0,0">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Image Source="{Binding Photo}" Height="100" Width="100" HorizontalAlignment="Left"/>
                <TextBlock Text="{Binding Names}" HorizontalAlignment="Right"/>
            </StackPanel>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</code>```

xml.cs

```<code>public partial class MainPage : PhoneApplicationPage
{
    ObservableCollection<SpeedDial> speedDialList = new ObservableCollection<SpeedDial>();

    // Constructor
    public MainPage()
    {

        InitializeComponent();
        speedDialList = new ObservableCollection <SpeedDial>();
        speedDialList.Add(new SpeedDial() { Names = "deepu", Photo =  new Uri("Image/2.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jilu", Photo =  new Uri("Image/3.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "tinu", Photo =  new Uri("Image/4.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jhd", Photo = new Uri("Image/7.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jose", Photo = new Uri("image/1.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "hgscf", Photo =  new Uri("image/2.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "hjsg", Photo =  new Uri("Image/5.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jhvdj", Photo =  new Uri("Image/6.jpg" ,UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jhd", Photo =  new Uri("Image/7.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jkgh", Photo =  new Uri("Image/4.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "kigh", Photo =  new Uri("Image/3.jpg",UriKind.Relative) });
        LLs.ItemsSource = speedDialList;
    }
}
}}
</code>```

class file

```<code>namespace yourprojuctname
{
class SpeedDial
    {
       public string name;
        public string Names
        {
            get { return name; }
            set { name = value; }
        }
        private Uri photo;
        public Uri Icon
        {
            get { return photo; }
            set { photo = value; }
        }
    }
}
</code>```

Body:
i made a simple long list selector app without jump header or header template.
i made it after a long journey in to the google and stack overflow. i was satisfied with it. the app contains only text blocks to show names- like first name last name phone number but i need to add photos also what would be the code how to show pictures along with names. i search a lot couldn't get a proper solution here is my code:

namespace listparee6
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
            List<SpeedDial> speeddial = new List<SpeedDial>();
            speeddial.Add(new SpeedDial ( "deepu", "43" ));
            speeddial.Add(new SpeedDial ( "anoop","32" ));
            speeddial.Add(new SpeedDial ( "abhilash","76"  ));
            SpeedDialLLS.ItemsSource = speeddial;
        }

        public class SpeedDial
        {

            public string Name { get; set;}
            public String Phone { get; set; }
            public SpeedDial(string peru, string num)
            {this.Phone=num ;
            this.Name = peru;
            }
           }
    }
}

Body:
I found a better way to do that.

Project needs 3 components mainly.

xml file

xml.cs file

class file

Implications are mainly made in these file.

In XML file arrange all control
drag and drop longlistselector control

<phone:LongListSelector x:Name="LLs" HorizontalAlignment="Left" Height="566" VerticalAlignment="Top" Width="401" Margin="42,144,0,0">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Image Source="{Binding Photo}" Height="100" Width="100" HorizontalAlignment="Left"/>
                <TextBlock Text="{Binding Names}" HorizontalAlignment="Right"/>
            </StackPanel>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

xml.cs

public partial class MainPage : PhoneApplicationPage
{
    ObservableCollection<SpeedDial> speedDialList = new ObservableCollection<SpeedDial>();

    // Constructor
    public MainPage()
    {

        InitializeComponent();
        speedDialList = new ObservableCollection <SpeedDial>();
        speedDialList.Add(new SpeedDial() { Names = "deepu", Photo =  new Uri("Image/2.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jilu", Photo =  new Uri("Image/3.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "tinu", Photo =  new Uri("Image/4.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jhd", Photo = new Uri("Image/7.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jose", Photo = new Uri("image/1.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "hgscf", Photo =  new Uri("image/2.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "hjsg", Photo =  new Uri("Image/5.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jhvdj", Photo =  new Uri("Image/6.jpg" ,UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jhd", Photo =  new Uri("Image/7.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "jkgh", Photo =  new Uri("Image/4.jpg",UriKind.Relative) });
        speedDialList.Add(new SpeedDial() { Names = "kigh", Photo =  new Uri("Image/3.jpg",UriKind.Relative) });
        LLs.ItemsSource = speedDialList;
    }
}
}}

class file

namespace yourprojuctname
{
class SpeedDial
    {
       public string name;
        public string Names
        {
            get { return name; }
            set { name = value; }
        }
        private Uri photo;
        public Uri Icon
        {
            get { return photo; }
            set { photo = value; }
        }
    }
}


问:
Images auto resize with screen height, no scrollbar - CSS
Two days have been passed with it. But I didn't found any solution yet. Conditions is-

1. No scrollbar (vertical or horizontal),

2. Screen height is unknown, so all content (images and text) should be auto-resize with screen height,

My code is here-

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML Quickstart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico">
    <!-- Bootstrap fremwork main css -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <style>
        #padding{
            padding: 15px;
        }
        img{
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="myDiv">
        <div class="container">
            <div class="row">
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
            </div>

            <div class="row">
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
                </div>
            </div>

            <div class="row">
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
            </div>

            <div class="row">
                <div class="col-md-12"><h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis dignissimosus.</h2></div>
            </div>

        </div>  <!-- end container -->
    </div> <!-- end myDiv -->

</body>
</html>
</code>```

I've tried with this link and it.

Since content (not many contents) is large than screen height, so is it possible to adapt screen height?

Please write a comment if you've any solution, suggestion or anything.

Thanks.

答:
If you want your webpage fully responsive, you should follow the Grid System Of Bootstrap Framework rules.
Here are some Grid Options you could use.

I have also provided you the source code & demo how your case should be done. You should learn and take advantage more from it. Hope this answer yours. Feel free to ask me bro.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis dignissimosus.

```

Body:
Two days have been passed with it. But I didn't found any solution yet. Conditions is-

1. No scrollbar (vertical or horizontal),

2. Screen height is unknown, so all content (images and text) should be auto-resize with screen height,

My code is here-

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>HTML Quickstart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis dignissimosus.

I've tried with this link and it.

Since content (not many contents) is large than screen height, so is it possible to adapt screen height?

Please write a comment if you've any solution, suggestion or anything.

Thanks.

Body:
If you want your webpage fully responsive, you should follow the Grid System Of Bootstrap Framework rules.
Here are some Grid Options you could use.

I have also provided you the source code & demo how your case should be done. You should learn and take advantage more from it. Hope this answer yours. Feel free to ask me bro.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
    .row {
      margin-bottom: 0.3em;
    }

    .picture {
      padding: 0.3em;
    }

    img {
      width: 100%;
    }
  </style>
</head>

<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
      </div>
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
      </div>
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
      </div>
    </div>

    <div class="row">
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
      </div>
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
      </div>
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
      </div>
    </div>

    <div class="row">
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
      </div>
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
      </div>
      <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 picture">
        <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
      </div>
    </div>

    <div class="row">
      <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
        <p class="text-center">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis dignissimosus.</p>
      </div>
    </div>
  </div>
  <!-- end container-fluid -->
  <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html>


问:
Tensorflow variables' name changed after function calling
I am trying to write my own batch normalization codes. Therefore, I test the codes below. In order to track the online average mean and variance, I pass them as parameters into the getsta() function. However, I find that the names of "avg_mean" and "avg_variance" changed. Although I could manually force change their names later, it seems Tensorflow treat every name as a separate variable.

```<code>def getsta(x,avg_mean,avg_variance):
  print('getsta start...')

  decay=0.9

  mean = tf.get_variable(
          'mean', [1], tf.float32,
          initializer=tf.constant_initializer(0.0, tf.float32))
  variance = tf.get_variable(
          'howvariance', [1], tf.float32,
          initializer=tf.constant_initializer(1.0, tf.float32))
  '''
  if (avg_mean == 0.0):
      avg_mean = tf.get_variable(
              'avg_mean', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
  if (avg_variance == 0.0):
      avg_variance = tf.get_variable(
              'avg_variance', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
  '''
  mean, variance = tf.nn.moments(x, [0], name='moments')

  avg_mean -= (1.0 - decay) * (avg_mean - mean)
  avg_variance -= (1.0 - decay) * (avg_variance - variance)

  return x, mean, variance, avg_mean, avg_variance

def train():
  x1 = tf.constant([1,2,3,4], tf.float32)
  x2 = tf.constant([5,6,7,8], tf.float32)
  x3 = tf.constant([1,3,5,7], tf.float32)
  x4 = tf.constant([4,8,12,16], tf.float32)

  with tf.variable_scope("AAA") as scopeA:
    avg_mean1 = tf.get_variable(
              'test1', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance1 = tf.get_variable(
              'test2', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    print([avg_mean1.name, avg_variance1.name])
    y1, mean1, variance1, avg_mean1, avg_variance1 = getsta(x1,avg_mean1,avg_variance1)
    print([avg_mean1.name, avg_variance1.name])
    scopeA.reuse_variables()
    print([avg_mean1.name, avg_variance1.name])
    y1, mean1, variance1, avg_mean1, avg_variance1 = getsta(x2,avg_mean1,avg_variance1)
    print([avg_mean1.name, avg_variance1.name])
    avg_mean1 = tf.identity(avg_mean1, name='avg_mean')
    avg_variance1 = tf.identity(avg_variance1, name='avg_variance')
    print([avg_mean1.name, avg_variance1.name])

  with tf.variable_scope("BBB") as scopeB:
    avg_mean2 = tf.get_variable(
              'test1', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance2 = tf.get_variable(
              'test2', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    print([avg_mean2.name, avg_variance2.name])
    y2, mean2, variance2, avg_mean2, avg_variance2 = getsta(x3, avg_mean2, avg_variance2)
    print([avg_mean2.name, avg_variance2.name])
    scopeB.reuse_variables()
    print([avg_mean2.name, avg_variance2.name])
    y2, mean2, variance2, avg_mean2, avg_variance2 = getsta(x4, avg_mean2, avg_variance2)
    print([avg_mean2.name, avg_variance2.name])
    avg_mean2 = tf.identity(avg_mean2, name='avg_mean')
    avg_variance2 = tf.identity(avg_variance2, name='avg_variance')
    print([avg_mean2.name, avg_variance2.name])

  saver = tf.train.Saver()
  sess = tf.InteractiveSession()
  sess.run(tf.global_variables_initializer())
  print(sess.run([y1, mean1, variance1, avg_mean1, avg_variance1]))
  print(sess.run([y2, mean2, variance2, avg_mean2, avg_variance2]))

  allVars = tf.global_variables()
  values = sess.run(allVars)
  for var, val in zip(allVars, values):
    print(var.name, val)

  saver.save(sess, "/tmp/test_EMA/var_save.ckpt")
</code>```

After running the above train() function, I got output as

```<code>['AAA/test1:0', 'AAA/test2:0']
getsta start...
['AAA/sub_1:0', 'AAA/sub_3:0']
['AAA/sub_1:0', 'AAA/sub_3:0']
getsta start...
['AAA/sub_5:0', 'AAA/sub_7:0']
['AAA/avg_mean:0', 'AAA/avg_variance:0']
['BBB/test1:0', 'BBB/test2:0']
getsta start...
['BBB/sub_1:0', 'BBB/sub_3:0']
['BBB/sub_1:0', 'BBB/sub_3:0']
getsta start...
['BBB/sub_5:0', 'BBB/sub_7:0']
['BBB/avg_mean:0', 'BBB/avg_variance:0']
[array([ 5.,  6.,  7.,  8.], dtype=float32), 6.5, 1.25, array([ 0.875], dtype=float32), array([ 0.23750001], dtype=float32)]
[array([  4.,   8.,  12.,  16.], dtype=float32), 10.0, 20.0, array([ 1.36000001], dtype=float32), array([ 2.45000005], dtype=float32)]
AAA/test1:0 [ 0.]
AAA/test2:0 [ 0.]
AAA/mean:0 [ 0.]
AAA/howvariance:0 [ 1.]
BBB/test1:0 [ 0.]
BBB/test2:0 [ 0.]
BBB/mean:0 [ 0.]
BBB/howvariance:0 [ 1.]
</code>```

I have several questions:

Is there any way to record the "avg_mean" without changing its name? I want to load the final updated values when loading the model.

Is it possible to define "avg_mean" inside the getsta() function, while still keeping it like a static variable, i.e., its initial value is from the last time's calling but not always starting from 0.

When I print out all variables, why the names and values both seem not correct as the last eight rows in the output? I expect the output is

```<code>AAA/avg_mean:0 [0.875]
AAA/avg_variance:0 [0.23750001]
BBB/avg_mean:0 [1.36000001]
BBB/avg_variance:0 [2.45000005]
</code>```

Thank you for your help in advance!

--------------------Update--------------------

I revised my codes as below

```<code>def train():
  x1 = tf.constant([1,2,3,4], tf.float32)
  x2 = tf.constant([5,6,7,8], tf.float32)
  x3 = tf.constant([1,3,5,7], tf.float32)
  x4 = tf.constant([4,8,12,16], tf.float32)

  with tf.variable_scope("AAA") as scopeA:
    avg_mean1 = tf.get_variable(
              'avg_mean', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance1 = tf.get_variable(
              'avg_variance', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    y1, mean1, variance1 = getsta(x1,avg_mean1,avg_variance1)
    scopeA.reuse_variables()
    y1, mean1, variance1 = getsta(x2,avg_mean1,avg_variance1)
    print([avg_mean1.name, avg_variance1.name])

  with tf.variable_scope("BBB") as scopeB:
    avg_mean2 = tf.get_variable(
              'avg_mean', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance2 = tf.get_variable(
              'avg_variance', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    y2, mean2, variance2 = getsta(x3, avg_mean2, avg_variance2)
    scopeB.reuse_variables()
    y2, mean2, variance2 = getsta(x4, avg_mean2, avg_variance2)
    print([avg_mean2.name, avg_variance2.name])

  saver = tf.train.Saver()
  sess = tf.InteractiveSession()
  sess.run(tf.global_variables_initializer())
  print(sess.run([y1, mean1, variance1, avg_mean1, avg_variance1]))
  print(sess.run([y2, mean2, variance2, avg_mean2, avg_variance2]))

  allVars = tf.global_variables()
  values = sess.run(allVars)
  for var, val in zip(allVars, values):
    print(var.name, val)

  saver.save(sess, "/tmp/test_EMA/var_save.ckpt")
</code>```

Now the variables' names are fixed. However, the outputs (variables' values) seem incorrect. The outputs are

```<code>[array([ 5.,  6.,  7.,  8.], dtype=float32), 6.5, 1.25, array([ 0.], dtype=float32), array([ 0.], dtype=float32)]
[array([  4.,   8.,  12.,  16.], dtype=float32), 10.0, 20.0, array([ 0.], dtype=float32), array([ 0.], dtype=float32)]
AAA/avg_mean:0 [ 0.]
AAA/avg_variance:0 [ 0.]
AAA/mean:0 [ 0.]
AAA/variance:0 [ 1.]
BBB/avg_mean:0 [ 0.]
BBB/avg_variance:0 [ 0.]
BBB/mean:0 [ 0.]
</code>```

How should I modify my codes to get the correct results? Thank you.

答:
Here are the problems in your code that needs to be fixed:

1- At the following line you are replacing avg_variance1 with an operation returned by getsta. You must not do that. When you have created the variable avg_variance1 and pass it to getstathe variable will be updated everywhere in the computation graph and TensorFlow will take care of that, you don't need to explicitly do that. As long as you are referring to a variable by its name you are fine. TensorFlow variables are not like regular Python variables.

```<code>y1, mean1, variance1, avg_mean1, avg_variance1 = getsta(x1,avg_mean1,avg_variance1)
</code>```

(you need to fix this for avg_mean1, avg_mean2, etc)

2- avg_mean2, avg_variance2, avg_mean2, and avg_variance2 are Tensor and not variable. So they are not in the list of variables you are printing out.

Body:
I am trying to write my own batch normalization codes. Therefore, I test the codes below. In order to track the online average mean and variance, I pass them as parameters into the getsta() function. However, I find that the names of "avg_mean" and "avg_variance" changed. Although I could manually force change their names later, it seems Tensorflow treat every name as a separate variable.

def getsta(x,avg_mean,avg_variance):
  print('getsta start...')

  decay=0.9

  mean = tf.get_variable(
          'mean', [1], tf.float32,
          initializer=tf.constant_initializer(0.0, tf.float32))
  variance = tf.get_variable(
          'howvariance', [1], tf.float32,
          initializer=tf.constant_initializer(1.0, tf.float32))
  '''
  if (avg_mean == 0.0):
      avg_mean = tf.get_variable(
              'avg_mean', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
  if (avg_variance == 0.0):
      avg_variance = tf.get_variable(
              'avg_variance', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
  '''
  mean, variance = tf.nn.moments(x, [0], name='moments')

  avg_mean -= (1.0 - decay) * (avg_mean - mean)
  avg_variance -= (1.0 - decay) * (avg_variance - variance)

  return x, mean, variance, avg_mean, avg_variance

def train():
  x1 = tf.constant([1,2,3,4], tf.float32)
  x2 = tf.constant([5,6,7,8], tf.float32)
  x3 = tf.constant([1,3,5,7], tf.float32)
  x4 = tf.constant([4,8,12,16], tf.float32)

  with tf.variable_scope("AAA") as scopeA:
    avg_mean1 = tf.get_variable(
              'test1', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance1 = tf.get_variable(
              'test2', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    print([avg_mean1.name, avg_variance1.name])
    y1, mean1, variance1, avg_mean1, avg_variance1 = getsta(x1,avg_mean1,avg_variance1)
    print([avg_mean1.name, avg_variance1.name])
    scopeA.reuse_variables()
    print([avg_mean1.name, avg_variance1.name])
    y1, mean1, variance1, avg_mean1, avg_variance1 = getsta(x2,avg_mean1,avg_variance1)
    print([avg_mean1.name, avg_variance1.name])
    avg_mean1 = tf.identity(avg_mean1, name='avg_mean')
    avg_variance1 = tf.identity(avg_variance1, name='avg_variance')
    print([avg_mean1.name, avg_variance1.name])

  with tf.variable_scope("BBB") as scopeB:
    avg_mean2 = tf.get_variable(
              'test1', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance2 = tf.get_variable(
              'test2', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    print([avg_mean2.name, avg_variance2.name])
    y2, mean2, variance2, avg_mean2, avg_variance2 = getsta(x3, avg_mean2, avg_variance2)
    print([avg_mean2.name, avg_variance2.name])
    scopeB.reuse_variables()
    print([avg_mean2.name, avg_variance2.name])
    y2, mean2, variance2, avg_mean2, avg_variance2 = getsta(x4, avg_mean2, avg_variance2)
    print([avg_mean2.name, avg_variance2.name])
    avg_mean2 = tf.identity(avg_mean2, name='avg_mean')
    avg_variance2 = tf.identity(avg_variance2, name='avg_variance')
    print([avg_mean2.name, avg_variance2.name])

  saver = tf.train.Saver()
  sess = tf.InteractiveSession()
  sess.run(tf.global_variables_initializer())
  print(sess.run([y1, mean1, variance1, avg_mean1, avg_variance1]))
  print(sess.run([y2, mean2, variance2, avg_mean2, avg_variance2]))

  allVars = tf.global_variables()
  values = sess.run(allVars)
  for var, val in zip(allVars, values):
    print(var.name, val)

  saver.save(sess, "/tmp/test_EMA/var_save.ckpt")

After running the above train() function, I got output as

['AAA/test1:0', 'AAA/test2:0']
getsta start...
['AAA/sub_1:0', 'AAA/sub_3:0']
['AAA/sub_1:0', 'AAA/sub_3:0']
getsta start...
['AAA/sub_5:0', 'AAA/sub_7:0']
['AAA/avg_mean:0', 'AAA/avg_variance:0']
['BBB/test1:0', 'BBB/test2:0']
getsta start...
['BBB/sub_1:0', 'BBB/sub_3:0']
['BBB/sub_1:0', 'BBB/sub_3:0']
getsta start...
['BBB/sub_5:0', 'BBB/sub_7:0']
['BBB/avg_mean:0', 'BBB/avg_variance:0']
[array([ 5.,  6.,  7.,  8.], dtype=float32), 6.5, 1.25, array([ 0.875], dtype=float32), array([ 0.23750001], dtype=float32)]
[array([  4.,   8.,  12.,  16.], dtype=float32), 10.0, 20.0, array([ 1.36000001], dtype=float32), array([ 2.45000005], dtype=float32)]
AAA/test1:0 [ 0.]
AAA/test2:0 [ 0.]
AAA/mean:0 [ 0.]
AAA/howvariance:0 [ 1.]
BBB/test1:0 [ 0.]
BBB/test2:0 [ 0.]
BBB/mean:0 [ 0.]
BBB/howvariance:0 [ 1.]

I have several questions:

Is there any way to record the "avg_mean" without changing its name? I want to load the final updated values when loading the model.

Is it possible to define "avg_mean" inside the getsta() function, while still keeping it like a static variable, i.e., its initial value is from the last time's calling but not always starting from 0.

When I print out all variables, why the names and values both seem not correct as the last eight rows in the output? I expect the output is

AAA/avg_mean:0 [0.875]
AAA/avg_variance:0 [0.23750001]
BBB/avg_mean:0 [1.36000001]
BBB/avg_variance:0 [2.45000005]

Thank you for your help in advance!

--------------------Update--------------------

I revised my codes as below

def train():
  x1 = tf.constant([1,2,3,4], tf.float32)
  x2 = tf.constant([5,6,7,8], tf.float32)
  x3 = tf.constant([1,3,5,7], tf.float32)
  x4 = tf.constant([4,8,12,16], tf.float32)

  with tf.variable_scope("AAA") as scopeA:
    avg_mean1 = tf.get_variable(
              'avg_mean', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance1 = tf.get_variable(
              'avg_variance', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    y1, mean1, variance1 = getsta(x1,avg_mean1,avg_variance1)
    scopeA.reuse_variables()
    y1, mean1, variance1 = getsta(x2,avg_mean1,avg_variance1)
    print([avg_mean1.name, avg_variance1.name])

  with tf.variable_scope("BBB") as scopeB:
    avg_mean2 = tf.get_variable(
              'avg_mean', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance2 = tf.get_variable(
              'avg_variance', [1], tf.float32,
              initializer=tf.constant_initializer(0.0, tf.float32))
    y2, mean2, variance2 = getsta(x3, avg_mean2, avg_variance2)
    scopeB.reuse_variables()
    y2, mean2, variance2 = getsta(x4, avg_mean2, avg_variance2)
    print([avg_mean2.name, avg_variance2.name])

  saver = tf.train.Saver()
  sess = tf.InteractiveSession()
  sess.run(tf.global_variables_initializer())
  print(sess.run([y1, mean1, variance1, avg_mean1, avg_variance1]))
  print(sess.run([y2, mean2, variance2, avg_mean2, avg_variance2]))

  allVars = tf.global_variables()
  values = sess.run(allVars)
  for var, val in zip(allVars, values):
    print(var.name, val)

  saver.save(sess, "/tmp/test_EMA/var_save.ckpt")

Now the variables' names are fixed. However, the outputs (variables' values) seem incorrect. The outputs are

[array([ 5.,  6.,  7.,  8.], dtype=float32), 6.5, 1.25, array([ 0.], dtype=float32), array([ 0.], dtype=float32)]
[array([  4.,   8.,  12.,  16.], dtype=float32), 10.0, 20.0, array([ 0.], dtype=float32), array([ 0.], dtype=float32)]
AAA/avg_mean:0 [ 0.]
AAA/avg_variance:0 [ 0.]
AAA/mean:0 [ 0.]
AAA/variance:0 [ 1.]
BBB/avg_mean:0 [ 0.]
BBB/avg_variance:0 [ 0.]
BBB/mean:0 [ 0.]

How should I modify my codes to get the correct results? Thank you.

Body:
Here are the problems in your code that needs to be fixed:

1- At the following line you are replacing avg_variance1 with an operation returned by getsta. You must not do that. When you have created the variable avg_variance1 and pass it to getstathe variable will be updated everywhere in the computation graph and TensorFlow will take care of that, you don't need to explicitly do that. As long as you are referring to a variable by its name you are fine. TensorFlow variables are not like regular Python variables.

y1, mean1, variance1, avg_mean1, avg_variance1 = getsta(x1,avg_mean1,avg_variance1)

(you need to fix this for avg_mean1, avg_mean2, etc)

2- avg_mean2, avg_variance2, avg_mean2, and avg_variance2 are Tensor and not variable. So they are not in the list of variables you are printing out.


问:
how to use SQL wildcard % with Queryset extra>select?
I'm using the extra() modifier in a view.

(See http://docs.djangoproject.com/en/1.1/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none )

Here's the the code:

```<code>def viewname(request)
    ...
    exact_matchstrings=[]
    exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + "')")
    exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + '\%' +  "')")

    extraquerystring = " + ".join(exact_matchstrings)

    return_queryset = return_queryset.extra(
        select = { 'match_weight': extraquerystring },
        )
</code>```

The two append statements above are almost completely alike except that the second adds a % SQL wildcard character.  This is causing an error; the statement without the % causes no problems.  What's going on with the %?  I'm surprised that django thinks this character is not defined, since it's in SQL specification.  For example, the following SQL statement executes just fine:

```<code>select (first_name like "Car") + (first_name like "Car%") from accountprofile;
</code>```

But trying to run it via the extra() modifier in my view code and evaluating the resulting queryset gives me an error.  I think "%" needs to be escaped, so I tried that already.  Any ideas?

答:
It looks like you are missing some quotes from the 2nd string.  And I'm not sure that you need to escape the percent (%) unless this is required by django.</p>

```<code>_matchstrings.append("(accountprofile.first_name LIKE '" + term + "%" +  "')")
</code>```

Body:
I'm using the extra() modifier in a view.

(See http://docs.djangoproject.com/en/1.1/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none )

Here's the the code:

def viewname(request)
    ...
    exact_matchstrings=[]
    exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + "')")
    exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + '\%' +  "')")

    extraquerystring = " + ".join(exact_matchstrings)

    return_queryset = return_queryset.extra(
        select = { 'match_weight': extraquerystring },
        )

The two append statements above are almost completely alike except that the second adds a % SQL wildcard character.  This is causing an error; the statement without the % causes no problems.  What's going on with the %?  I'm surprised that django thinks this character is not defined, since it's in SQL specification.  For example, the following SQL statement executes just fine:

select (first_name like "Car") + (first_name like "Car%") from accountprofile;

But trying to run it via the extra() modifier in my view code and evaluating the resulting queryset gives me an error.  I think "%" needs to be escaped, so I tried that already.  Any ideas?

Body:
It looks like you are missing some quotes from the 2nd string.  And I'm not sure that you need to escape the percent (%) unless this is required by django.

_matchstrings.append("(accountprofile.first_name LIKE '" + term + "%" +  "')")


问:
Comparing enumerated types in java
```<code> public class seasons{

        public enum compare{

                 summer(0), spring(1), winter(3), fall(4);

               (assume the constructor is already coded)
       }
}
</code>```

How would I create a method that takes in 2 seasons as arguements and compares the values of the seasons?

答:
See comments in code </p>

```<code>public enum Seasons{

    summer(0), spring(1), winter(3), fall(4);

    int order;
    Seasons(int order){
        this.order = order;
    }

    //a method that fits the signature of Comparator<T>
    //https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
    public static int compare(Seasons s1, Seasons s2) {

        //Box int to an Integer object, and delegate comparison to its
        //comareTo
        return new Integer(s1.order).compareTo(s2.order);

        //or as  DarkRift 3 proposed
        //return Integer.compare(s1.order, s2.order);
    }

    public static void main(String[] args) {

        //if you just want to check for equality you can do it simply by
        //using the == operator
        System.out.println(summer == summer); //returns true;
        System.out.println(summer == winter); //returns false

        //if you want to compare based on the int property, use a comperator
        System.out.println(compare(summer, summer));//return 0 meaning equal
        System.out.println(compare(summer, winter));//return -1 meaning smaller
        System.out.println(compare(winter,summer));//return 1 meaning bigger
    }
}
</code>```

Title: Comparing enumerated types in java

Body:
 public class seasons{

        public enum compare{

                 summer(0), spring(1), winter(3), fall(4);

               (assume the constructor is already coded)
       }
}

How would I create a method that takes in 2 seasons as arguements and compares the values of the seasons?

Body:
See comments in code

public enum Seasons{

    summer(0), spring(1), winter(3), fall(4);

    int order;
    Seasons(int order){
        this.order = order;
    }

    //a method that fits the signature of Comparator<T>
    //https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
    public static int compare(Seasons s1, Seasons s2) {

        //Box int to an Integer object, and delegate comparison to its
        //comareTo
        return new Integer(s1.order).compareTo(s2.order);

        //or as  DarkRift 3 proposed
        //return Integer.compare(s1.order, s2.order);
    }

    public static void main(String[] args) {

        //if you just want to check for equality you can do it simply by
        //using the == operator
        System.out.println(summer == summer); //returns true;
        System.out.println(summer == winter); //returns false

        //if you want to compare based on the int property, use a comperator
        System.out.println(compare(summer, summer));//return 0 meaning equal
        System.out.println(compare(summer, winter));//return -1 meaning smaller
        System.out.println(compare(winter,summer));//return 1 meaning bigger
    }
}


问:
AngularFire2 - Remove an item via Observable - last item doesn't remove from UI
I was wondering why when I run this function, the item gets removed from my Firebase database, but inside my Angular 2 app, when it gets to the last entry, it removes it from the database, but it doesn't remove it from the list in my *ngFor loop. However, if I refresh the page, the list is updated and the entry is no longer there. Anyone know why this could be happening?

Here is the function in my provider to remove the attachment:

```<code>removeAttachment(attachment, projectId, requestId) {
    return this._af.database.list(`/check_requests/${projectId}/${requestId}/attachments/${attachment.id}`).remove();
  }
</code>```

Here are the associated arrays in my component:

```<code>public attachments: any = [];
public attachmentKeys:any = [];
</code>```

Here is an async function that populates the attachments and attachmentKeys arrays any time the database updates:

```<code>populateFormWithRequest() {
    this.formPopulationObs = this._checkRequests.getRequest(requestId, projectId).subscribe(requestData => {

      // Get the attachments
      if(requestData['attachments']) {
        this.attachments = requestData['attachments'];
        this.attachmentKeys = Object.keys(requestData['attachments']);
      }
   });
}
</code>```

Here is my *ngFor loop in my html template:

```<code><ul class="attachment-list" *ngIf="attachments && (attachments | mapToIterable).length > 0">
          <li *ngFor="let key of attachmentKeys">
            <a target="_blank" href="{{attachments[key].url}}"><i class="fa fa-paperclip"></i>{{attachments[key].name}}</a>
            <button (click)="removeAttachment(attachments[key], key)"><i class="fa fa-times"></i></button>
          </li>
        </ul>
</code>```

答:
It's most likely this line:

if (requestData['attachments']) {
```

<p>When you remove the last attachment, the <code>attachments</code> property will not exist in the emitted request object. If a child in the Firebase database has no children, it too is removed.</p>

<p>So <code>requestData['attachments']</code> will be falsy and the <code>attachments</code> and <code>attachmentKeys</code> properties will remain unchanged.</p>

<p>The solution would be something like this:</p>

<pre class="lang-ts prettyprint-override"><code>if (requestData['attachments']) {
  this.attachments = requestData['attachments'];
  this.attachmentKeys = Object.keys(requestData['attachments']);
} else {
  this.attachments = {};
  this.attachmentKeys = [];
}
</code>```

Body:
I was wondering why when I run this function, the item gets removed from my Firebase database, but inside my Angular 2 app, when it gets to the last entry, it removes it from the database, but it doesn't remove it from the list in my *ngFor loop. However, if I refresh the page, the list is updated and the entry is no longer there. Anyone know why this could be happening?

Here is the function in my provider to remove the attachment:

removeAttachment(attachment, projectId, requestId) {
    return this._af.database.list(`/check_requests/${projectId}/${requestId}/attachments/${attachment.id}`).remove();
  }

Here are the associated arrays in my component:

public attachments: any = [];
public attachmentKeys:any = [];

Here is an async function that populates the attachments and attachmentKeys arrays any time the database updates:

populateFormWithRequest() {
    this.formPopulationObs = this._checkRequests.getRequest(requestId, projectId).subscribe(requestData => {

      // Get the attachments
      if(requestData['attachments']) {
        this.attachments = requestData['attachments'];
        this.attachmentKeys = Object.keys(requestData['attachments']);
      }
   });
}

Here is my *ngFor loop in my html template:

 0">

            {{attachments[key].name}}
            <button (click)="removeAttachment(attachments[key], key)"></button>

Body:
It's most likely this line:

if (requestData['attachments']) {

When you remove the last attachment, the attachments property will not exist in the emitted request object. If a child in the Firebase database has no children, it too is removed.

So requestData['attachments'] will be falsy and the attachments and attachmentKeys properties will remain unchanged.

The solution would be something like this:

if (requestData['attachments']) {
  this.attachments = requestData['attachments'];
  this.attachmentKeys = Object.keys(requestData['attachments']);
} else {
  this.attachments = {};
  this.attachmentKeys = [];
}


问:
why my htaccess rule not works
I created a htaccess rule but it doesnot works.
here is my url

```<code>http://localhost/mat/site/brandlisting/21/page/2
</code>```

here is my htaccess rule for it

```<code>RewriteRule brandlisting/(.*)(.*)/page/(.*) site/brandlisting?id=$1&page=$2 [L]
RewriteRule brandlisting/(.*)(.*)/page site/brandlisting?id=$1&page=$2 [L]

RewriteRule brandlisting/(.*)/ site/brandlisting?id=$1 [L]
RewriteRule brandlisting/(.*) site/brandlisting?id=$1 [L]
RewriteRule site/brandlisting/(.*)/?$ site/brandlisting?id=$1 [L]
</code>```

is there anything wrong?
what mistate is in my htaccess rule.

答:
You are using wildcard greedy pattern regex matching everything in single hit, use below rules I am assuming you are using .htaccess in site folder.</p>

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^brandlisting/([\d]+)/page/([\d]+)$ brandlisting?id=$1&page=$2 [L]
RewriteRule ^brandlisting/([\d]+)/?$ brandlisting?id=$1 [L]
RewriteRule ^site/brandlisting/([\d]+)/?$ brandlisting?id=$1 [L]
</code>```

Title: why my htaccess rule not works

Body:
I created a htaccess rule but it doesnot works.
here is my url

http://localhost/mat/site/brandlisting/21/page/2

here is my htaccess rule for it

RewriteRule brandlisting/(.*)(.*)/page/(.*) site/brandlisting?id=$1&page=$2 [L]
RewriteRule brandlisting/(.*)(.*)/page site/brandlisting?id=$1&page=$2 [L]

RewriteRule brandlisting/(.*)/ site/brandlisting?id=$1 [L]
RewriteRule brandlisting/(.*) site/brandlisting?id=$1 [L]
RewriteRule site/brandlisting/(.*)/?$ site/brandlisting?id=$1 [L]

is there anything wrong?
what mistate is in my htaccess rule.

Body:
You are using wildcard greedy pattern regex matching everything in single hit, use below rules I am assuming you are using .htaccess in site folder.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^brandlisting/([\d]+)/page/([\d]+)$ brandlisting?id=$1&page=$2 [L]
RewriteRule ^brandlisting/([\d]+)/?$ brandlisting?id=$1 [L]
RewriteRule ^site/brandlisting/([\d]+)/?$ brandlisting?id=$1 [L]


问:
FIRRemoteConfig.activateFetched() fails
I've implemented FIRRemoteConfig and added my first value in the firebase console.  However, when I try to activate the fetched values it fails and my remote value  is never available.</p>

```<code>    let remote = FIRRemoteConfig.remoteConfig()
    #if DEBUG
        let expiration: TimeInterval = 0
        remote.configSettings = FIRRemoteConfigSettings(developerModeEnabled: true)
    #else
        let expiration: TimeInterval = 24*60*60
    #endif

    var map = [String:NSObject]()
    let defaults = RemoteSettings.defaults.keys
    for key in defaults.keys {
        map[key.rawValue] = defaults[key] as? NSObject
    }
    remote.setDefaults(map) // Have confirmed that map is valid here

    remote.fetch(withExpirationDuration: expiration, completionHandler: { (status, error) in
        // status always == .success, but remote.activateFetched() always returns false.
        if status == .success && remote.activateFetched() {
            print("applied remote settings")
        } else {
            print("failed to apply remote settings: \(error)")
        }
    })
</code>```

答:
I figured out after a lot of trial and error. The problem is with the expiration value, set the expiration value to 0 seconds to see the immediate results put into effect!

I hope this could save a lot of time for others guys!

Title: FIRRemoteConfig.activateFetched() fails

Body:
I've implemented FIRRemoteConfig and added my first value in the firebase console.  However, when I try to activate the fetched values it fails and my remote value  is never available.

    let remote = FIRRemoteConfig.remoteConfig()
    #if DEBUG
        let expiration: TimeInterval = 0
        remote.configSettings = FIRRemoteConfigSettings(developerModeEnabled: true)
    #else
        let expiration: TimeInterval = 24*60*60
    #endif

    var map = [String:NSObject]()
    let defaults = RemoteSettings.defaults.keys
    for key in defaults.keys {
        map[key.rawValue] = defaults[key] as? NSObject
    }
    remote.setDefaults(map) // Have confirmed that map is valid here

    remote.fetch(withExpirationDuration: expiration, completionHandler: { (status, error) in
        // status always == .success, but remote.activateFetched() always returns false.
        if status == .success && remote.activateFetched() {
            print("applied remote settings")
        } else {
            print("failed to apply remote settings: \(error)")
        }
    })