A business creates value through a combination of strategy, governance, performance and prospects in an external environment. A framework that enables a businesses to bring these elements together – and to communicate the value creation story through the 'connectivity of information' - is called Integrated Thinking & Reporting, in short . At the heart of is an integrated model, which demonstrates how six capitals – financial, manufactured, human, social and relationship, intellectual and natural – represent all the resources organizations utilize to create value (over time).
Today many listed companies label their annual reports as Integrated Reports, some even before the International Integrated Reporting Council (IIRC) launched the official framework (in December 2013). These annual reports however, should actually be more considered as combined reporting instead of , because they combine the financial and the sustainability report into one report. For many of those – and other – companies, how to move forward from "simply" combining information (which can take up months of manual work during the reporting period) to connecting information and truly understanding the value creation process poses a big challenge.
An integrated report conform the framework communicates how the activities and capabilities of an organization transform the six - or less - material capitals into outcomes. It's a forward looking, value focused, and holistic way of corporate reporting and provides different audiences with relevant information, preferably digital available, at any time. This is distinctly different from the "old way" of of combining information in corporate reporting, since that way of reporting is still mostly focused on financial value, backward looking with silos of information and provides companies with paper-based PDF's. Implementing on the other hand, is not a yearly one off event aimed at disclosing information externally. It's a continuous way of reporting with the aim to shift financial management into value management.
One of the reasons why organizations are struggling with embedding is because is a "principle" based framework and doesn't include a pre-defined set of KPI's. An understanding about which capitals are material for your business, how these capitals transform into outcomes (both positive and negative) and how to translate this into value, requires specific skills and is generally not something a reporting department can do itself. It should be on the top priority list of the CFO, because the so-called non-financial capitals – such as natural capital - can turn into financial ones within a day, as we have seen with Volkswagen this week.
Furthermore, there is a need for technology that can align underlying systems and information flows for both internal as external reporting. This week we were invited to the Round Table of the IIRC Tech Initiative were technology firms, the accounting profession and corporates are trying to develop solutions that support the adoption of in order to enhance (or in some cases restore) accountability, stewardship and trust.
Sinzer encourages this initiative and supports the implementation of the framework. We therefore offer everyone who wants to embed in their organization a coupon for a free-of-charge two hours consult in which we explain how to set up your value creation story. Interested?


I found the ending particularly dissatisfying as it failed to resolve anytning. I am not surprised at the many negative reviews this book has had.
When everybody is against them, it is tough being a lifeliner, as Nash Bannon found out. Lifeliners are ordinary people…almost. They can draw energy from another person; they live longer and are smarter.
Reconstructing the Shield of Achilles is a great introductory scholarly work into Homer's epic poems and the wonder of Greek myths.
An interview with Thomas Anderson, Editor in Chief, Literary Titan.
Stefan Vučak has written eight Shadow Gods Saga sci-fi novels and six contemporary political drama books. He started writing science fiction while still in college, but didn't get published until 2001. His Cry of Eagles won the coveted Readers' Favorite silver medal award, and his All the Evils was the prestigious Eric Hoffer contest finalist and Readers' Favorite silver medal winner. Strike for Honor won the gold medal. Stefan leveraged a successful career in the Information Technology industry, which took him to the Middle East working on cellphone systems. He applied his IT discipline to create realistic storylines for his books. Writing has been a road of discovery, helping him broaden his horizons. He also spends time as an editor and book reviewer. Stefan lives in Melbourne, Australia.


text:
Q: How to measure time in postgres In postgres I want to know the time taken to generate plan. I know that \timing gives me the time taken to execute the plan after finding the optimal plan. But I want to find out the time which postgres takes in finding out the optimal plan. Is it possible to determine this time in postgres. If yes, then how?
Also query plan generators at times do not find the optimal plan. Can I force postgres to use the optimal plan for plan generation. If yes, then how can I do so?

A: For the time taken to prepare a plan and the time taken to execute it, you can use explain (which merely finds a plan) vs explain analyze (which actually runs it) with \timing turned on:
test=# explain select * from test where val = 1 order by id limit 10;
                                   QUERY PLAN
--------------------------------------------------------------------------------
 Limit  (cost=0.00..4.35 rows=10 width=8)
   ->  Index Scan using test_pkey on test  (cost=0.00..343.25 rows=789 width=8)
         Filter: (val = 1)
(3 rows)

Time: 0.759 ms
test=# explain analyze select * from test where val = 1 order by id limit 10;
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.00..4.35 rows=10 width=8) (actual time=0.122..0.170 rows=10 loops=1)
   ->  Index Scan using test_pkey on test  (cost=0.00..343.25 rows=789 width=8) (actual time=0.121..0.165 rows=10 loops=1)
         Filter: (val = 1)
         Rows Removed by Filter: 67
 Total runtime: 0.204 ms
(5 rows)

Time: 1.019 ms

Note that there is a tiny overhead in both commands to actually output the plan.

Usually it happens e.g. in DB2 that since finding the optimal plan takes a lot of time..therefore the database engine decides to use a suboptimal plan...i think it must be the case with postgres also.

In Postgres, this only occurs if your query is gory enough that it cannot reasonably do an exhaustive search. When you reach the relevant thresholds (which are high, if your use-cases are typical), the planner uses the genetic query optimizer:
http://www.postgresql.org/docs/current/static/geqo-pg-intro.html

If it is then how can i fiddle with postgres such that it chooses the optimal plan.

In more general use cases, there are many things that you can fiddle, but be very wary of messing around with them (apart, perhaps, from collecting a bit more statistics on a select few columns using ALTER TABLE SET STATISTICS):
http://www.postgresql.org/docs/current/static/runtime-config-query.html

A: If you use \i command in psql client than in sql file add following row
\timing true

redpajama_set_name: RedPajamaStackExchange


text:
Determines whether an annotation is empty or not.

## Subject metadata fields

A single subject can have multiple feedback rules. To group the metadata fields for a single feedback rule together, `N` should be an integer that is identical for each rule, e.g.:

```
#feedback_1_id,,#feedback_2_id...
```

- `#feedback_N_id` (**required**) - ID of the corresponding workflow task rule.
- `#feedback_N_successMessage` (optional) - message to show when the target is correctly annotated. Overrides the default success message set on the workflow task rule.
- `#feedback_N_failureMessage` (optional) - message to show when the target is incorrectly annotated. Overrides the default failure message set on the workflow task rule.

redpajama_set_name: RedPajamaGithub


text:
Victor Lund
Alfred Nobel led an impressive life. He spoke 5 languages fluently by the age of 17. He was incredibly well educated in literature, poetry, chemistry and physics. His father is often cited for directing Nobel as a man. His father was an engineer who pioneered military advancement like naval mines. Shortly after Alfred graduated from college with a degree in chemical engineering, he invented and patented dynamite in 1867. This invention led the young man to develop manufacturing of his product at factories that he owned and managed worldwide. His fortune was made.
I would like to think that Alfred's mother played a significant role in his life. Somewhere, somehow, he became convinced that all of his life's work should be invested to bestow a 5 monetary prizes to the individuals who, in the preceding year, conferred the greatest benefit to mankind. These prizes are awarded for physics, chemistry, medicine, literature, and peace. The Nobel Prize. He gave his entire worth to endow the award in his will. Something that his family contested until 1901.
I imagine that Mr. Nobel led a conflicted life knowing that his invention was used both for good and evil. For every blast that cut through rock to build a road, another blast was used by an army to kill an enemy. It is legend that he believed that the only path to peace are equally armed nations. There is support for his belief. The nuclear arms race has prevented world wars, at least for now.
Alfred Nobel will continue to reward the greatest minds on our planet until monetary gain and peer recognition are no longer considered prizes. By abstraction, I doubt that the Nobel Prize for Literature is any form of incentive. Gabriel Garcia Marquez certainly did not compose his novels with such a prize in mind. Nor did Samuel Beckett, Jean-Paul Sartre, Albert Camus, William Faulkner, Sinclair Lewis, Earnest Hemingway, or them many other great writers whom I have grown to adore. Perhaps calling it a Prize was a mistake. The Nobel Gift for Literature may be more appropriate.
Men do not do achieve great things because they seek prizes or recognition. Men do things because they are driven by their passionate souls to do what they do. If the collective world deems those things great, prizes and recognition come forth.
This year, the Nobel Prize for Medicine awarded to biologist Francis Crick was sold at auction for $2.3 Million. Crick was born in England in 1916. He had something that bound him to Alfred Nobel. During the war, he worked with magnetic and acoustic mines (like Nobel's father). His Price worthy act was discovering how nucleic acids play a role for information transfer in living material (why cells do what they do and the significance of DNA). Crick died in 2004. It seems a little ungentle that the family sold the prize. Perhaps Francis should have learned a thing or two from Alfred Nobel about writing wills.
In 2013, the Nobel Prize confers $1.2 Million to each recipient.
Labels: education healthcare leadership philosophy
Thanks a lot for leaving a comment. My phone number is 805-709-6696 if you have any questions.
Tax Reform and Lies
Election Observations - What Just Happened
Copyright 2011 Victor Lund All Rights Reserved
Social Media in the Entertainment Business
Federal Reserve Governance
Quantitative Easing Is Really A Tax
#lilbeast2
alexandra lund14
Arroyo grande ca9
barbara boxer3
business management15
California Law5
dance6
dellos performing arts10
Detroit lakes1
F-Secure1
federal budget24
flashback virus1
ipad apps2
mandy moore1
marco cruz3
mobile advertising1
National Dance Day1
omni hotels2
philosophy23
plastic bag ban4
pulse on tour2
san luis obispo8
san luis obispo county9
san luis obispo dance4
san luis obispo farmers market1
san luis obispo tribune3
shattuck1
state budget4
styrofoam ban2
taxes21
victor lund3

redpajama_set_name: RedPajamaCommonCrawl


As a result, Orchard Software allows users to include POCT data in analytics projects and population health management initiatives.
Launched in April 2018, the OM SDK facilitates third-party viewability and verification measurement for ads served to mobile app environments without requiring multiple measurement provider SDKs.
In the four years since Gartner identified this discipline, personal analytics has developed in fits and starts through technologies such as Fitbit watches and dieting apps.


This one is for our fashionable men out there - florals is one of the biggest fashion trends of the season and designers such as Dolce and Gabbana,Versace and Fabiani shows you how to rock the trend if you are a guy.
Bold prints with strong florals is popular for men and it is mostly paired with a masculine look such as a floral short with a suit jacket or a floral jacket with suit pants just to keep the balance. It is a fresh new trend and I think men should be daring and try it out!
No comments yet on Florals for Men.


text:
JSC Georgian Oil And Gas Corporation Announces Early Tender Results
JSC Georgian Oil and Gas Corporation
LONDON, April 18, 2016 /PRNewswire/ -- Further to the announcement by JSC Georgian Oil and Gas Corporation (the "Issuer") on 4 April 2016 that it had launched an invitation to each Holder (subject to certain offer and distribution restrictions) to tender any and all outstanding U.S.$250,000,000 6.875% Notes due 2017 (the "Notes") (ISINs: XS0652911420 (Unrestricted Notes) / US37363CAA45 (Restricted Notes)) held by it for purchase by the Issuer for cash (the "Tender Offer"), all as more fully described in the tender offer memorandum dated 4 April 2016 (the "Tender Offer Memorandum"), the Issuer has today announced that, as at the Early Participation Deadline (being 5:00 p.m. (New York time) on 15 April 2016), the aggregate principal amount of Notes validly tendered (and not validly withdrawn) was U.S.$129,437,000.
The Tender Offer is made on the terms and subject to the conditions contained in the Tender Offer Memorandum. Capitalised terms used and not otherwise defined in this announcement have the meaning given to them in the Tender Offer Memorandum.
Holders of Notes that were validly tendered (and not validly withdrawn) at or prior to the Early Participation Date are eligible to receive consideration of U.S.$1,022.50 per U.S.$1,000 in principal amount of Notes (the "Total Consideration") for such Notes, which comprises consideration of U.S.$992.50 per U.S.$1,000 in principal amount of Notes (the "Tender Offer Consideration") plus consideration of U.S.$30.00 per U.S.$1,000 in principal amount of Notes (the "Early Tender Premium"). Holders of Notes that were validly tendered (and not validly withdrawn) after the Early Participation Deadline but at or prior to the Expiration Deadline and accepted for purchase will be eligible to receive only the Tender Offer Consideration for their Notes. The Issuer expects to announce the results of the Tender Offer, including details of the Notes accepted for purchase (subject to satisfaction of the New Financing Condition) promptly following the Expiration Deadline (being 11:59 p.m. (New York time) on 29 April 2016), and the Total Consideration or the Tender Offer Consideration (as the case may be) payable to Holders of validly tendered (and not validly withdrawn) Notes accepted for purchase is expected to be paid, together with Accrued Interest, on or about 4 May 2016 (the "Settlement Date").
The Tender Offer will expire on the Expiration Deadline, unless the offer period is extended or earlier terminated. All Holders may tender Notes until the Expiration Deadline. Any tender of Notes received by D.F. King Ltd. (the "Information and Tender Agent") after the Expiration Deadline will not be accepted.
All documentation relating to the Tender Offer is available via http://sites.dfkingltd.com/gogc.
The Dealer Managers are Barclays (+44(0)20-3134-8515/+1(212)528-7581 (U.S. Collect)/+1(800)438-3242 (U.S. Toll Free), [email protected]) and J.P. Morgan (+44(0)20-7134-2468, [email protected]).
The Information and Tender Agent is DF King Ltd. (+44(0)20-7920-9700/ +1(212)269-5550/ +1(800)622-1569 (U.S. Toll Free)/ +852-3953-7230, [email protected]).
This announcement is for informational purposes only. The Tender Offer is being made only pursuant to the Tender Offer Memorandum and only in such jurisdictions as is permitted under applicable law. None of this announcement, the announcement dated 4 April 2016 or the Tender Offer Memorandum constitutes an offer to purchase or the solicitation of an offer to tender or sell Notes to or from any person located or resident in any jurisdiction where such offer or solicitation is unlawful.
SOURCE JSC Georgian Oil and Gas Corporation


text:
Today the UKC is an international charity that has helped thousands of children around the world to overcome the stress, anxiety and health challenges of serious health conditions. But it started out with the simple idea of giving back, through music.
Jared Bergman (left) and Corey Bergman
In 2013, Corey Bergman, a life-long musician, began volunteering at local hospitals in Miami, Florida as a way of coping with the tragic loss of his son, Jared. As he played guitar for young patients and their families, he says, "I could plainly see that the act of listening to and playing music, and holding an instrument, has a deep positive effect on a child. All the anxiety and fear of the hospital just fades away and this kid becomes a kid again."
Then, two developments quickly brought the future UKC sharply into focus. First, Corey connected with music therapists at Miami Children's Hospital, Joe DiMaggio Children's Hospital and others, and gained exposure to the field of music therapy. Through music therapy, certified professionals help patients use music to achieve clinical goals, which in the case of young children might include lowering anxiety and stress, improving vital signs, and a multitude of other results. Second, the simplicity and small size of the ukulele made it seem like the ideal vehicle for music therapy with even the smallest patients.
In 2014, Corey and his wife Edda incorporated the UKC. Its mission was, and remains, to support music therapy for hospitalized children, by giving children a ukulele to use during their hospital stay, and to keep when they go home. Each year, the UKC delivers thousands of ukuleles, to a growing network of more than 200 hospitals in the U.S. and in North America, Europe and Asia.
Giving back, through music – this is the idea behind UKC, past, present and future.





Press Release (ePRNews.com) - NEW YORK - Mar 13, 2018 - FlippingBook, a company that develops professional software for converting PDFs into interactive online documents, has just released a new version of FlippingBook Publisher. The company keeps developing its products and introduces the latest FlippingBook Publisher release dedicated to interactivity.
All the new features are focused on making FlippingBook documents more compelling, interactive and capturing readers' attention at first sight.
While browsing a document, the readers can now place a note anywhere on the page and capture their quick thought right away. Notes serve well for bookmarking important info, adding comments and questions while working with training or educational materials. This way, the educational documents become as easy and comfortable to work with as printed textbooks. In product catalogs, notes help the clients mark the items they are interested in while looking through the pages, and get back to them while making the purchase.
To make the documents more interactive and eye-catching the marketers are now able to embed GIFs into them. Animated GIFs can be used to illustrate complex ideas in an easy way – for example, to explain new concepts or data in educational or training materials. In catalogs, GIFs can help showcasing products, enticing readers and adding an element of delight and humor to the document.
The more video formats, the better interactivity. Videos, stored on Wistia, can now be embedded into FlippingBook documents along with YouTube and Vimeo videos.
The interactive elements on a page of a document got a new convenient highlight mode. It's very helpful to see what's clickable on a page and it makes finding links and popup images even easier and more intuitive.
FlippingBook started out in 2004. Since then, it has developed FlippingBook Publisher and FlippingBook Online: a professional software and web-service for turning PDFs into interactive HTML5 documents. Its clients are a vast range of companies from many different industries, including manufacturing, real estate, healthcare, education, and retail. For more information visit https://flippingbook.com.


We provide a forum for the economic needs of those doing business in Stockbridge and its environs of Berkshire County. We represent these interests as a unified group and promote friendship and cooperation within the business community. We are here to promote the uniqueness of Stockbridge which offers history, celebrity, romance & intrigue.....Stockbridge, a lovely village in the Berkshire Hills of Western Massachusetts, is peacefully situated in the heart of a quiet and beautiful valley. Visitors are impressed with the charm of the town and those who live here are proud of her role in history, science, and the arts. Since its incorporation as a town in 1739, Stockbridge has grown from an Indian mission to a quiet village of gracious living to multifaceted town that serves as a resort for tourists and a country retreat for many well-to-do urbanites. Few other places of its size can offer its visitors and residents a world-famous music center, a renowned summer theater (Berkshire Theatre Festival), a museum dedicated to a beloved American painter (The Norman Rockwell Museum), as well as historic mansions, a botanical garden, and a broad range of accommodations, dining, and shopping.


Stand up on the left leg and fold back the right leg at the knee. Bring the right foot on the thigh of the left leg so that the outer part of the heel and sole rest on the left leg. This will twist the right foot a little and press its side against the left thigh. Do not press the thigh with the heel itself but with its side. When the side of the heel has been firmly pressed against the left thigh, make the left leg and the whole body tight and straight.
Then raise both hands sideways towards the head. When the hands are stretched above the head, join the palms and the fingers together. Then bring the palms on the head so that the wrists rest on the head.
When the palms have been jointly put on the head, you have to do several things at this stage. Try to give a backward pull on the folded elbows in order to bring them in one line. But do not exert too much. Look straight forward at the level of your eyes. Tighten the leg you are standing on. Now there is tightness all over the body. You are breathing normally, stay in that position you six to eight seconds. You are in Vriksha asana, as shown in fig.
After holding in that asana for the desired periods, loosen the pressure on the palms and stretch out the arms in order to bring them back tightly to their respective sides. When the hands are in position, grab the toes of the folded leg. Left it slightly upwards and then drop it on the floor. You are now back in the position of readiness. Rest for two normal breaths.
After resting for a few seconds, repeat the Vrikshasana a few more times alternating with leg position.
For example, in the second round you have to stand up on the right leg and fold the left leg. Then follow the various steps done in the first round for completing this tree pose.
Make four rounds daily during the first week. During the second week and afterwards make six rounds daily. Keep alternating the leg while making further rounds. Do not practice it more than six rounds in a single day.
Vriksh Asana (Tree Pose) activates all the joints of the body. All the major joints of the body are affected by this single asana. It tones up the muscles of the ankles, toes, knees, hip joints, shoulder joints, elbows, hands and fingers. As a result of this activation and conditioning of the joint muscles, blood circulation becomes normal in the joints and they regain strength.
For the general practitioners Vrikshasana has good conditioning and strengthening effect upon their bodily joints and bones. It brings flexibility in the legs and hands and enhances the measurement of the chest. It is an easy asana and hence every practitioner of Yoga can do it.


UCLA Tarjan Center Lecture – Vindia G. Fernandez, Ph.D.
Vindia G. Fernandez, Ph.D. presented, "Dyslexia 101: Identification and Treatment" at the UCLA Semel Institute as part of the Tarjan Center Lecture Series. The presentation covered information on identifying difficulties and cognitive patterns commonly exhibited by children with dyslexia and other related disorders; key differences between assessment strategies used by educational professionals in the school setting and clinical neuropsychologists in the private/outpatient setting; and evidence-based interventions and where to find them in the community.
CLICK HERE TO WATCH THE FULL LECTURE!


text:
"""Tests for MirroredStrategy."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json
import sys

from absl.testing import parameterized
import numpy as np
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import cross_device_ops as cross_device_ops_lib
from tensorflow.python.distribute import device_util
from tensorflow.python.distribute import distribution_strategy_context as ds_context
from tensorflow.python.distribute import mirrored_strategy
from tensorflow.python.distribute import multi_worker_test_base
from tensorflow.python.distribute import reduce_util
from tensorflow.python.distribute import strategy_combinations
from tensorflow.python.distribute import strategy_test_lib
from tensorflow.python.distribute import values
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.eager import function
from tensorflow.python.eager import test
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.keras.engine import training as keras_training
from tensorflow.python.keras.layers import core as keras_core
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gradients
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.training import gradient_descent
from tensorflow.python.training import optimizer as optimizer_lib
from tensorflow.python.training import server_lib

GPU_TEST = "test_gpu" in sys.argv[0]

@combinations.generate(
    combinations.combine(
        distribution=[
            strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
            strategy_combinations.mirrored_strategy_with_two_gpus,
        ],
        mode=["graph", "eager"]))
class MirroredTwoDeviceDistributionTest(
    strategy_test_lib.DistributionTestBase,
    strategy_test_lib.TwoDeviceDistributionTestBase,
    parameterized.TestCase):

  def testMinimizeLoss(self, distribution):
    if context.executing_eagerly():
      self._test_minimize_loss_eager(distribution)
    else:
      self._test_minimize_loss_graph(distribution)

  def testReplicaId(self, distribution):
    self._test_replica_id(distribution)

  def testNumReplicasInSync(self, distribution):
    self.assertEqual(2, distribution.num_replicas_in_sync)

  def testCallAndMergeExceptions(self, distribution):
    self._test_call_and_merge_exceptions(distribution)

  def testRunRegroupError(self, distribution):
    def run_fn():
      replica_id = int(self.evaluate(_replica_id()))
      # Generates a list with different lengths on different devices.
      # Will fail in _regroup() (if more than one device).
      return list(range(replica_id))

    with distribution.scope(), self.assertRaises(AssertionError):
      distribution.extended.call_for_each_replica(run_fn)

  def testReduceToCpu(self, distribution):
    with distribution.scope():
      result = distribution.extended.call_for_each_replica(_replica_id)
      reduced = distribution.reduce(reduce_util.ReduceOp.SUM, result, axis=None)
      expected = sum(range(distribution.num_replicas_in_sync))
      self.assertEqual(expected, self.evaluate(reduced))

  def reduce_axis_helper(self, distribution, replica_squared_fn):
    with distribution.scope():
      num_replicas = distribution.num_replicas_in_sync
      result = distribution.extended.call_for_each_replica(replica_squared_fn)
      # sum
      reduced = distribution.reduce(reduce_util.ReduceOp.SUM, result, axis=0)
      expected = sum(x * (x + 1) for x in range(num_replicas))
      self.assertNear(expected, self.evaluate(reduced), 0.00001)

      # mean
      reduced = distribution.reduce(reduce_util.ReduceOp.MEAN, result, axis=0)
      expected /= sum(x + 1 for x in range(num_replicas))
      self.assertNear(expected, self.evaluate(reduced), 0.00001)

  def testReduceAxisToCpu(self, distribution):
    for dtype in (dtypes.float32, dtypes.int32):
      def replica_squared_fn(dtype=dtype):
        # Lists with different lengths on different replicas.
        replica_id = _replica_id_as_int()
        return math_ops.cast([replica_id] * (replica_id + 1), dtype)

      self.reduce_axis_helper(distribution, replica_squared_fn)

  def set_v2_tensorshape(self, v2):
    if v2:
      tensor_shape.enable_v2_tensorshape()
    else:
      tensor_shape.disable_v2_tensorshape()

  def testReduceAxisToCpuUnknownShape(self, distribution):
    original_v2 = tensor_shape._TENSORSHAPE_V2_OVERRIDE  # pylint: disable=protected-access
    try:
      for v2 in (False, True):
        self.set_v2_tensorshape(v2)
        for dtype in (dtypes.float32, dtypes.int32):
          for shape in ((None,), None):  # Test both unknown size and rank.
            def replica_squared_fn(dtype=dtype, shape=shape):
              # Lists with different lengths on different replicas.
              replica_id = _replica_id_as_int()
              tensor = math_ops.cast([replica_id] * (replica_id + 1), dtype)
              # Erase shape information
              return array_ops.placeholder_with_default(tensor, shape=shape)

            self.reduce_axis_helper(distribution, replica_squared_fn)
    finally:
      self.set_v2_tensorshape(original_v2)

  def testReplicateDataset(self, distribution):
    dataset_fn = lambda: dataset_ops.Dataset.range(10)
    expected_values = [[i, i+1] for i in range(0, 10, 2)]
    input_fn = self._input_fn_to_test_input_context(
        dataset_fn,
        expected_num_replicas_in_sync=2,
        expected_num_input_pipelines=1,
        expected_input_pipeline_id=0)
    self._test_input_fn_iterable(distribution, input_fn, expected_values)

  def testMakeInputFnIteratorWithDataset(self, distribution):
    dataset_fn = lambda: dataset_ops.Dataset.range(10)
    expected_values = [[i, i+1] for i in range(0, 10, 2)]

    input_fn = self._input_fn_to_test_input_context(
        dataset_fn,
        expected_num_replicas_in_sync=2,
        expected_num_input_pipelines=1,
        expected_input_pipeline_id=0)
    iterator = distribution.make_input_fn_iterator(input_fn)
    self._test_input_fn_iterator(iterator, distribution.extended.worker_devices,
                                 expected_values)

  def testMakeInputFnIteratorWithCallable(self, distribution):
    def fn():
      dataset = dataset_ops.Dataset.range(2).interleave(
          (lambda _: dataset_ops.Dataset.range(10)), cycle_length=2)
      it = dataset_ops.make_one_shot_iterator(dataset)
      return it.get_next
    expected_values = [[i, i] for i in range(0, 10)]

    input_fn = self._input_fn_to_test_input_context(
        fn,
        expected_num_replicas_in_sync=2,
        expected_num_input_pipelines=1,
        expected_input_pipeline_id=0)
    iterator = distribution.make_input_fn_iterator(input_fn)
    self._test_input_fn_iterator(iterator, distribution.extended.worker_devices,
                                 expected_values, test_reinitialize=False,
                                 ignore_order=True)

  def testNumpyDataset(self, distribution):
    self._test_numpy_dataset(distribution)

  def testGlobalStepUpdate(self, distribution):
    self._test_global_step_update(distribution)

  def testRun(self, distribution):
    self._test_run(distribution)

  def testAllReduceSum(self, distribution):
    self._test_all_reduce_sum(distribution)

  def testAllReduceSumGradients(self, distribution):
    self._test_all_reduce_sum_gradients(distribution)

  def testAllReduceSumGradientTape(self, distribution):
    self._test_all_reduce_sum_gradient_tape(distribution)

  def testAllReduceMean(self, distribution):
    self._test_all_reduce_mean(distribution)

  def testAllReduceMeanGradients(self, distribution):
    self._test_all_reduce_mean_gradients(distribution)

  def testAllReduceMeanGradientTape(self, distribution):
    self._test_all_reduce_mean_gradient_tape(distribution)

  def testSummaryForReplicaZeroOnly(self, distribution):
    self._test_summary_for_replica_zero_only(distribution)

  def testTrainableVariables(self, distribution):
    self._test_trainable_variable(distribution)

def one_device_combinations():
  return combinations.combine(
      distribution=[
          strategy_combinations.mirrored_strategy_with_one_cpu,
          strategy_combinations.mirrored_strategy_with_one_gpu,
      ],
      mode=["graph", "eager"])

@combinations.generate(one_device_combinations())
class MirroredOneDeviceDistributionTest(
    strategy_test_lib.DistributionTestBase,
    strategy_test_lib.OneDeviceDistributionTestBase,
    parameterized.TestCase):

  def testMinimizeLoss(self, distribution):
    if context.executing_eagerly():
      self._test_minimize_loss_eager(distribution)
    else:
      self._test_minimize_loss_graph(distribution)

  def testReplicaId(self, distribution):
    self._test_replica_id(distribution)

  def testCallAndMergeExceptions(self, distribution):
    self._test_call_and_merge_exceptions(distribution)

  def testRun(self, distribution):
    self._test_run(distribution)

  def testAllReduceSum(self, distribution):
    self._test_all_reduce_sum(distribution)

  def testAllReduceSumGradients(self, distribution):
    self._test_all_reduce_sum_gradients(distribution)

  def testAllReduceSumGradientTape(self, distribution):
    self._test_all_reduce_sum_gradient_tape(distribution)

  def testAllReduceMean(self, distribution):
    self._test_all_reduce_mean(distribution)

  def testAllReduceMeanGradients(self, distribution):
    self._test_all_reduce_mean_gradients(distribution)

  def testAllReduceMeanGradientTape(self, distribution):
    self._test_all_reduce_mean_gradient_tape(distribution)

class MirroredStrategyVariableCreatorStackTest(
    test.TestCase, parameterized.TestCase):

  @combinations.generate(
      combinations.combine(
          distribution=[
              strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
          ],
          mode=["graph"]))
  def testCreatorStacksAreThreadLocal(self, distribution):
    def model_fn():
      replica_id_str = str(self.evaluate(_replica_id()))

      def thread_creator_fn(next_creator, *args, **kwargs):
        return next_creator(*args, **kwargs) + ":thread_" + replica_id_str

      with variable_scope.variable_creator_scope(thread_creator_fn):
        # Create a variable in this scope.
        v = variable_scope.variable(1.0)

        # This will pause the current thread, and execute the other thread.
        ds_context.get_replica_context().merge_call(lambda _: _)
      return v

    def main_thread_creator(next_creator, *args, **kwargs):
      # We are not using the underlying next_creator for test purposes.
      del next_creator, args, kwargs
      return "main_thread"

    with context.graph_mode(), \
        distribution.scope(), \
        variable_scope.variable_creator_scope(main_thread_creator):
      result = distribution.extended.call_for_each_replica(model_fn)
      result = distribution.experimental_local_results(result)
      expected = ("main_thread:thread_0", "main_thread:thread_1")
      self.assertEqual(expected, result)

@combinations.generate(
    combinations.combine(
        distribution=[
            strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
        ],
        mode=["graph", "eager"]))
class MirroredStrategyCallForEachReplicaTest(test.TestCase):

  def testExecutingEagerlyOutsideFunction(self, distribution):
    """Verify we preserve the value of executing_eagerly_outside_functions()."""
    def model_fn():
      return ops.executing_eagerly_outside_functions()

    originally = ops.executing_eagerly_outside_functions()
    with distribution.scope():
      in_scope = ops.executing_eagerly_outside_functions()
      in_model_fn = distribution.extended.call_for_each_replica(model_fn)
      unwrapped = distribution.experimental_local_results(in_model_fn)
      self.assertEqual(in_scope, unwrapped[0])
      self.assertEqual(in_scope, originally)

    # Verify this all again, but this time in a FuncGraph.
    with func_graph.FuncGraph("fg").as_default(), distribution.scope():
      in_scope = ops.executing_eagerly_outside_functions()
      in_model_fn = distribution.extended.call_for_each_replica(model_fn)
      unwrapped = distribution.experimental_local_results(in_model_fn)
      self.assertEqual(in_scope, unwrapped[0])
      self.assertEqual(in_scope, originally)

  def testFunctionInCallForEachReplica(self, distribution):
    traces = []
    @def_function.function
    def model_fn():
      traces.append(1)
      return ds_context.get_replica_context().replica_id_in_sync_group

    with distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      self.assertEqual((0, 1), self.evaluate(result.values))
      self.assertLen(traces, distribution.num_replicas_in_sync)

  def testFunctionInCallForEachReplicaInsideAnotherFunction(self, distribution):
    traces = []
    @def_function.function
    def model_fn():
      traces.append(1)
      return ds_context.get_replica_context().replica_id_in_sync_group

    @def_function.function
    def step():
      return distribution.extended.call_for_each_replica(model_fn)

    with distribution.scope():
      result = step()
      self.assertEqual((0, 1), self.evaluate(result.values))
      self.assertLen(traces, distribution.num_replicas_in_sync)

  def testNestedFunctionInCallForEachReplicaWithMergeCall(self, distribution):
    def merge_fn(_):
      pass

    @def_function.function
    def model_fn():
      def body_fn(i):
        ds_context.get_replica_context().merge_call(merge_fn)
        return i + 1
      return control_flow_ops.while_loop_v2(lambda i: i < 2, body_fn, [0])

    with distribution.scope():
      with self.assertRaisesRegexp(
          RuntimeError, "`merge_call` called while defining a new graph."):
        distribution.extended.call_for_each_replica(model_fn)

  def testFunctionInCallForEachReplicaWithMergeCall(self, distribution):
    def merge_fn(_):
      pass

    @def_function.function
    def model_fn():
      ds_context.get_replica_context().merge_call(merge_fn)
      return 0.

    with distribution.scope():
      self.assertEqual(
          self.evaluate(distribution.extended.call_for_each_replica(model_fn)),
          0.)

  def testFunctionInCallForEachReplicaCached(self, distribution):
    traces = []

    @def_function.function
    def model_fn():
      traces.append(None)

    self.assertEmpty(traces)

    for i in range(10):
      distribution.extended.call_for_each_replica(model_fn)

      if i == 0:
        num_devices = len(traces)
        self.assertGreater(num_devices, 0)
      else:
        # model_fn should not have been re-evaluated so the length should remain
        # the same.
        self.assertLen(traces, num_devices)

@combinations.generate(
    combinations.combine(
        distribution=[
            strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
        ],
        mode=["graph"]))
class MirroredStrategyNameScopeTest(test.TestCase):
  # NOTE(priyag): Names and name scopes are ignored in eager, hence we are not
  # testing this in eager mode.

  def testNameScope(self, distribution):
    def model_fn():
      with ops.name_scope("foo"):
        a = constant_op.constant(1.0, name="a")
        ds_context.get_replica_context().merge_call(lambda _: _)
        b = constant_op.constant(1.0, name="b")
      return a, b

    with context.graph_mode(), distribution.scope():
      with ops.name_scope("main"):
        result = distribution.extended.call_for_each_replica(model_fn)
        self.assertEqual(2, len(result))
        for v, name in zip(result, ["a", "b"]):
          self.assertIsInstance(v, values.DistributedValues)
          v0, v1 = distribution.experimental_local_results(v)
          self.assertEqual("main/foo/" + name + ":0", v0.name)
          self.assertEqual("main/replica_1/foo/" + name + ":0", v1.name)

  def testWithDefaultName(self, distribution):
    def model_fn():
      with ops.name_scope(None, "foo"):
        a = constant_op.constant(1.0, name="a")
        ds_context.get_replica_context().merge_call(lambda _: _)
        b = constant_op.constant(2.0, name="b")
      return a, b

    with context.graph_mode(), distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      self.assertEqual(2, len(result))
      for v, name in zip(result, ["a", "b"]):
        self.assertIsInstance(v, values.DistributedValues)
        v0, v1 = distribution.experimental_local_results(v)
        self.assertEqual("foo/" + name + ":0", v0.name)
        self.assertEqual("replica_1/foo/" + name + ":0", v1.name)

  # variable_scope.variable() respects name scopes when creating
  # variables. On the other hand variable_scope.get_variable() ignores name
  # scopes but respects variable scope when creating variables. We test both
  # methods of creating variables to make sure that we have the same
  # variable names in both cases.
  def testNameScopeWithVariable(self, distribution):
    def in_cross_replica(_):
      c = variable_scope.variable(1.0, name="c")
      return c

    def model_fn():
      b = variable_scope.variable(1.0, name="b")
      with ops.name_scope("foo"):
        c = ds_context.get_replica_context().merge_call(in_cross_replica)
      return b, c

    with context.graph_mode(), distribution.scope():
      with ops.name_scope("main"):
        a = variable_scope.variable(1.0, name="a")
        result = distribution.extended.call_for_each_replica(model_fn)
      result_b = result[0]
      result_c = result[1]
      self.assertIsInstance(result_b, values.DistributedValues)
      self.assertIsInstance(result_c, values.DistributedValues)
      a0, a1 = distribution.experimental_local_results(a)
      b0, b1 = distribution.experimental_local_results(result_b)
      c0, c1 = distribution.experimental_local_results(result_c)
      self.assertEqual("main/a:0", a0.name)
      self.assertEqual("main/a/replica_1:0", a1.name)
      self.assertEqual("main/b:0", b0.name)
      self.assertEqual("main/b/replica_1:0", b1.name)
      self.assertEqual("main/foo/c:0", c0.name)
      self.assertEqual("main/foo/c/replica_1:0", c1.name)

  def testNameScopeWithGetVariable(self, distribution):
    def in_cross_replica(_):
      c = variable_scope.get_variable("c", [1])
      return c

    def model_fn():
      b = variable_scope.get_variable("b", [1])
      with ops.name_scope("foo"):
        c = ds_context.get_replica_context().merge_call(in_cross_replica)
      return b, c

    with context.graph_mode(), distribution.scope():
      with ops.name_scope("main"):
        a = variable_scope.get_variable("a", [1])
        result = distribution.extended.call_for_each_replica(model_fn)
      result_b = result[0]
      result_c = result[1]
      self.assertIsInstance(result_b, values.DistributedValues)
      self.assertIsInstance(result_c, values.DistributedValues)
      a0, a1 = distribution.experimental_local_results(a)
      b0, b1 = distribution.experimental_local_results(result_b)
      c0, c1 = distribution.experimental_local_results(result_c)
      self.assertEqual("a:0", a0.name)
      self.assertEqual("a/replica_1:0", a1.name)
      self.assertEqual("b:0", b0.name)
      self.assertEqual("b/replica_1:0", b1.name)
      self.assertEqual("c:0", c0.name)
      self.assertEqual("c/replica_1:0", c1.name)

  def testVariableScopeWithGetVariable(self, distribution):

    def in_cross_replica(_):
      c = variable_scope.get_variable("c", [1])
      return c

    def model_fn():
      b = variable_scope.get_variable("b", [1])
      with variable_scope.variable_scope("foo"):
        c = ds_context.get_replica_context().merge_call(in_cross_replica)
      return b, c

    with context.graph_mode(), distribution.scope():
      with variable_scope.variable_scope("main"):
        a = variable_scope.get_variable("a", [1])
        result = distribution.extended.call_for_each_replica(model_fn)
      result_b = result[0]
      result_c = result[1]
      self.assertIsInstance(result_b, values.DistributedValues)
      self.assertIsInstance(result_c, values.DistributedValues)
      a0, a1 = distribution.experimental_local_results(a)
      b0, b1 = distribution.experimental_local_results(result_b)
      c0, c1 = distribution.experimental_local_results(result_c)
      self.assertEqual("main/a:0", a0.name)
      self.assertEqual("main/a/replica_1:0", a1.name)
      self.assertEqual("main/b:0", b0.name)
      self.assertEqual("main/b/replica_1:0", b1.name)
      self.assertEqual("main/foo/c:0", c0.name)
      self.assertEqual("main/foo/c/replica_1:0", c1.name)

@combinations.generate(
    combinations.combine(
        distribution=[
            combinations.NamedDistribution(
                "Mirrored3Devices",
                # pylint: disable=g-long-lambda
                lambda: mirrored_strategy.MirroredStrategy(
                    ["/device:GPU:0", "/device:GPU:1", "/device:CPU:0"]),
                required_gpus=2)
        ],
        mode=["graph", "eager"]))
class MirroredThreeDeviceDistributionTest(
    strategy_test_lib.DistributionTestBase,
    parameterized.TestCase):

  def testThreeDevices(self, distribution):
    def model_fn():
      v = variable_scope.variable(1.0, name="foo")
      ds_context.get_replica_context().merge_call(lambda _: _)
      return v

    with distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      self.assertIsInstance(result, values.MirroredVariable)
      self.assertEqual("foo:0", result.name)

@combinations.generate(
    combinations.combine(
        distribution=[
            strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
        ],
        mode=["graph", "eager"]))
class MirroredVariableUpdateTest(test.TestCase):
  # The following tests check assign, assign_add and assign_sub on Mirrored
  # variables in replica and cross replica context.

  def testAssignMirroredVarReplicaContextWithoutAggregationType(self,
                                                                distribution):
    # Test that we always have an aggregation type set on the mirrored variable
    # if we assign to it in replica mode.
    def var_fn():
      v = variable_scope.variable(1.0, name="foo")
      return v

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())

      def model_fn():
        return mirrored_var.assign(5.0)

      with self.assertRaisesRegexp(
          ValueError, "You must specify an aggregation method to update a "
                      "MirroredVariable in Replica Context. You can do so by"):
        self.evaluate(distribution.experimental_local_results(
            distribution.extended.call_for_each_replica(model_fn)))

  def testAssignMirroredVarReplicaContextWithSum(self, distribution):
    # Test that we don't reduce a non-per-replica value with the "sum"
    # aggregation type.
    def var_fn():
      v = variable_scope.variable(
          1.0, name="foo", aggregation=variable_scope.VariableAggregation.SUM)
      return v

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())

      def model_fn():
        return mirrored_var.assign(5.0)

      with self.assertRaisesRegexp(
          ValueError, "A non-DistributedValues value 5.0 cannot be reduced "
          "with the given reduce op ReduceOp.SUM."):
        self.evaluate(distribution.experimental_local_results(
            distribution.extended.call_for_each_replica(model_fn)))

  def testAssignMirroredVarCrossDeviceContext(self, distribution):
    def var_fn():
      return variable_scope.variable(1.0, name="foo")

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(1.0, self.evaluate(mirrored_var))
      self.assertIsNotNone(ops.tensor_id(mirrored_var))
      mirrored_var_result = self.evaluate(mirrored_var.assign(6.0))
      self.assertEqual(6.0, mirrored_var_result)

  def testAssignMirroredVarReplicaContext(self, distribution):
    def var_fn():
      return variable_scope.variable(
          1.0, name="foo", aggregation=variable_scope.VariableAggregation.MEAN)

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(1.0, self.evaluate(mirrored_var))

      def model_fn():
        value = math_ops.cast(
            ds_context.get_replica_context().replica_id_in_sync_group,
            mirrored_var.dtype)
        return mirrored_var.assign(value)

      self.evaluate(distribution.experimental_local_results(
          distribution.extended.call_for_each_replica(model_fn)))
      self.assertEqual(0.5, self.evaluate(mirrored_var))

  def testAssignMirroredVarReplicaContextWithSingleValue(self, distribution):
    def var_fn():
      return variable_scope.variable(
          1.0, name="foo", aggregation=variable_scope.VariableAggregation.MEAN)

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(1.0, self.evaluate(mirrored_var))

      def model_fn():
        return mirrored_var.assign(5.0)

      self.evaluate(distribution.experimental_local_results(
          distribution.extended.call_for_each_replica(model_fn)))
      self.assertEqual(5.0, self.evaluate(mirrored_var))

  def testAssignAddMirroredVarCrossDeviceContext(self, distribution):
    def var_fn():
      return variable_scope.variable(1.0, name="foo")

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(1.0, self.evaluate(mirrored_var))

      # read_value == True
      mirrored_var_result = self.evaluate(
          mirrored_var.assign_add(6.0, read_value=True))
      self.assertEqual(7.0, mirrored_var_result)
      self.assertEqual(7.0, self.evaluate(mirrored_var.get("/device:CPU:0")))
      self.assertEqual(7.0, self.evaluate(mirrored_var.get("/device:GPU:0")))

      # read_value == False
      self.evaluate(mirrored_var.assign_add(2.0, read_value=False))
      self.assertEqual(9.0, self.evaluate(mirrored_var.get("/device:CPU:0")))
      self.assertEqual(9.0, self.evaluate(mirrored_var.get("/device:GPU:0")))

  def testAssignAddMirroredVarReplicaContext(self, distribution):
    def var_fn():
      return variable_scope.variable(
          1.0, name="foo", aggregation=variable_scope.VariableAggregation.MEAN)

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(1.0, self.evaluate(mirrored_var))

      def model_fn():
        value = math_ops.cast(
            ds_context.get_replica_context().replica_id_in_sync_group,
            mirrored_var.dtype)
        return mirrored_var.assign_add(value)

      self.evaluate(distribution.experimental_local_results(
          distribution.extended.call_for_each_replica(model_fn)))
      self.assertEqual(1.5, self.evaluate(mirrored_var))

  def testAssignAddMirroredVarReplicaContextWithSingleValue(self, distribution):
    def var_fn():
      return variable_scope.variable(
          1.0, name="foo", aggregation=variable_scope.VariableAggregation.MEAN)

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(1.0, self.evaluate(mirrored_var))

      def model_fn():
        return mirrored_var.assign_add(5.0)

      self.evaluate(distribution.experimental_local_results(
          distribution.extended.call_for_each_replica(model_fn)))
      self.assertEqual(6.0, self.evaluate(mirrored_var))

  def testAssignSubMirroredVarCrossDeviceContext(self, distribution):
    def var_fn():
      return variable_scope.variable(5.0, name="foo")

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(5.0, self.evaluate(mirrored_var))
      mirrored_var_result = self.evaluate(mirrored_var.assign_sub(2.0))
      self.assertEqual(3.0, mirrored_var_result)
      self.assertEqual(3.0, self.evaluate(mirrored_var.get("/device:GPU:0")))
      self.assertEqual(3.0, self.evaluate(mirrored_var.get("/device:CPU:0")))

  def testAssignSubMirroredVarReplicaContext(self, distribution):
    def var_fn():
      return variable_scope.variable(
          5.0, name="foo", aggregation=variable_scope.VariableAggregation.MEAN)

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(5.0, self.evaluate(mirrored_var))

      def model_fn():
        value = math_ops.cast(
            ds_context.get_replica_context().replica_id_in_sync_group,
            mirrored_var.dtype)
        return mirrored_var.assign_sub(value)

      self.evaluate(distribution.experimental_local_results(
          distribution.extended.call_for_each_replica(model_fn)))
      self.assertEqual(4.5, self.evaluate(mirrored_var))

  def testAssignSubMirroredVarReplicaContextWithSingleValue(self, distribution):
    def var_fn():
      return variable_scope.variable(
          5.0, name="foo", aggregation=variable_scope.VariableAggregation.MEAN)

    with distribution.scope():
      mirrored_var = distribution.extended.call_for_each_replica(var_fn)
      self.assertIsInstance(mirrored_var, values.MirroredVariable)
      self.evaluate(variables.global_variables_initializer())
      self.assertEqual(5.0, self.evaluate(mirrored_var))

      def model_fn():
        return mirrored_var.assign_sub(1.0)

      self.evaluate(distribution.experimental_local_results(
          distribution.extended.call_for_each_replica(model_fn)))
      self.assertEqual(4.0, self.evaluate(mirrored_var))

@combinations.generate(
    combinations.combine(
        distribution=[
            strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
        ],
        mode=["graph", "eager"]))
class MirroredAndSyncOnReadVariableInitializerTest(test.TestCase):

  def testAssignMirroredVarInitializer(self, distribution):
    # This test is not eager compatible since in eager variables are initialized
    # upon construction instead of once the initialization op is run.
    with context.graph_mode():
      def var_fn():
        v = variable_scope.variable(1.0, name="foo")
        return v

      with distribution.scope():
        mirrored_var = distribution.extended.call_for_each_replica(var_fn)
        self.assertIsInstance(mirrored_var, values.MirroredVariable)
        self.assertFalse(self.evaluate(mirrored_var.is_initialized()))
        self.evaluate(mirrored_var.initializer)
        self.assertTrue(self.evaluate(mirrored_var.is_initialized()))

  def testAssignReplicaLocalVarInitializer(self, distribution):
    # This test is not eager compatible since in eager variables are initialized
    # upon construction instead of once the initialization op is run.
    with context.graph_mode():
      def model_fn():
        v_sum = variable_scope.variable(
            1.0,
            synchronization=variable_scope.VariableSynchronization.ON_READ,
            aggregation=variable_scope.VariableAggregation.SUM)
        self.assertIsInstance(v_sum, values.SyncOnReadVariable)
        return v_sum

      with distribution.scope():
        sync_on_read_var = distribution.extended.call_for_each_replica(
            model_fn)
        self.assertIsInstance(sync_on_read_var, values.SyncOnReadVariable)
        self.assertFalse(self.evaluate(sync_on_read_var.is_initialized()))
        self.evaluate(sync_on_read_var.initializer)
        self.assertTrue(self.evaluate(sync_on_read_var.is_initialized()))

@combinations.generate(
    combinations.combine(
        distribution=[
            strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
        ],
        mode=["graph", "eager"]))
class SyncOnReadVariableAssignTest(test.TestCase):

  def testAssignReplicaLocalVarSumAggregation(self, distribution):
    def model_fn():
      v_sum = variable_scope.variable(
          1.0,
          synchronization=variable_scope.VariableSynchronization.ON_READ,
          aggregation=variable_scope.VariableAggregation.SUM)
      return v_sum

    with distribution.scope():
      sync_on_read_var = distribution.extended.call_for_each_replica(model_fn)
      self.assertIsInstance(sync_on_read_var, values.SyncOnReadVariable)
      self.evaluate(variables.global_variables_initializer())
      # Each replica has a value of 1.0 assigned to it in replica context.
      # When we read the value using `read_var` we should see the SUM of each of
      # values on each of the replicas.
      self.assertEqual(2.0, self.evaluate(
          distribution.extended.read_var(sync_on_read_var)))
      # Assigning 6.0 in cross replica context will assign a value of
      # 6.0/num_replicas to each replica.
      tlv_ops = sync_on_read_var.assign(6.0)
      self.evaluate(tlv_ops)
      # On reading the sync on read var we should get the assigned value back.
      # The value on all the replicas are added before being returned by
      # `read_var`.
      self.assertEqual(6.0, self.evaluate(
          distribution.extended.read_var(sync_on_read_var)))

  def testAssignReplicaLocalVarMeanAggregation(self, distribution):
    def model_fn():
      v_sum = variable_scope.variable(
          1.0,
          synchronization=variable_scope.VariableSynchronization.ON_READ,
          aggregation=variable_scope.VariableAggregation.MEAN)
      return v_sum

    with distribution.scope():
      sync_on_read_var = distribution.extended.call_for_each_replica(model_fn)
      self.assertIsInstance(sync_on_read_var, values.SyncOnReadVariable)
      self.evaluate(variables.global_variables_initializer())
      # Each replica has a value of 1.0 assigned to it in replica context.
      # When we read the value using `read_var` we should see the MEAN of values
      # on all replicas which is the value assigned in replica context.
      self.assertEqual(1.0, self.evaluate(
          distribution.extended.read_var(sync_on_read_var)))
      tlv_ops = sync_on_read_var.assign(6.0)
      self.evaluate(tlv_ops)
      # On reading the sync on read var we should get the MEAN of all values
      # which is equal to the value assigned.
      self.assertEqual(6.0, self.evaluate(
          distribution.extended.read_var(sync_on_read_var)))

class MockModel(object):

  def __init__(self, two_variables=False):
    self.variables = []
    self.variables.append(variable_scope.variable(1.25, name="dummy_var1"))
    if two_variables:
      self.variables.append(variable_scope.variable(2.0, name="dummy_var2"))

  def __call__(self, factor=2):
    x = factor * self.variables[0]
    if len(self.variables) > 1:
      x += self.variables[1]
    return x

class MiniModel(keras_training.Model):
  """Minimal model for mnist.

  Useful for testing and debugging on slow TPU simulators.
  """

  def __init__(self):
    super(MiniModel, self).__init__(name="")
    self.fc = keras_core.Dense(1, name="fc", kernel_initializer="ones",
                               bias_initializer="ones")

  def call(self, inputs, training=True):
    inputs = array_ops.ones([1, 10])
    return self.fc(inputs)

@combinations.generate(
    combinations.combine(
        distribution=[
            strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
        ],
        mode=["graph", "eager"]))
class MirroredStrategyDefunTest(test.TestCase):

  def _call_and_check(self, distribution, model_fn, inputs, expected_result,
                      defuns, two_variables=False):
    cpu_dev = device_util.canonicalize("CPU:0")
    gpu_dev = device_util.canonicalize("GPU:0")
    devices = [cpu_dev, gpu_dev]

    with distribution.scope():
      mock_model = MockModel(two_variables)
      self.evaluate(variables.global_variables_initializer())

      result = distribution.extended.call_for_each_replica(
          model_fn, args=[mock_model] + inputs)
      for r in range(len(devices)):
        device_result = values.select_replica(r, result)
        device_expected_result = values.select_replica(r, expected_result)
        self.assertAllClose(device_expected_result,
                            self.evaluate(device_result))

      for defun in defuns:
        # `Function`s are specialized to the current device stack, so
        # call_for_each has one trace per device. To check that the expected set
        # of variables was accessed on each trace, we first retrieve each
        # device-specific graph function.
        per_replica_graph_functions = (
            distribution.extended.call_for_each_replica(
                defun.get_concrete_function, args=[mock_model] + inputs))
        for device in devices:
          graph_function = per_replica_graph_functions.get(device=device)
          # TODO(b/129555712): re-enable an assertion here that the two sets of
          # variables are the same.
          # self.assertEqual(set(graph_function.graph.variables),
          #  set(mock_model.variables))
          del graph_function

  def testVariableInDefun(self, distribution):
    @function.defun
    def times_two(mock_model):
      return mock_model()

    def model_fn(mock_model):
      return times_two(mock_model)

    self._call_and_check(distribution, model_fn, [], 2.5, [times_two])

  def testVariableInNestedDefun(self, distribution):
    @function.defun
    def times_two(mock_model):
      return mock_model()

    @function.defun
    def two_x_plus_one(mock_model):
      return times_two(mock_model) + 1

    def model_fn(mock_model):
      return two_x_plus_one(mock_model)

    self._call_and_check(distribution, model_fn, [], 3.5,
                         [times_two, two_x_plus_one])

  def testTwoVariablesInNestedDefun(self, distribution):
    @function.defun
    def fn1(mock_model):
      return mock_model()

    @function.defun
    def fn2(mock_model):
      return fn1(mock_model) + 1

    def model_fn(mock_model):
      return fn2(mock_model)

    self._call_and_check(distribution, model_fn, [], 5.5, [fn1, fn2],
                         two_variables=True)

  def testGradientTapeOverNestedDefuns(self, distribution):
    @function.defun
    def fn1(mock_model):
      return mock_model()

    @function.defun
    def fn2(mock_model):
      return fn1(mock_model) + 1

    def model_fn(mock_model):
      with backprop.GradientTape(persistent=True) as gtape:
        result = fn2(mock_model)
      grads = gtape.gradient(result,
                             [v.get() for v in mock_model.variables])
      return grads

    self._call_and_check(distribution, model_fn, [], [2.0, 1.0], [fn1, fn2],
                         two_variables=True)

  def testPassPerReplica(self, distribution):
    @function.defun
    def fn1(mock_model, factor):
      return mock_model(factor)

    device_map = values.ReplicaDeviceMap(("/device:CPU:0", "/device:GPU:0"))
    factors = values.PerReplica(device_map, (5.0, 3.0))
    expected_result = values.PerReplica(device_map, (5.0 * 1.25, 3.0 * 1.25))
    self._call_and_check(distribution, fn1, [factors], expected_result, [fn1])

  def testTrain(self, distribution):
    with distribution.scope():
      mock_model = MiniModel()
      mock_model.call = function.defun(mock_model.call)

      def loss_fn(ctx):
        del ctx
        return mock_model(array_ops.ones([1, 10]))

      gradients_fn = backprop.implicit_grad(loss_fn)
      gradients_fn = optimizer_lib.get_filtered_grad_fn(gradients_fn)
      grads_and_vars = distribution.extended.call_for_each_replica(
          gradients_fn, args=(None,))

      optimizer = gradient_descent.GradientDescentOptimizer(0.25)
      update_ops = optimizer._distributed_apply(distribution, grads_and_vars)  # pylint: disable=protected-access

      if not context.executing_eagerly():
        self.evaluate(variables.global_variables_initializer())
        self.evaluate(update_ops)

      updated_var_values = self.evaluate(mock_model.variables)
      # All variables start at 1.0 and get two updates of 0.25.
      self.assertAllEqual(0.5 * np.ones([10, 1]), updated_var_values[0])
      self.assertAllEqual([0.5], updated_var_values[1])

@combinations.generate(
    combinations.combine(
        distribution=[
            combinations.NamedDistribution(
                "Mirrored",
                # pylint: disable=g-long-lambda
                lambda: mirrored_strategy.MirroredStrategy(
                    devices=mirrored_strategy.all_local_devices(),
                    cross_device_ops=cross_device_ops_lib.MultiWorkerAllReduce([
                        "/job:worker/task:0", "/job:worker/task:1"
                    ], context.num_gpus())),
                required_gpus=1)
        ],
        mode=["graph"]))
class MultiWorkerMirroredStrategyTest(
    multi_worker_test_base.MultiWorkerTestBase,
    strategy_test_lib.DistributionTestBase):

  def _configure_distribution_strategy(self, distribution):
    cluster_spec = server_lib.ClusterSpec({
        "worker": ["/job:worker/task:0", "/job:worker/task:1"]
    })
    distribution.configure(cluster_spec=cluster_spec)

  def test_num_replicas_in_sync(self, distribution):
    self._configure_distribution_strategy(distribution)
    # We calculate the total number of gpus across the workers(2) specified in
    # the cluster spec.
    self.assertEqual(context.num_gpus() * 2, distribution.num_replicas_in_sync)

  def testMinimizeLossGraph(self, distribution):
    self._configure_distribution_strategy(distribution)
    self._test_minimize_loss_graph(distribution, learning_rate=0.05)

  def testDeviceScope(self, distribution):
    """Test the device scope of multi-worker MirroredStrategy."""
    self._configure_distribution_strategy(distribution)
    with distribution.scope():
      a = constant_op.constant(1.)
      with ops.device("/cpu:0"):
        b = constant_op.constant(1.)
      self.assertEqual(a.device, "/job:worker/task:0")
      self.assertEqual(b.device, "/job:worker/task:0/device:CPU:0")

  def testMakeInputFnIteratorWithDataset(self, distribution):
    self._configure_distribution_strategy(distribution)
    dataset_fn = lambda: dataset_ops.Dataset.range(100)
    num_gpus = context.num_gpus()
    num_workers = 2

    expected_values = [[i+j for j in range(num_gpus)] * num_workers
                       for i in range(0, 100, num_gpus)]

    with context.graph_mode(), self.cached_session() as sess:
      # `expected_input_pipeline_id` is None because the input_fn will be called
      # multiple times, each with a different input_pipeline_id.
      input_fn = self._input_fn_to_test_input_context(
          dataset_fn,
          expected_num_replicas_in_sync=num_workers*num_gpus,
          expected_num_input_pipelines=num_workers,
          expected_input_pipeline_id=None)
      iterator = distribution.make_input_fn_iterator(input_fn)
      self._test_input_fn_iterator(
          iterator, distribution.extended.worker_devices, expected_values, sess)

  def testMakeInputFnIteratorWithCallable(self, distribution):
    self._configure_distribution_strategy(distribution)
    def fn():
      dataset = dataset_ops.Dataset.range(100)
      it = dataset_ops.make_one_shot_iterator(dataset)
      return it.get_next
    num_gpus = context.num_gpus()
    num_workers = 2

    expected_values = []
    for i in range(0, 100, num_gpus):
      expected_values.append([i+j for j in range(num_gpus)] * num_workers)

    with context.graph_mode(), self.cached_session() as sess:
      # `expected_input_pipeline_id` is None because the input_fn will be called
      # multiple times, each with a different input_pipeline_id.
      input_fn = self._input_fn_to_test_input_context(
          fn,
          expected_num_replicas_in_sync=num_workers*num_gpus,
          expected_num_input_pipelines=num_workers,
          expected_input_pipeline_id=None)
      iterator = distribution.make_input_fn_iterator(input_fn)
      self._test_input_fn_iterator(
          iterator, distribution.extended.worker_devices, expected_values, sess,
          test_reinitialize=False, ignore_order=True)

  def testUpdateConfigProto(self, distribution):
    distribution.configure(cluster_spec={"worker": ["fake1", "fake2"]})

    config_proto = config_pb2.ConfigProto()
    new_config = distribution.update_config_proto(config_proto)

    # Verify isolate_session_state
    self.assertTrue(new_config.isolate_session_state)

@combinations.generate(
    combinations.combine(
        distribution=[
            combinations.NamedDistribution(
                "Mirrored",
                # pylint: disable=g-long-lambda
                lambda: mirrored_strategy.MirroredStrategy(
                    devices=["/job:worker/task:0/gpu:{}".format(
                        i) for i in range(context.num_gpus())]),
                required_gpus=1)
        ],
        mode=["graph"]))
class RemoteSingleWorkerMirroredStrategy(
    multi_worker_test_base.SingleWorkerTestBase,
    strategy_test_lib.DistributionTestBase):

  def test_num_replicas_in_sync(self, distribution):
    self.assertEqual(context.num_gpus(), distribution.num_replicas_in_sync)

  def testMinimizeLossGraph(self, distribution):
    self._test_minimize_loss_graph(distribution, learning_rate=0.05)

  def testDeviceScope(self, distribution):
    """Test the device scope of single-worker MirroredStrategy."""
    with distribution.scope():
      a = constant_op.constant(1.)
      with ops.device("/cpu:0"):
        b = constant_op.constant(1.)
      self.assertEqual(a.device, "/job:worker/replica:0/task:0")
      self.assertEqual(b.device, "/job:worker/replica:0/task:0/device:CPU:0")

  def testMakeInputFnIteratorWithDataset(self, distribution):
    dataset_fn = lambda: dataset_ops.Dataset.range(100)
    num_gpus = context.num_gpus()
    num_workers = 1

    expected_values = [[i+j for j in range(num_gpus)] * num_workers
                       for i in range(0, 100, num_gpus)]

    with context.graph_mode(), self.cached_session() as sess:
      # `expected_input_pipeline_id` is None because the input_fn will be called
      # multiple times, each with a different input_pipeline_id.
      input_fn = self._input_fn_to_test_input_context(
          dataset_fn,
          expected_num_replicas_in_sync=num_workers*num_gpus,
          expected_num_input_pipelines=num_workers,
          expected_input_pipeline_id=None)
      iterator = distribution.make_input_fn_iterator(input_fn)
      self._test_input_fn_iterator(
          iterator, distribution.extended.worker_devices, expected_values, sess)

  def testMakeInputFnIteratorWithCallable(self, distribution):
    def fn():
      dataset = dataset_ops.Dataset.range(100)
      it = dataset_ops.make_one_shot_iterator(dataset)
      return it.get_next
    num_gpus = context.num_gpus()
    num_workers = 1

    expected_values = []
    for i in range(0, 100, num_gpus):
      expected_values.append([i+j for j in range(num_gpus)] * num_workers)

    with context.graph_mode(), self.cached_session() as sess:
      # `expected_input_pipeline_id` is None because the input_fn will be called
      # multiple times, each with a different input_pipeline_id.
      input_fn = self._input_fn_to_test_input_context(
          fn,
          expected_num_replicas_in_sync=num_workers*num_gpus,
          expected_num_input_pipelines=num_workers,
          expected_input_pipeline_id=None)
      iterator = distribution.make_input_fn_iterator(input_fn)
      self._test_input_fn_iterator(
          iterator, distribution.extended.worker_devices, expected_values, sess,
          test_reinitialize=False, ignore_order=True)

class MultiWorkerMirroredStrategyTestWithChief(
    multi_worker_test_base.MultiWorkerTestBase,
    strategy_test_lib.DistributionTestBase):

  @classmethod
  def setUpClass(cls):
    """Create a local cluster with 2 workers and 1 chief."""
    cls._cluster_spec = multi_worker_test_base.create_in_process_cluster(
        num_workers=2, num_ps=0, has_chief=True)
    cls._default_target = "grpc://" + cls._cluster_spec["chief"][0]

  def _make_cross_device_ops(self):
    return cross_device_ops_lib.MultiWorkerAllReduce(
        ["/job:chief/task:0", "/job:worker/task:0", "/job:worker/task:1"],
        context.num_gpus())

  def testMinimizeLossGraph(self):
    with context.graph_mode():
      strategy = mirrored_strategy.MirroredStrategy(
          cross_device_ops=self._make_cross_device_ops())
      strategy.configure(cluster_spec=self._cluster_spec)
      self._test_minimize_loss_graph(strategy, learning_rate=0.05)

  def testMinimizeLossGraphMirroredStrategy(self):
    with context.graph_mode():
      strategy = mirrored_strategy.MirroredStrategy(
          mirrored_strategy.all_local_devices(),
          cross_device_ops=self._make_cross_device_ops())
      strategy.configure(cluster_spec=self._cluster_spec)
      self._test_minimize_loss_graph(strategy, learning_rate=0.05)

  def testMinimizeLossGraphMirroredStrategyWithOneNode(self):
    with context.graph_mode():
      cluster_spec = {}
      cluster_spec["chief"] = self._cluster_spec["chief"]
      tf_config = {"cluster": cluster_spec}
      with test.mock.patch.dict("os.environ",
                                {"TF_CONFIG": json.dumps(tf_config)}):
        strategy = mirrored_strategy.MirroredStrategy()
        if context.num_gpus() > 0:
          self.assertIsInstance(strategy.extended._inferred_cross_device_ops,
                                cross_device_ops_lib.NcclAllReduce)
        else:
          self.assertIsInstance(strategy.extended._inferred_cross_device_ops,
                                cross_device_ops_lib.ReductionToOneDevice)
      self.skipTest("b/130551176, run the following once fixed.")
      self._test_minimize_loss_graph(strategy, learning_rate=0.05)

  def testInitializeFromTFConfig(self):
    with context.graph_mode():
      tf_config = {"cluster": self._cluster_spec}
      with test.mock.patch.dict("os.environ",
                                {"TF_CONFIG": json.dumps(tf_config)}):
        strategy = mirrored_strategy.MirroredStrategy(
            cross_device_ops=self._make_cross_device_ops())
        self.assertEqual(
            max(context.num_gpus(), 1) * 3, strategy.num_replicas_in_sync)

  def testSummaryForReplicaZeroOnly(self):
    with context.graph_mode():
      strategy = mirrored_strategy.MirroredStrategy(
          mirrored_strategy.all_local_devices(),
          cross_device_ops=self._make_cross_device_ops())
      strategy.configure(cluster_spec=self._cluster_spec)
      self._test_summary_for_replica_zero_only(strategy)

class MirroredVariableStopGradientTest(test.TestCase, parameterized.TestCase):

  @combinations.generate(
      combinations.combine(
          distribution=[
              strategy_combinations.mirrored_strategy_with_one_cpu,
              strategy_combinations.mirrored_strategy_with_one_gpu,
          ],
          mode=["graph"]))
  def testMirroredVariableAsStopGradient(self, distribution):
    with distribution.scope():
      inp = constant_op.constant(1.0)
      x = variables.Variable(1.0)
      y = inp*x
      grads = gradients.gradients(x, y, stop_gradients=x)
      self.assertIsNone(grads[0])

def _replica_id():
  replica_id = ds_context.get_replica_context().replica_id_in_sync_group
  if not isinstance(replica_id, ops.Tensor):
    replica_id = constant_op.constant(replica_id)
  return replica_id

def _replica_id_as_int():
  replica_id = ds_context.get_replica_context().replica_id_in_sync_group
  if isinstance(replica_id, ops.Tensor):
    replica_id = tensor_util.constant_value(replica_id)
  return replica_id

if __name__ == "__main__":
  test.main()


text:
Samsung's latest flagship phone is one of the first to tap into new spectrum being deployed by the US carrier.
Samsung announced the Galaxy S9 and S9+ yesterday, but the news for T-Mobile subscribers doesn't stop there. It turns out the new Galaxy phones support team magenta's new 600MHz band 71 LTE. So if you've got your heart set on taking advantage of the frequency's extra coverage and penetration in the coming years, then the S9 and S9+ are your best bet right now.
T-Mobile is offering credits on trade-ins too, with half-off the S9 or $360 off the S9+. The carrier hasn't specified which phones are eligible for the rebate, which are spread out as monthly bill credits. Sprint, too, will offer up to $350 in trade-in rebates for S9 and S9+ customers.
T-Mobile will begin Galaxy S9 and Galaxy S9+ preorders on March 1 at 9:01 pm PT, with in-store availability from March 16. The Galaxy S9 will be $30 per month for 24 months on the T-Mobile Equipment Installment Plan, with $0 down and 0-percent APR; in the end, you'll pay $720. The Galaxy S9+ will also be $30 per month on the same plan, but with a $120 downpayment; in total, you'll pay $840. They'll be offered in Lilac Purple, Midnight Black, and Coral Blue.
While T-Mobile has improved the speed and coverage of its networks over the past several years, the carrier still has significant gaps in rural parts of the nation, and still lags behind Verizon and AT&T on total nationwide coverage. The 600 MHz spectrum will allow T-Mobile to even the field. The company began using the airwaves last year and now covers 738 cities and towns across 30 states.
The Galaxy S9 isn't the first to tap into the 600 MHz band — that honor belongs to last fall's LG V30. But the V30 wasn't a big seller, and the Galaxy S9 will likely mark the first phone that gets broadly adopted to take advantage of T-Mobile's big coverage boost.
The Galaxy S9 and V30 won't be alone for long. T-Mobile said it plans to launch more than a dozen phones with the capability this year, ranging from budget devices to superphones.
Source: https://www.cnet.com/news/how-the-samsung-galaxy-s9-marks-a-big-coverage-boost-for-t-mobile-mwc-2018/


Our next meeting will be on December 10, 2018 at 11 am.
Safe Haven will provide a collaborative healing environment for the behavioral health continuum by creating a high-quality, coordinated, sustainable and humane network of care anchored in St. Tammany Parish.
Join our mailing list for the latest updates on Safe Haven St. Tammany.
For more information about Safe Haven please contact us.


text:
Q: How can I Call a function within a function using action script 3.0 How can i call function in another function using action script 3.0
Here I am Using WSDL Web service and getting data in my data grid. i want to put this data into my database table.
I am calling Following function on Button click event which is associated to WebService .
private function Login():void {
                // Get Data from WebService and fill datagrid when you fist invoke the application
                SignIn1Result2.token = vtrServices.SignIn1(txtUserName.text, txtPassword.text);
                stmt.sqlConnection = this.isDbConnected(conn);
                func:addEventListener(SQLEvent.OPEN,insertContact);

                 /* insertContact(SignIn1Result2.lastResult.UserId,SignIn1Result2.lastResult.UserName,SignIn1Result2.lastResult.ContactName,SignIn1Result2.lastResult.Password,SignIn1Result2.lastResult.Salt); */
                }

And my WebService Definition is
  <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
            <mx:WebService
                id="ws"
                wsdl="http://localhost:2690/vtrServices.asmx?wsdl">
                <mx:operation
                    name="GetEmployees"
                    resultFormat="object"
                    result="Login()"
                    />

            </mx:WebService>
            <vtrservices:VtrServices id="vtrServices"
                                     fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)"
                                     showBusyCursor="true"/>
            <s:CallResponder id="SignIn1Result2"/>
 </fx:Declarations>

My controls
<mx:Panel x="41.5" y="66" width="714.5" height="237" layout="absolute" title="ASP.NET WebService + Flex Demonstration">
        <mx:HBox height="95%" width="95%" horizontalCenter="0" verticalCenter="0">
            <mx:DataGrid id="datagrid" width="499" height="100%"
                         dataProvider="{SignIn1Result2.lastResult}">
                <mx:columns>
                    <mx:DataGridColumn headerText="User Id" dataField="UserId"/>
                    <mx:DataGridColumn headerText="UserName" dataField="UserName"/>
                    <mx:DataGridColumn headerText="ContactName" dataField="ContactName"/>
                    <mx:DataGridColumn headerText="Password" dataField="Password"/>
                    <mx:DataGridColumn headerText="Salt" dataField="Salt"/>
                </mx:columns>
            </mx:DataGrid>

            <mx:Form x="608" y="74" width="100%" height="100%" borderStyle="solid" id="UserLogin">

                <mx:FormItem label="UserName">
                    <mx:TextInput width="106" id="txtUserName"/>
                </mx:FormItem>

                <mx:FormItem label="Password">
                    <mx:TextInput width="106"
                                  displayAsPassword="true"
                                  id="txtPassword"/>
                </mx:FormItem>

                <mx:FormItem width="156" horizontalAlign="right">
                    <mx:Button label="Login" id="btnLogin" click="Login();"/>
                </mx:FormItem>

            </mx:Form>
        </mx:HBox>
    </mx:Panel>

here is the following function which should be called after success of Login() funtion or i can say within the Login() Function
private function insertContact(UserId:String, UserName:String,ContactName:String, Password:String, Salt:String):void
            {
                stmt.sqlConnection = this.isDbConnected(conn);
                stmt.text = "INSERT INTO TblUsers (UserId, UserName, ContactName ,Password, Salt) VALUES('"+SignIn1Result2.lastResult.UserId+"','"+SignIn1Result2.lastResult.UserName+"','"+SignIn1Result2.lastResult.ContactName+"','"+SignIn1Result2.lastResult.Password+"','"+SignIn1Result2.lastResult.Salt+"');";
                Alert.show("Contact Has been Saved");
                stmt.execute();
            }

I have Binded the following
[Bindable]
        public var conn:SQLConnection = new SQLConnection();

        [Bindable]
        private var stmt:SQLStatement = new SQLStatement();

        // ArrayCollection used as a data provider for the datagrid. It has to be bindable so that data in datagrid changes automatically when we change the ArrayCollection

        [Bindable]
        private var contactList:ArrayCollection = new ArrayCollection();

InsertContact() Is the function that i want to call within the Login() function execution success

A: Functions are Called within a function Just like other Scripting Languages But Here You have to Watch Carefully on what Event you want to call them.
I got It , I found the Mistakes i was doing .
As i said i Want to call the function on Success of WebService Function
Here the function Should be called on Result Event of The webService Call .
So i Have just Added the Result Event to my WebService Block Of Flex Application and changed the Webservice Definition According to it
<mx:WebService
            id="ws"
            wsdl="http://localhost:2690/vtrServices.asmx?wsdl">

        </mx:WebService>
        <vtrservices:VtrServices id="vtrServices"
                                 fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)"
                                 showBusyCursor="true"
                                 result="vtrServices_resultHandler(event)"/>
        <s:CallResponder id="SignIn1Result2"/>

Then I have used The Data Provider And its 'LastResult' Property In the Result Event
and the function that i want to be executed is
private function insertContact(UserId:String, UserName:String,ContactName:String, Password:String):void
        {
            stmt.sqlConnection = this.isDbConnected(conn);
            stmt.text = "INSERT INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('"+UserId+"','"+UserName+"','"+ContactName+"','"+Password+"');";
            Alert.show("Contact Has been Saved");
            stmt.execute();
        }

protected function vtrServices_resultHandler(event:ResultEvent):void
            {
                // TODO Auto-generated method stub
                Alert.show(SignIn1Result2.lastResult[0].UserName);
                insertContact(SignIn1Result2.lastResult[0].UserId,SignIn1Result2.lastResult[0].UserName,SignIn1Result2.lastResult[0].ContactName,SignIn1Result2.lastResult[0].Password);
                lblWelcome.text = "Welcome"
                lblName.text = SignIn1Result2.lastResult[0].ContactName;
            }

Here [0] is my row Index Number
Thanks


text:
Q: Questions about one dimensional arrays and sorting in Java I'm currently in the second half of a computer science class but I wasn't able to take the second one right after the first one. So I've forgot a large portion of my coding knowledge. I'm trying to re learn it all but it's quite tough without just going all the way back to the basics.
An assignment I'm working on currently is asking me to do the following:

Design a solution that requests and receives student names and an exam score for each. Use one-dimensional arrays to solve this.
The program should continue to accept names and scores until the user inputs a student whose name is "alldone".
After the inputs are complete determine which student has the highest score and display that student's name and score.
Finally sort the list of names and corresponding scores in ascending order.

I wasn't really sure how to organize and start this but I went ahead and just started writing some code to at least make some progress and maybe figure something out.
The way I've set up my program doesn't exactly respond to the prompt as I was experimenting with array lengths and for loops to get reacquainted.
SO MY QUESTION IS, How would I make it so when users type "alldone" the program stops taking inputs and calculates the highest grade with the person who had it only using 1D Arrays.
Is it possible to take the names as a string and then insert the strings into an array?
Here is my code so far, It's not what the assignment is looking for but I just want to get some inspiration on some things I could do:
public static void main(String[] args) {
    int studentcount;
    Scanner input = new Scanner(System.in);
    Scanner sc= new Scanner(System.in);

    //Input to set array length
    System.out.println("How many students are you grading? ");
    studentcount=sc.nextInt();

    //One dimensional array to hold student names/grades
    String [] names = new String [studentcount+1];
    int [] grades = new int [studentcount];

    //Input to record student names/grades
    System.out.println("Please enter the name of the students ");
    for (int i = 0; i < names.length; i++) {
        names[i] = sc.nextLine();
    }
    System.out.println("Please enter the grades of the students ");
    for (int i = 0; i < grades.length; i++) {
        grades[i] = sc.nextInt();
    }

    // For loop to display student names and grades
    for (int i = 0; i < studentcount; i++) {
    System.out.println(names[i+1] + " " + grades[i]);
}}}

The output looks like this:
How many students are you grading?
3
Please enter the name of the students
John
Brett
Wendy
Please enter the grades of the students
10
20
30
John 10
Brett 20
Wendy 30

A: You should create a class and implement the Comparable interface like this.  The way I have it set up here, it sorts by name. If you want to sort by the score, just comment out the name compare and uncomment the grade compare.
public class Student implements Comparable<Student> {
private String name;
private int grade;

public Student(String name, int grade) {
    this.name = name;
    this.grade = grade;
}

public String getName() {
    return name;
}

public int getGrade() {
    return grade;
}

@Override
public int compareTo(Student o) {
    //sorting by name
    return name.compareTo(o.name);
    //Compare by grade -- reversed so it's highest first
    //return Integer.compare(o.grade, grade);
}

@Override
public String toString() {
    return "Student [name=" + name + ", grade=" + grade + "]";
}

public static void main(String[] args) {
    try (Scanner input = new Scanner(System.in)) {
        Student [] students = new Student[0];

        while(true) {
            System.out.println("Please enter the name of the student or \"alldone\" if complete: ");
            String name = input.next();
            if (name.contentEquals("alldone")) {
                break;
            }
            System.out.println(String.format("Please enter %s's grade: ", name));
            int grade = input.nextInt();
            input.reset();

            students = Arrays.copyOf(students, students.length+1);
            students[students.length-1] = new Student(name, grade);
        }

        Arrays.sort(students);

        for (Student student : students) {
            System.out.println(student);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

A: It doesn't make sense to enter the number of students and also signal the end of input with a keyword.  Since you must key in on "alldone" to stop taking input, it is implied (to me) you must initially over allocate you arrays.   I chose 3 for demo purposes.  If more input is required the arrays can be adjusted as demonstrated.  This example simply explains how to take in the data and populate the arrays.  It does not deal with the mechanics of sorting as that was not part of your question.
int studentCount = 0;
Scanner input = new Scanner(System.in);

// allocate space for three students
String[] names = new String[3];
int[] grades = new int[3];

int maxInput = names.length;
System.out.println(
        "Please enter name and grade of student (e.g. john 23)\non each line.");

// now enter the student and their grade
for (int i = 0; i < maxInput; i++) {

    String name = input.next();

    // this is where you check for the keyword to signal
    // end of input
    if (name.equals("alldone")) {
        break;
    }
    names[studentCount] = name;
    grades[studentCount++] = input.nextInt();

    // if you have maxed out your arrays you need to copy
    // the contents to a larger array
    if (studentCount == maxInput) {
        // increase array size
        maxInput += 3;  // increase by 3.
        names = Arrays.copyOf(names, maxInput);
        grades = Arrays.copyOf(grades, maxInput);
    }
}

// once here, the input part is over.  This displays the entered data
for (int i = 0; i < studentCount; i++) {
    System.out.println(names[i] + " " + grades[i]);
}

Note, at this point it is possible that your arrays will contain extra spaces that could affect your sort (and possibly cause an error).  You can trim the excess space using Arrays.copyOf as before, specifying the number of students.
Or if you sort using your own routine, you can ignore the excess spaces by using studentCount instead of the length of the arrays.


The second one version of Textbook of basic Anatomy provides undergraduate and postgraduate scholars with the hottest details within the field.
Beginning with an advent to anatomy and histology, the next sections research forms of tissue came across in the course of the body.
Topics are offered in bullet aspect structure for simple analyzing and comprise quite a few vibrant diagrams. each one bankruptcy ends with assessment inquiries to increase studying and attempt knowledge.
"Karen Stabiner's going in [is] funny (in a wry type of approach) yet pointed and unusually enticing novel approximately parental and teenage obsessiveness concerning the university software procedure in self sufficient faculties and the debilitating, distorting impression of it on little ones and households. needs to learn for college-prep youngsters and their mom and dad.
From Publishers Weekly *Starred overview. * Signature*Reviewed via* Perri KlassI want I had learn this publication while i used to be in clinical college, and i am joyful i have learn it now. so much readers will knowJerome Groopman from his essays within the *New Yorker*, which tackle a large choice of complicated health conditions, evocatively speaking the tensions and feelings of either medical professionals and sufferers.
Symmetry is without doubt one of the strongest and wide-ranging of mathematical rules with fresh paintings on symmetry breaking, whilst symmetrical styles are a bit of altered or corrupted, throwing up a rare diversity of functions and ordinary examples, from the stripes on a tiger's again to the territorial styles of fish and to the constitution of viruses.
In the blood, as the monocytes. In the sinusoids of the liver (Kuffer's cells), spleen, bone marrow and else where.  In the lymphoid tissues and lymph nodes as the reticular cells.  In the lung alveoli as the alveolar phagocytes.  In the brain and spinal cord, as the microglia.    Function The Macrophages Phagocytose and digest particulate organic materials, foreign bodies or invading microorganisms and thereby eliminate them from the body to avoid any injurious effects.  Sometimes a number of macrophages form a barricade around a large foreign material and often coalesce with one another to form mononucleated masses known as the foreign body Giant cells (Fig.
They branch and join together to form a network within a tissue. These fibers are much fewer than the collagen fibers. They are elastic and stretchable, with perfect recoiling. The thin elastin fibers branch and rejoin freely.  Elastic fibers are formed by fibroblasts.  But in the walls of arteries they are formed by smooth muscle cells.  Though elastic fibers are stretchable and elastic, their elasticity diminishes with age.  The elastic fibers are composed of protein subunits the tropoelastin which possess high content of amino acid valine.
Each cell is spherical or polygonal, consists of peripheral rim of cytoplasm with an eccentric nucleus and contains a large central lobule of fat. Connective Tissue Fig. 9: Fat cell  When stained with H and E, the cell is 'signet ring' in appearance because the fat is dissolved by the solvent used.  By special method, fat may be fixed and stained with Sudan III, Sudan black, Scharlach R. CONNECTIVE TISSUE–II Connective tissue–II is considered under the following headings: Connective tissue matrix  Fibers –– Collagen fibers –– Elastic fibers –– Reticular fibers  Ground substance  Types of mature connective tissue  Applied anatomy of connective tissue.