text:
Home / NEWS & INSIGHTS / Blog / The Handshake / New Balance Chinese trade mark win – kicking a goal for damages in China
The Handshake 14 September 2017
New Balance Chinese trade mark win – kicking a goal for damages in China
A Chinese court recently ruled three local shoemakers have infringed the New Balance 'NB' logo and must pay US $1.5 million in damages and legal costs. The case is significant as it is reportedly the largest amount awarded to a foreign business in a Chinese trade mark dispute. The infringing shoemakers manufactured shoes under a brand called 'New Boom' and were found by the court to have damaged the reputation of New Balance and confused consumers due to the high similarity of their logos to the New Balance 'NB' logo and brand.
Critics have often maintained China's intellectual property system does not sufficiently protect foreign brands; however this recent decision is certainly a step in the right direction.
Under the Chinese system, the first party to file for a trade mark is awarded protection. In Australia, on the other hand, the first party to use the trade mark is awarded protection (unless there is no prior use, in which case registration is awarded on a first come first served basis). The way the Chinese system operates means it is vital brands register the trade mark in China as soon as possible, before expanding into the Chinese market. Otherwise, the brand may find the trade mark has already been registered to a trade mark squatter, or to a party producing imitation goods.
In recent months, the Chinese Government has vowed to tackle the issue of intellectual property infringement caused by the legions of fake goods produced and offered for sale in the country. There have also been changes to Chinese trade mark law over the past few years to take on trade mark abuse. This decision indicates steps are being made to support foreign rights holders. It also provides reassurance for foreign brands looking to expand into the Chinese market and pursue an active brand protection strategy.
Belinda Breakspear


text:
Eye Magazine
Contact Eye
Eye, the international review of graphic
design, is a quarterly printed magazine about
graphic design and visual culture
Monday, 5:00am
What type taught me about music
Critical path
Music design
Rick Finlay recalls his time at Reading, a university education that was not about vocation, but 'raw knowledge and research, and their applicability to whatever life throws at you'
As an undergraduate on the Typography course at Reading University around 1980 I found enough fellow tunesmiths to put together a five-piece band made up only of students on the course, writes Rick Finlay. We were proud of our rock-pop constructions, but also fastidious about the packaging of our demo cassette.
After graduating in 1982, my life took the other fork in the road and, although my early career as a drummer and percussionist was subsidised by freelance book design for a year or so, my portfolio was soon gathering dust under the bed.
And yet my passion for my four years at Reading persisted, and there was little need for hindsight to recognise that the inspiring institution of the department shaped my adult self and continues to influence my work to this day.
When I stumbled across the obituary of Paul Stiff last year, I found myself reflecting on how it could be that the Department of Typography & Graphic Communication (we would brook no abbreviation) played such a significant part in how I lead my life as a musician.
It felt like a golden time: the course had originated as Michael Twyman's baby some years earlier, but by 1978 the ethos and modus operandi was in full flow. The brightly coloured internal architecture of the prefab buildings shouted 'modern' to my eighteen-year-old north London eyes, and Swiss typography was still a recent enough concept to be a rallying cry to those of us in love with design as a pure and political rebuttal to the lightweight postwar ephemeral design of our parents' generation.
What shaped me more than anything, though, was this oddball family of obsessives I found at Reading who could argue into the night about letterspacing and what we loved to call 'nitty-gritty' typography. I'd read about my jazz heroes practising for hours every day, and there was a romantic appeal to learning that my favourite drummer lived in a bedsit with no more than a bed and a ride cymbal for furniture. Now I found real-life characters whose love for their subject led to similarly beguiling single-mindedness, confirming for me that you could become an adult and still play with trains.
I remember a privileged (for an undergraduate) invitation to a meeting of these minds, where the classification of fonts in the new digital world became the subject of an abstract and ideological study, trying to adapt the tools of statistical cluster analysis to the multidimensional field of graphic elements.
The parallels between musical and graphic communication run deep and wide. The language analogy is a powerful metaphor in both fields, and when we learned about synectics at Reading (thanks to a design client who evangelised the methodology) it chimed with an internal conviction that everything connected, and there was nothing that couldn't inform my journey as a musician as much as a designer.
Department of Typography & Graphic Communication, University of Reading, early 1980s. Photographs from the collection of Rick Finlay.
I left Reading at the moment the desktop publishing revolution swept away hot metal, hand-rendered roughs and copyfitting tables. Another inspiring tutor on the course, Richard Southall, somehow managed to bring an early Apple Lisa into the building for a week or two, and for us it was like some kind of time machine.
The democratisation of the means of design and production the Lisa portended weighed heavily on the senior brains of the department. The whole postwar conviction that typographic design could be a force for social and political change was threatened by the ease with which the powerful arsenal of fonts and printing could fall into the wrong hands. It seemed that all we were learning about could be unstitched.
And it's true that there was a proliferation of awful design in the early years.
But we never imagined that a consequence of this would be an awareness and appreciation of, and interest in, typography which would lead to the minor cinematic success of Gary Hustwit's film Helvetica (reviewed in Eye 64), or the mass-audience popularity of Simon Garfield's book Just My Type (reviewed in Eye 78).
An exactly parallel process was developing in music at the same time: home recording and computerised music production were becoming available, and as I entered the music business I recoiled at the horrors of thousands of dabblers in music churning out soulless and meaningless music at near-professional quality. And yet a similar coming of age has happened: almost all musicians, from the hobbyist to the big-name celebrity, use the kind of tools that were once only available in top-notch recording studios to develop their ideas at home.
I still practise my now-creaking typographic skills in designing album covers, websites and promotional materials for my band, and teaching materials for my drum students. But it is in the management of business and musical relationships that I draw on the rich and diverse knowledge imparted at Reading.
Whether communicating through my percussion instruments on a gig, negotiating with European promoters, or debating in the boardroom of the Musicians' Union, I reference skills first acquired 30 years ago. This was a proper university education, not about vocation but about raw knowledge and research, and their applicability to whatever life throws at you.
I could mention Ernest Hoch opening the doors of systems analysis to me. Or postgraduate student Robin Kinross (see 'Reputations', Eye 80) producing Potter's What Is a Designer on his Hyphen Press imprint – the publishing equivalent of the punk independent record label. Or Michael Twyman's alchemical conversion of ephemeral typography to gold.
But perhaps the abiding memory is of Paul Stiff's lectures, on anything and everything, unfolding like the best Miles Davis solo, turning the lecture room into a jazz club and the audience into devoted fans.
Rick Finlay is a drummer and a member of Just East.
Read Paul Stiff's 'The way ahead' in Eye 78. Also, 'Strategies for telling truths' from Eye 25 and 'Stop sitting around and start reading', Eye 11.
Eye is the world's most beautiful and collectable graphic design journal, published quarterly for professional designers, students and anyone interested in critical, informed writing about graphic design and visual culture. It is available from all good design bookshops and online at the Eye shop, where you can buy subscriptions, back issues and single copies of the latest issue. You can see what Eye 84 looks like at Eye before You Buy on Vimeo.
Department of Typography & Graphic Communication at the University of Reading, UK
Just East website
Just East manifesto
Buy Eye
Purchase single issues, back issues or subscribe online now.
Change the rules of the game
Books received #39
(Typographic) Noted #92
Spirit of the Paraná
Awards madness
Brand madness
Design history
Type Tuesday
January (3) February (3) March (3) April (2) May (7) June (4) July (3) January (4) February (4) March (3) April (3) May (4) June (2) July (4) August (5) September (3) October (3) November (4) December (3) January (4) February (3) March (2) April (4) May (4) June (4) July (3) August (3) September (5) October (4) November (5) December (4) January (5) February (3) March (5) April (5) May (5) June (6) July (2) August (6) September (5) October (6) November (3) December (6) January (3) February (7) March (9) April (4) May (5) June (7) July (5) August (7) September (5) October (3) November (4) December (7) January (6) February (7) March (7) April (8) May (9) June (3) July (6) August (3) September (7) October (5) November (4) December (5) January (13) February (11) March (10) April (11) May (10) June (10) July (14) August (9) September (9) October (13) November (6) December (8) January (21) February (18) March (19) April (17) May (23) June (14) July (16) August (14) September (9) October (17) November (14) December (11) January (15) February (17) March (17) April (19) May (19) June (20) July (21) August (24) September (23) October (24) November (22) December (16) January (22) February (16) March (19) April (19) May (15) June (17) July (18) August (16) September (15) October (18) November (19) December (18) January (13) February (10) March (12) April (23) May (14) June (14) July (22) August (18) September (21) October (29) November (25) December (20) July (6) August (11) September (17) October (20) November (12) December (17)

redpajama_set_name: RedPajamaCommonCrawl


Fitch Upgrades Indonesia to 'BBB'; Outlook Stable – Embassy of the Republic of Indonesia | Washington D.C.
Fitch Ratings-Hong Kong-20 December 2017: Fitch Ratings has upgraded Indonesia's Long-Term Foreign- and Local-Currency Issuer Default Ratings (IDR) to 'BBB', from 'BBB-'. The Outlook is Stable.
Indonesia's resilience to external shocks has steadily strengthened in the past few years, as macroeconomic policies have consistently been geared towards maintaining stability. A more flexible exchange-rate policy since mid-2013 has helped foreign reserve buffers swell to USD126 billion as at November 2017, reaching seven months of current account payments, compared with the 'BBB' median of six months. Moreover, monetary policy has been sufficiently disciplined to limit bouts of volatile capital outflows during challenging periods. Macro-prudential measures have helped curb a sharp rise in corporate external debt, while financial deepening has coincided with improved market stability. The focus on macro stability is also evident in credible budget assumptions in the previous few years.
Indonesia's resilience has improved, but external challenges remain, including potential emerging market pressure in the context of the US Federal Reserve's policy normalisation. Indonesia's dependence on commodities remains relatively high and both its net and gross external debt (166% of current account receipts; 'BBB' median: 130%) remain elevated compared with 'BBB' peers. Domestically, the possibility that political noise becomes a distraction from economic policy-making in the run up to the 2018 local elections and 2019 presidential election represents a risk to the strong reform drive and could undermine domestic and foreign market sentiment, although such an outcome is not Fitch's base case.
The government's concerted structural reform drive is improving a still-challenging business environment. Implementation of measures to reduce business procedural and permit requirements have sharply improved Indonesia's position in the World Bank's Ease of Doing Business ranking to 72nd out of 190 countries; a rise of 37 places in two years. The reforms also seem to be contributing to stronger external finances, with foreign direct investment (FDI) picking up in recent quarters to such an extent that Fitch expects net FDI to cover the current account deficit over the next few years.


text:
Carla Hills
Two-Time Cabinet Member, Business Executive, and Renowned Expert on International Trade, Commerce, and Investment
Emerging Market | Business - Management, Leadership | International Business | Economy - Finance | Women in Business, Finance | International Affairs - Business | Female Political | Social Issues | CEO | Women on the Platform | Global Economy | Asia
Carla Hills Bio
Two-Time Cabinet Member, Business Executive, and
Renowned Expert on International Trade, Commerce,
and Investment
As the third woman to hold a cabinet position, Carla Hills knows what it is like to overcome barriers with spirit, candor, and business savvy. Since then, she has become one of the world's most influential voices on international trade, commerce, and investment. She has also played a key role in negotiating some of the world's most defining trade agreements, still holding firm today. Her presentations draw on the many lessons and experiences from her long and storied career.
Carla first passed the bar in California to become Assistant United States Attorney in Los Angeles from 1959 to 1961. She continued to climb higher as a co-founder and partner at Munger, Tolles, Hills, and Rickershauser from 1962 to 1974, and an adjunct professor at UCLA teaching antitrust law. Through these experiences, she had already become an authority on federal practice and antitrust law, writing Federal Civil Practice and co-authoring the Antitrust Advisor, which was published by McGraw-Hill. As testament to her understanding of business, she went on to achieve the title of United States Assistant Attorney General, heading the Civil Division of the U.S Department of Justice, and was then named secretary of the Department of Housing and Urban Development, the third woman to hold a cabinet position. Despite lacking in relevant experience, she made such a high impression that President Ford referred to her as an exceptionally effective advocate for HUD and even listed her as a candidate for U.S Supreme Court Justice.
U.S. Trade Representative
Carla served as United States Trade Representative from 1989 to 1993. As a member of President Bush's Cabinet, she was the President's principal advisor on international trade policy. She was also the nation's chief trade negotiator, representing American interests in multilateral and bilateral trade negotiations throughout the world. Carla was the primary U.S negotiator on the North American Free Trade Agreement and also led U.S negotiations on the Uruguay Round of the World Trade Organization. She then joined the Task Force on the Future of North America, contributing to a report that advocated greater coherence and integration in North American Trade. Carla was even awarded the Aztec Eagle, the highest honor given by the Mexican government to non-citizens. Ultimately, Carla's tenure led to the U.S. entering into numerous trade and investment agreements with countries around the world.
Carla has also held many other distinguished positions of high office, serving on the board of directors for AIG, AT&T, Chevron, Gilead Sciences, Time Warner, IBM, and United Airlines, among others. She has been an international advisor to Yale and is an executive committee member of the Peterson Institute and Trilateral Commission. She was also one of the founders, and now a trustee, of the Forum for International Policy. On top of this impressive list of connections, Carla works as a consultant and public speaker through her own firm, Hills & Company International Consultants, in which she is Chairman and CEO. She currently serves on various international advisory boards, such as the American International Group, The Coca-Cola Company, J.P Morgan Chase, and Rolls Royce. While evidenced as an expert in many subjects, she maintains a specialty on China, as Chair of the National Committee on US-China Relations, advisory board member to the National Bureau of Asian Research, and Co-chair of the Council on Foreign Relations.
Doing Business in a Global Environment
Expanding beyond the confines of national borders is one of the most difficult tasks for a business to undertake. That is truer today than ever before with a whole array of challenges to global success, including tariffs, border restrictions, and national regulations. And on top of these conventional issues, ever-changing foreign policies and the rapid advancement of technology ensures that business leaders always need to stay one step ahead of the game. To help understand and face these challenges, there is perhaps no better guide than Carla Hills, a former U.S Trade Representative, respected founder of a national law firm and global advisory consultancy, and member of a multitude of Fortune 500 companies. She can provide just the insight that business leaders need to move into the global market and successfully manage the balancing act of business and politics.
NAFTA and North America's Untapped Economic Opportunities
Since the signing of the North American Free Trade Agreement, and the creation of a trilateral trade bloc between the United States, Canada, and Mexico, these three territories have received a mutually beneficial boost to their economies that continue to hold firm to this day. NAFTA remains one of the world's leading examples on how this kind of international cooperation should be handled and it is in our national interest to see it continue to prosper and evolve. As America's original NAFTA negotiator, Carla Hills provides unique insight into how this agreement came to be and how it has become such a key structure in producing, selling, and trading between the nations. She also offers her advice on how to handle the issues they currently face and to move forward in a way that will continue to benefit not just the U.S, but all of North America for decades to come.
Preserving the Benefits of Trade and Globalization
While political rhetoric in the U.S has turned increasingly hostile towards the notion of trade, it has proven to be a crucial factor in the prosperity of our economy, as well as that of our allies, helped billions out of poverty, and brought the world together on a range of important political issues. It is more important now than ever to showcase these benefits, while also addressing those who trade has not been wholly beneficial. This applies mainly to those in industries with rapidly-changing technologies, who face a deep-rooted and understandable anxiety towards the notion of open markets. Carla Hills brings her knowledge and experience as a former U.S Trade Representative and negotiator of NAFTA to educate the public on the benefits of trade, help those who face challenges, and ensure the continuation of open borders and an open market.
How to Work With China
As one of the largest superpowers in the world alongside the U.S, and one of the largest economies, a strong U.S-China is crucial to global prosperity. Unfortunately, China and the U.S have had more than their fair share of disagreements and mutual mistrust threatens to undermine any sense of cooperation. Both countries face considerable economic and political uncertainties as well, creating a challenging playing field to engage in. But with her wealth of experience as a chair member of several foreign relationship organizations, doing business inside Chinese borders, and recognized as one of the leading voices in U.S-China relations, Carla Hills offers her advice in breaching one of the world's largest markets and thriving through cooperation.
Art Laffer
Robyn Meredith
Ted Fishman
Check Carla Hills Availability


Delving deep into the archives, Wedgwood sources inspiration from collections of time gone by for the Wonderlust collection. Delicately crafted in fine bone china and edged with gold trim, this tray features a unique, decadent design in feminine florals with a hint of exoticism. Petite in size, place on bedside tables to display fine accessories and trinkets.


text:
//
//  quadTreeHalos.h
//  GLAMER
//
//  Created by Robert Benton Metcalf on 30/10/2020.
//

#ifndef quadTreeHalos_h
#define quadTreeHalos_h
/**
 * \brief TreeQuadHalo is a class for calculating the deflection, kappa and gamma by tree method.
 *
 * TreeQuadParticles is evolved from TreeSimple and TreeForce.  It splits each cell into four equal area
 * subcells instead of being a binary tree like TreeSimple.  When the "particles" are given sizes
 * the tree is built in such a way the large particles are stored in branches that are no smaller
 * than their size.  In this way particles are stored on all levels of the tree and not just in the
 * leaves.  This improves efficiency when particles of a wide range of sizes overlap in 2D.
 *
 * The default value of theta = 0.1 generally gives better than 1% accuracy on alpha.
 * The shear and kappa is always more accurate than the deflection.
 *
 */

/** \brief Class to calculate the deflection, etc. for a collection of LensHalos using a tree structure.

 */
template <typename LensHaloType>
class TreeQuadHalos {
public:
  TreeQuadHalos(
           LensHaloType **my_halos
           ,IndexType Npoints
           ,PosType my_sigma_background = 0
           ,int bucket = 5
           ,PosType theta_force = 0.1
           ,bool my_periodic_buffer = false
           ,PosType my_inv_screening_scale = 0
           ,PosType maximum_range  = -1
           );
  ~TreeQuadHalos();

  friend class LensPlaneTree;
  void force2D(PosType const *ray,PosType *alpha,KappaType *kappa,KappaType *gamma
                       ,KappaType *phi) const;

  void force2D_recur(const PosType *ray,PosType *alpha,KappaType *kappa
                             ,KappaType *gamma,KappaType *phi);

  /// find all points within rmax of ray in 2D
  void neighbors(PosType ray[],PosType rmax,std::list<IndexType> &neighbors) const;
  void neighbors(PosType ray[],PosType rmax,std::vector<LensHaloType *> &neighbors) const;

  void printParticlesInBranch(unsigned long number);

  void printBranchs(int level = -1);

protected:

  std::vector<PosType> workspace;
  PosType **xp;
  bool MultiMass;
  bool MultiRadius;
  //float *masses;
  //float *sizes;

  IndexType Nparticles;
  PosType sigma_background;
  int Nbucket;

  PosType force_theta;
  PosType max_range;

  QTreeNB<PosType *> * tree;
  std::vector<IndexType> index;

  //bool haloON;
  LensHaloType **halos;

  PosType realray[2];
  int incell,incell2;

  /// if true there is one layer of peridic buffering
  bool periodic_buffer;
  PosType inv_screening_scale2;
  PosType original_xl;  // x-axis size of simulation used for peridic buffering.  Requrement that it top branch be square my make it differ from the size of top branch.
  PosType original_yl;  // x-axis size of simulation used for peridic buffering.

  QTreeNB<PosType *> * BuildQTreeNB(PosType **xp,IndexType Nparticles,IndexType *particles);
  void _BuildQTreeNB(IndexType nparticles,IndexType *particles);

  inline short WhichQuad(PosType *x,QBranchNB &branch);

  //inline bool atLeaf();
  inline bool inbox(const PosType *ray,const PosType *p1,const PosType *p2){
    return (ray[0]>=p1[0])*(ray[0]<=p2[0])*(ray[1]>=p1[1])*(ray[1]<=p2[1]);
  }
  //int cutbox(PosType *ray,PosType *p1,PosType *p2,float rmax);

  void CalcMoments();
  void rotate_coordinates(PosType **coord);

  //QTreeNBHndl rotate_simulation(PosType **xp,IndexType Nparticles,IndexType *particles
  //                              ,PosType **coord,PosType theta,float *rsph,float *mass
  //                              ,bool MultiRadius,bool MultiMass);
  //QTreeNBHndl rotate_project(PosType **xp,IndexType Nparticles,IndexType *particles
  //                           ,PosType **coord,PosType theta,float *rsph,float *mass
  //                           ,bool MultiRadius,bool MultiMass);
  void cuttoffscale(QTreeNB<PosType *> * tree,PosType *theta);

  void walkTree_recur(QBranchNB *branch,PosType const *ray,PosType *alpha,KappaType *kappa,KappaType *gamma,KappaType *phi);
  void walkTree_iter(QBiterator<PosType *> &treeit, PosType const *ray,PosType *alpha,KappaType *kappa
                     ,KappaType *gamma,KappaType *phi) const;

  PosType phiintconst;

};

/** \brief Constructor meant for halos with internal structure parameters.  This is a protected constructor because
 * it should only be invoked from the derived classes that have specific defined halo models.
 */

template <typename LensHaloType>
TreeQuadHalos<LensHaloType>::TreeQuadHalos(
                   LensHaloType **my_halos     /// list of halos to be put in tree
                   ,IndexType Npoints          /// number of halos
                   ,PosType my_sigma_background /// background kappa that is subtracted
                   ,int bucket                  /// maximum number of halos in each leaf of the tree
                   ,PosType theta_force         /// the openning angle used in the criterion for decending into a subcell
                   ,bool periodic_buffer        /// if true a periodic buffer will be imposed in the force calulation.  See documentation on TreeQuadHalos::force2D() for details. See note for TreeQuadHalos::force2D_recur().
                   ,PosType my_inv_screening_scale   /// the inverse of the square of the sreening length. See note for TreeQuadHalos::force2D_recur().
                   ,PosType maximum_range  /// if set this will cause the tree not be fully construct down to the bucket size outside this range
):
MultiMass(true),MultiRadius(true)//,masses(NULL),sizes(NULL)
,Nparticles(Npoints),sigma_background(my_sigma_background),Nbucket(bucket)
,force_theta(theta_force),halos(my_halos),periodic_buffer(periodic_buffer)
,inv_screening_scale2(my_inv_screening_scale*my_inv_screening_scale)
,max_range(max_range)
{
  index.resize(Npoints);
  IndexType ii;

  for(ii=0;ii<Npoints;++ii) index[ii] = ii;

  // copy halo positions into xp array to make compatable with QTreeNB
  xp = Utilities::PosTypeMatrix(Npoints,2);
  for(ii=0;ii<Npoints;++ii) halos[ii]->getX(xp[ii]);

  if(Npoints > 0){
    tree = BuildQTreeNB(xp,Npoints,index.data());
    CalcMoments();
  }

  phiintconst = (120*log(2.) - 631.)/840 + 19./70;
  return;
}

/// Particle positions and other data are not destroyed.
template <typename LensHaloType>
TreeQuadHalos<LensHaloType>::~TreeQuadHalos()
{
  if(Nparticles == 0) return;
  delete tree;
  Utilities::free_PosTypeMatrix(xp,Nparticles,2);
  return;
}

template <typename LensHaloType>
QTreeNB<PosType *> * TreeQuadHalos<LensHaloType>::BuildQTreeNB(PosType **xp,IndexType Nparticles,IndexType *particles){
  IndexType i;
  short j;
  PosType p1[2],p2[2];

  for(j=0;j<2;++j){
    p1[j]=xp[0][j];
    p2[j]=xp[0][j];
  }

  // Find borders that enclose all particles
  for(i=0;i<Nparticles;++i){
    for(j=0;j<2;++j){
      if(xp[i][j] < p1[j] ) p1[j]=xp[i][j];
      if(xp[i][j] > p2[j] ) p2[j]=xp[i][j];
    }
  }

  if(Nparticles == 1){
    p1[0]=-0.25;
    p1[1]=-0.25;
    p2[0]=0.25;
    p2[1]=0.25;
  }

  // store true dimensions of simulation
  PosType lengths[2] = {p2[0]-p1[0],p2[1]-p1[1]};
  original_xl = lengths[0];
  original_yl = lengths[1];

  if(lengths[0] == 0 || lengths[1] == 0){
    throw std::invalid_argument("particles in same place.");
  }

  // If region is not square, make it square.
  j = lengths[0] > lengths[1] ? 1 : 0;
  p2[j] = p1[j] + lengths[!j];

  /* Initialize tree root */
  tree = new QTreeNB<PosType *>(xp,particles,Nparticles,p1,p2);

  /* build the tree */
  workspace.resize(Nparticles);
  _BuildQTreeNB(Nparticles,particles);
  workspace.clear();
  workspace.shrink_to_fit();

  /* visit every branch to find center of mass and cutoff scale */
  tree->moveTop();

  return tree;
}

/// returns an index for which of the four quadrangles of the branch the point x[] is in
template <typename LensHaloType>
inline short TreeQuadHalos<LensHaloType>::WhichQuad(PosType *x,QBranchNB &branch){
  return (x[0] < branch.center[0]) + 2*(x[1] < branch.center[1]);
}

/// tree must be created and first branch must be set before start
template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::_BuildQTreeNB(IndexType nparticles,IndexType *particles){

  QBranchNB *cbranch = tree->current; /* pointer to current branch */
  IndexType i,j,cut,cut2,jt;

  cbranch->center[0] = (cbranch->boundary_p1[0] + cbranch->boundary_p2[0])/2;
  cbranch->center[1] = (cbranch->boundary_p1[1] + cbranch->boundary_p2[1])/2;
  cbranch->quad[0]=cbranch->quad[1]=cbranch->quad[2]=0;
  cbranch->mass = 0.0;

  double theta_range = 2*force_theta;
  if(max_range > 0){
      double boxsize = 1.732*(cbranch->boundary_p2[0] - cbranch->boundary_p1[0]);
      theta_range = boxsize / MAX(sqrt(cbranch->center[0]*cbranch->center[0]
             + cbranch->center[1]*cbranch->center[1] )
             - max_range, boxsize );
  }

   // leaf case
   if(cbranch->nparticles <= Nbucket
      || force_theta > theta_range
    ){

    PosType r;
    cbranch->Nbig_particles = 0;
    for(i=0;i<cbranch->nparticles;++i){
      jt = particles[i]*MultiRadius;
      r = halos[jt]->get_Rmax();
      //r = haloON ? halos[particles[i]*MultiRadius].Rmax  : sizes[particles[i]*MultiRadius];
      if(r < (cbranch->boundary_p2[0]-cbranch->boundary_p1[0])) ++cbranch->Nbig_particles;
    }
    if(cbranch->Nbig_particles){
      //cbranch->big_particles = new IndexType[cbranch->Nbig_particles];
      cbranch->big_particles.reset( new IndexType[cbranch->Nbig_particles] );
      for(i=0,j=0;i<cbranch->nparticles;++i){
        jt = particles[i]*MultiRadius;
        r = halos[jt]->get_Rmax();
        //r = haloON ? halos[particles[i]*MultiRadius].Rmax  : sizes[particles[i]*MultiRadius];
        if(r < (cbranch->boundary_p2[0]-cbranch->boundary_p1[0])) cbranch->big_particles[j++] = particles[i];
      }
    }
    else{
      cbranch->big_particles.reset(nullptr);
    }

    return;
  }

  // find particles too big to be in children

  //PosType *x = new PosType[cbranch->nparticles];
  PosType *x = workspace.data();

  cbranch->Nbig_particles=0;

  if(MultiRadius){
    // store the particles that are too large to be in a child at the end of the list of particles in cbranch
    for(i=0;i<cbranch->nparticles;++i){
      x[i] = halos[particles[i]]->get_Rmax();
      //x[i] =  haloON ? halos[particles[i]].Rmax : sizes[particles[i]];
    }
    PosType maxsize = (cbranch->boundary_p2[0]-cbranch->boundary_p1[0])/2;

    // sort particles in size
    //quicksort(particles,x,cbranch->nparticles);
    Utilities::quickPartition(maxsize,&cut,particles,x,cbranch->nparticles);

    if(cut < cbranch->nparticles){
      if(tree->atTop()){
        cbranch->Nbig_particles = cut2 = cbranch->nparticles-cut;
      }else{
        Utilities::quickPartition(2*maxsize,&cut2,&particles[cut],&x[cut],cbranch->nparticles-cut);
        cbranch->Nbig_particles = cut2;
      }

      //cbranch->big_particles = new IndexType[cbranch->Nbig_particles];
      cbranch->big_particles.reset( new IndexType[cbranch->Nbig_particles] );
      for(i=cut;i<(cut+cut2);++i) cbranch->big_particles[i-cut] = particles[i];
    }

  }else{
    x[0] = halos[0]->get_Rmax();
    //x[0] =  haloON ? halos[0].Rmax : sizes[0];
    if(x[0] > (cbranch->boundary_p2[0]-cbranch->boundary_p1[0])/2
       && x[0] < (cbranch->boundary_p2[0]-cbranch->boundary_p1[0])){
      cbranch->Nbig_particles = cbranch->nparticles;
      //cbranch->big_particles = cbranch->particles;
      cbranch->big_particles.reset( new IndexType[cbranch->Nbig_particles] );
      for(i=0;i<cbranch->Nbig_particles;++i) cbranch->big_particles[i] = particles[i];

    }
  }

  assert( cbranch->nparticles >= cbranch->Nbig_particles );
  IndexType NpInChildren = cbranch->nparticles;// - cbranch->Nbig_particles;
  assert(NpInChildren >= 0);

  if(NpInChildren == 0){
    //delete[] x;
    return;
  }

  IndexType cutx,cuty;
  PosType xcut,ycut;

  QBranchNB *child0 = new QBranchNB(cbranch);
  QBranchNB *child1 = new QBranchNB(cbranch);
  QBranchNB *child2 = new QBranchNB(cbranch);
  QBranchNB *child3 = new QBranchNB(cbranch);

  tree->attachChildrenToCurrent(child0,child1,child2,child3);

  // initialize boundaries of children

  child0->boundary_p1[0]=cbranch->center[0];
  child0->boundary_p1[1]=cbranch->center[1];
  child0->boundary_p2[0]=cbranch->boundary_p2[0];
  child0->boundary_p2[1]=cbranch->boundary_p2[1];

  child1->boundary_p1[0]=cbranch->boundary_p1[0];
  child1->boundary_p1[1]=cbranch->center[1];
  child1->boundary_p2[0]=cbranch->center[0];
  child1->boundary_p2[1]=cbranch->boundary_p2[1];

  child2->boundary_p1[0]=cbranch->center[0];
  child2->boundary_p1[1]=cbranch->boundary_p1[1];
  child2->boundary_p2[0]=cbranch->boundary_p2[0];
  child2->boundary_p2[1]=cbranch->center[1];

  child3->boundary_p1[0]=cbranch->boundary_p1[0];
  child3->boundary_p1[1]=cbranch->boundary_p1[1];
  child3->boundary_p2[0]=cbranch->center[0];
  child3->boundary_p2[1]=cbranch->center[1];

  // **** makes sure force does not require nbucket at leaf

  xcut = cbranch->center[0];
  ycut = cbranch->center[1];

  // divide along y direction
  for(i=0;i<NpInChildren;++i) x[i] = tree->xxp[particles[i]][1];
  Utilities::quickPartition(ycut,&cuty,particles,x,NpInChildren);

  if(cuty > 0){
    // divide first group in the x direction
    for(i=0;i<cuty;++i) x[i] = tree->xxp[particles[i]][0];
    Utilities::quickPartition(xcut,&cutx,particles,x,cuty);

    child3->nparticles=cutx;
    assert(child3->nparticles >= 0);
    if(child3->nparticles > 0)
      child3->particles = particles;
    else child3->particles = NULL;

    child2->nparticles = cuty - cutx;
    assert(child2->nparticles >= 0);
    if(child2->nparticles > 0)
      child2->particles = &particles[cutx];
    else child2->particles = NULL;

  }else{
    child3->nparticles = 0;
    child3->particles = NULL;

    child2->nparticles = 0;
    child2->particles = NULL;
  }

  if(cuty < NpInChildren){
    // divide second group in the x direction
    for(i=cuty;i<NpInChildren;++i) x[i-cuty] = tree->xxp[particles[i]][0];
    Utilities::quickPartition(xcut,&cutx,&particles[cuty],x,NpInChildren-cuty);

    child1->nparticles=cutx;
    assert(child1->nparticles >= 0);
    if(child1->nparticles > 0)
      child1->particles = &particles[cuty];
    else child1->particles = NULL;

    child0->nparticles=NpInChildren - cuty - cutx;
    assert(child0->nparticles >= 0);
    if(child0->nparticles > 0)
      child0->particles = &particles[cuty + cutx];
    else child0->particles = NULL;

  }else{
    child1->nparticles = 0;
    child1->particles = NULL;

    child0->nparticles = 0;
    child0->particles = NULL;
  }

  //delete[] x;

  tree->moveToChild(0);
  _BuildQTreeNB(child0->nparticles,child0->particles);
  tree->moveUp();

  tree->moveToChild(1);
  _BuildQTreeNB(child1->nparticles,child1->particles);
  tree->moveUp();

  tree->moveToChild(2);
  _BuildQTreeNB(child2->nparticles,child2->particles);
  tree->moveUp();

  tree->moveToChild(3);
  _BuildQTreeNB(child3->nparticles,child3->particles);
  tree->moveUp();

  return;
}

// calculates moments of the mass and the cutoff scale for each box
template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::CalcMoments(){

  //*** make compatable
  IndexType i;
  PosType rcom,xcm[2],xcut;
  QBranchNB *cbranch;
  PosType tmp;

  tree->moveTop();
  do{
    cbranch=tree->current; /* pointer to current branch */

    cbranch->rmax = sqrt( pow(cbranch->boundary_p2[0]-cbranch->boundary_p1[0],2)
                         + pow(cbranch->boundary_p2[1]-cbranch->boundary_p1[1],2) );

    // calculate mass
    for(i=0,cbranch->mass=0;i<cbranch->nparticles;++i)
        cbranch->mass +=  halos[cbranch->particles[i]]->get_mass();
     //cbranch->mass +=  haloON ? halos[cbranch->particles[i]*MultiMass].mass : masses[cbranch->particles[i]*MultiMass];

    // calculate center of mass
    cbranch->center[0]=cbranch->center[1]=0;
    for(i=0;i<cbranch->nparticles;++i){
        tmp = halos[cbranch->particles[i]]->get_mass();
       //tmp = haloON ? halos[cbranch->particles[i]*MultiMass].mass : masses[cbranch->particles[i]*MultiMass];
      cbranch->center[0] += tmp*tree->xxp[cbranch->particles[i]][0]/cbranch->mass;
      cbranch->center[1] += tmp*tree->xxp[cbranch->particles[i]][1]/cbranch->mass;
    }
    //////////////////////////////////////////////
    // calculate quadropole moment of branch
    //////////////////////////////////////////////
    cbranch->quad[0]=cbranch->quad[1]=cbranch->quad[2]=0;
    for(i=0;i<cbranch->nparticles;++i){
      xcm[0]=tree->xxp[cbranch->particles[i]][0]-cbranch->center[0];
      xcm[1]=tree->xxp[cbranch->particles[i]][1]-cbranch->center[1];
      xcut = pow(xcm[0],2) + pow(xcm[1],2);

      tmp = halos[cbranch->particles[i]]->get_mass();

      cbranch->quad[0] += (xcut-2*xcm[0]*xcm[0])*tmp;
      cbranch->quad[1] += (xcut-2*xcm[1]*xcm[1])*tmp;
      cbranch->quad[2] += -2*xcm[0]*xcm[1]*tmp;
    }

    // largest distance from center of mass of cell
    for(i=0,rcom=0.0;i<2;++i) rcom += ( pow(cbranch->center[i]-cbranch->boundary_p1[i],2) > pow(cbranch->center[i]-cbranch->boundary_p2[i],2) ) ?
      pow(cbranch->center[i]-cbranch->boundary_p1[i],2) : pow(cbranch->center[i]-cbranch->boundary_p2[i],2);

    rcom=sqrt(rcom);

    if(force_theta > 0.0) cbranch->rcrit_angle = 1.15470*rcom/(force_theta);
    else  cbranch->rcrit_angle=1.0e100;

  }while(tree->WalkStep(true));

  return;
}

/// simple rotates the coordinates in the xp array
template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::rotate_coordinates(PosType **coord){
  IndexType i;
  short j;
  PosType tmp[3];

  /* rotate particle positions */
  for(i=0;i<tree->top->nparticles;++i){
    for(j=0;j<3;++j) tmp[j]=0.0;
    for(j=0;j<3;++j){
      tmp[0]+=coord[0][j]*xp[i][j];
      tmp[1]+=coord[1][j]*xp[i][j];
      tmp[2]+=coord[2][j]*xp[i][j];
    }
    for(j=0;j<3;++j) xp[i][j]=tmp[j];
  }

  return;
}

/** \brief Force2D calculates the defection, convergence and shear using
 *   the plane-lens approximation.  The tree is walked iteratively.
 *
 *       The output alpha[] is in units of mass_scale/Mpc, ie it needs to be
 *       divided by Sigma_crit and multiplied by mass_scale to be the deflection
 *       in the lens equation expressed on the lens plane or multiplied by
 *       4*pi*G*mass_scale to get the deflection angle caused by the plane lens.
 *
 *       kappa and gamma need to by multiplied by mass_scale/Sigma_crit to get
 *       the traditional units for these where Sigma_crit are in the mass/units(ray)^2
 *       NB : the units of sigma_backgound need to be mass/units(ray)^2
 *
 *   If periodic_buffer == true a periodic buffer is included.  The ray is calculated as if there
 *   where identical copies of it on the borders of the tree's root branch.  This is not the same thing as periodic boundary conditions, because
 *   there are not an infinite number of copies in all direction as for the DFT force solver.
 *
 *   If inv_screening_scale2 != 0 the mass of cells are reduced by a factor of exp(-|ray - center of mass|^2*inv_screening_scale2) which
 *   screens the large scale geometry of the simulation on the sky.  This is useful when the region is rectangular instead of circular.
 * */
template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::force2D(const PosType *ray,PosType *alpha,KappaType *kappa,KappaType *gamma,KappaType *phi) const{

  alpha[0]=alpha[1]=gamma[0]=gamma[1]=gamma[2]=0.0;
  *kappa=*phi=0.0;

  if(Nparticles == 0) return;

  assert(tree);
  //QTreeNB<PosType *>::iterator it(tree);
  QBiterator<PosType *> it(tree);

  if(periodic_buffer){
    PosType tmp_ray[2];

    for(int i = -1;i<2;++i){
      for(int j = -1;j<2;++j){
        tmp_ray[0] = ray[0] + i*original_xl;
        tmp_ray[1] = ray[1] + j*original_yl;
        walkTree_iter(it,tmp_ray,alpha,kappa,gamma,phi);
      }
    }
  }else{
    walkTree_iter(it,ray,alpha,kappa,gamma,phi);
  }

  // Subtract off uniform mass sheet to compensate for the extra mass
  //  added to the universe in the halos.
  alpha[0] -= ray[0]*sigma_background*(inv_screening_scale2 == 0);
  alpha[1] -= ray[1]*sigma_background*(inv_screening_scale2 == 0);

  *kappa -= sigma_background;

  return;
}

/** \brief Returns the halos that are within rmax of ray[]
 */
template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::neighbors(PosType ray[],PosType rmax,std::list<IndexType> &neighbors) const{
  //QTreeNB::iterator it(tree);
  QBiterator<PosType *> it(tree);

  neighbors.clear();

  PosType r2 = rmax*rmax;
  bool decend=true;
  it.movetop();
  do{
    int cut = Utilities::cutbox(ray,(*it)->boundary_p1,(*it)->boundary_p2,rmax);
    decend = true;

    if(cut == 0){      // box outside circle
      decend = false;
    }else if(cut == 1){  // whole box inside circle
      for(int i=0;i<(*it)->nparticles;++i) neighbors.push_back((*it)->particles[i]);
      decend = false;
    }else if((*it)->child0 == NULL){  // at leaf
      for(int i=0;i<(*it)->nparticles;++i){
        if( (tree->xxp[(*it)->particles[i]][0] - ray[0])*(tree->xxp[(*it)->particles[i]][0] - ray[0])
           + (tree->xxp[(*it)->particles[i]][1] - ray[1])*(tree->xxp[(*it)->particles[i]][1] - ray[1]) < r2) neighbors.push_back((*it)->particles[i]);
      }
      decend = false;
    }
  }while(it.TreeWalkStep(decend));

}
/** \brief Returns the halos that are within rmax of ray[]
 */
template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::neighbors(PosType ray[],PosType rmax,std::vector<LensHaloType *> &neighbors) const{
  neighbors.clear();

  if(halos == NULL){
    std::cerr << "TreeQuadHalos<LensHaloType>::neighbors - The are no halos in this tree use other version of this function" << std::endl;
    throw std::runtime_error("no halos");
    return;
  }

  std::list<IndexType> neighbor_indexes;
  TreeQuadHalos<LensHaloType>::neighbors(ray,rmax,neighbor_indexes);

  neighbors.resize(neighbor_indexes.size());
  std::list<IndexType>::iterator it = neighbor_indexes.begin();
  for(size_t i=0;i<neighbors.size();++i,++it){
    neighbors[i] = halos[*it];
  }

  return;
}

template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::walkTree_iter(
                             QBiterator<PosType *> &treeit,
                             const PosType *ray
                             ,PosType *alpha
                             ,KappaType *kappa
                             ,KappaType *gamma
                             ,KappaType *phi
                             ) const {

  PosType xcm[2],rcm2cell,rcm2,tmp,boxsize2;
  IndexType i;
  bool allowDescent=true;
  unsigned long count=0,tmp_index;
  PosType prefac;
  //bool notscreen = true;

  assert(tree);

  treeit.movetop();
  //tree->moveTop();
  do{
    ++count;
    allowDescent=false;

    /*
     if(inv_screening_scale2 != 0) notscreen = BoxIntersectCircle(ray,3*sqrt(1.0/inv_screening_scale2)
     ,(*treeit)->boundary_p1
     ,(*treeit)->boundary_p2);
     else notscreen = true;
     */
    //if(tree->current->nparticles > 0)
    if((*treeit)->nparticles > 0)
    {

      xcm[0]=(*treeit)->center[0]-ray[0];
      xcm[1]=(*treeit)->center[1]-ray[1];

      rcm2cell = xcm[0]*xcm[0] + xcm[1]*xcm[1];

      boxsize2 = ((*treeit)->boundary_p2[0]-(*treeit)->boundary_p1[0])*((*treeit)->boundary_p2[0]-(*treeit)->boundary_p1[0]);

      if( rcm2cell < ((*treeit)->rcrit_angle)*((*treeit)->rcrit_angle) || rcm2cell < 5.83*boxsize2)
      {

        // includes rcrit_particle constraint
        allowDescent=true;

        // Treat all particles in a leaf as a point particle
        if(treeit.atLeaf())
        {

          for(i = 0 ; i < (*treeit)->nparticles ; ++i)
          {

            xcm[0] = tree->xxp[(*treeit)->particles[i]][0] - ray[0];
            xcm[1] = tree->xxp[(*treeit)->particles[i]][1] - ray[1];

            rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];
            double screening = exp(-rcm2*inv_screening_scale2);
            if(rcm2 < 1e-20) rcm2 = 1e-20;

            tmp_index = MultiMass*(*treeit)->particles[i];

            prefac = halos[tmp_index]->get_mass();
            prefac /= rcm2*PI/screening;

            tmp = -1.0*prefac;

            alpha[0] += tmp*xcm[0];
            alpha[1] += tmp*xcm[1];

            tmp = -2.0*prefac/rcm2;

            gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
            gamma[1] += xcm[0]*xcm[1]*tmp;

            *phi += prefac*rcm2*0.5*log(rcm2);

          } // end of for
        } // end of if(tree->atLeaf())

        // Find the particles that intersect with ray and add them individually.
        if(rcm2cell < 5.83*boxsize2)
        {

          for(i = 0 ; i < (*treeit)->Nbig_particles ; ++i)
          {

            tmp_index = (*treeit)->big_particles[i];

            xcm[0] = tree->xxp[tmp_index][0] - ray[0];
            xcm[1] = tree->xxp[tmp_index][1] - ray[1];

            rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];

            double screening = exp(-rcm2*inv_screening_scale2);
            halos[tmp_index]->force_halo(alpha,kappa,gamma,phi,xcm,true,screening);
           }
        }

      }
      else
      { // use whole cell

        allowDescent=false;

        double screening = exp(-rcm2cell*inv_screening_scale2);
        double tmp = -1.0*(*treeit)->mass/rcm2cell/PI*screening;

        alpha[0] += tmp*xcm[0];
        alpha[1] += tmp*xcm[1];

        {      //  taken out to speed up
          tmp=-2.0*(*treeit)->mass/PI/rcm2cell/rcm2cell*screening;
          gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
          gamma[1] += xcm[0]*xcm[1]*tmp;

          *phi += 0.5*(*treeit)->mass*log( rcm2cell )/PI*screening;
          *phi -= 0.5*( (*treeit)->quad[0]*xcm[0]*xcm[0] + (*treeit)->quad[1]*xcm[1]*xcm[1] + 2*(*treeit)->quad[2]*xcm[0]*xcm[1] )/(PI*rcm2cell*rcm2cell)*screening;
        }

        // quadrapole contribution
        //   the kappa and gamma are not calculated to this order
        alpha[0] -= ((*treeit)->quad[0]*xcm[0] + (*treeit)->quad[2]*xcm[1])
        /(rcm2cell*rcm2cell)/PI*screening;
        alpha[1] -= ((*treeit)->quad[1]*xcm[1] + (*treeit)->quad[2]*xcm[0])
        /(rcm2cell*rcm2cell)/PI*screening;

        tmp = 4*((*treeit)->quad[0]*xcm[0]*xcm[0] + (*treeit)->quad[1]*xcm[1]*xcm[1]
                 + 2*(*treeit)->quad[2]*xcm[0]*xcm[1])/(rcm2cell*rcm2cell*rcm2cell)/PI*screening;

        alpha[0] += tmp*xcm[0];
        alpha[1] += tmp*xcm[1];

      }
    }
  }while(treeit.TreeWalkStep(allowDescent));

  // Subtract off uniform mass sheet to compensate for the extra mass
  //  added to the universe in the halos.
  alpha[0] -= ray[0]*sigma_background*(inv_screening_scale2 == 0.0);
  alpha[1] -= ray[1]*sigma_background*(inv_screening_scale2 == 0.0);
  {      //  taken out to speed up
    *kappa -= sigma_background;
    // *phi -= sigma_background * sigma_background ;
  }

  return;
}

/** \brief Force2D_recur calculates the defection, convergence and shear using
 *   the plane-lens approximation.
 *
 *  This function should do the same work as TreeQuadHalos::force2D() except it is
 *  done recursively instead of iteratively.  This is done to enable multi-threading
 *  of the force calculation.
 *
 *       The output alpha[] is in units of mass_scale/Mpc, ie it needs to be
 *       divided by Sigma_crit and multiplied by mass_scale to be the deflection
 *       in the lens equation expressed on the lens plane or multiplied by
 *       4*pi*G*mass_scale to get the deflection angle caused by the plane lens.
 *
 *       kappa and gamma need to by multiplied by mass_scale/Sigma_crit to get
 *       the traditional units for these where Sigma_crit are in the mass/units(ray)^2
 *       NB : the units of sigma_backgound need to be mass/units(ray)^2
 *
 *   If periodic_buffer == true a periodic buffer is included.  The ray is calculated as if there
 *   where identical copies of it on the borders of the tree's root branch.  This is not the same thing as periodic boundary conditions, because
 *   there are not an infinite number of copies in all direction as for the DFT force solver.
 *
 *   If inv_screening_scale2 != 0 the mass of cells are reduced by a factor of exp(-|ray - center of mass|^2*inv_screening_scale2) which
 *   screens the large scale geometry of the simulation on the sky.  This is useful when the region is rectangular instead of circular.
 * */

template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::force2D_recur(const PosType *ray,PosType *alpha,KappaType *kappa,KappaType *gamma,KappaType *phi){

  alpha[0]=alpha[1]=gamma[0]=gamma[1]=gamma[2]=0.0;
  *kappa=*phi=0.0;

  if(Nparticles == 0) return;
  assert(tree);

  //walkTree_recur(tree->top,ray,&alpha[0],kappa,&gamma[0],phi);

  if(periodic_buffer){
    PosType tmp_ray[2],tmp_c[2];

    // for points outside of primary zone shift to primary zone
    //if(inbox(ray,tree->top->boundary_p1,tree->top->boundary_p2)){
    tmp_c[0] = ray[0];
    tmp_c[1] = ray[1];
    /*}else{
     int di[2];
     PosType center[2] = { (tree->top->boundary_p1[0] + tree->top->boundary_p2[0])/2 ,
     (tree->top->boundary_p1[1] + tree->top->boundary_p2[1])/2 };

     di[0] = (int)( 2*(ray[0] - center[0])/lx );
     di[1] = (int)( 2*(ray[1] - center[1])/ly );

     di[0] = (di[0] > 0) ? (di[0] + 1)/2 : (di[0] - 1)/2;
     di[1] = (di[1] > 0) ? (di[1] + 1)/2 : (di[1] - 1)/2;

     tmp_c[0] = ray[0] - lx * di[0];
     tmp_c[1] = ray[1] - ly * di[1];

     assert(inbox(tmp_c,tree->top->boundary_p1,tree->top->boundary_p2));
     }*/

    for(int i = -1;i<2;++i){
      for(int j = -1;j<2;++j){
        tmp_ray[0] = tmp_c[0] + i*original_xl;
        tmp_ray[1] = tmp_c[1] + j*original_yl;
        walkTree_recur(tree->top,tmp_ray,alpha,kappa,gamma,phi);
      }
    }
  }else{
    walkTree_recur(tree->top,ray,alpha,kappa,gamma,phi);
  }

  // Subtract off uniform mass sheet to compensate for the extra mass
  //  added to the universe in the halos.
  alpha[0] -= ray[0]*sigma_background*(inv_screening_scale2 == 0);
  alpha[1] -= ray[1]*sigma_background*(inv_screening_scale2 == 0);

  *kappa -= sigma_background;

  return;
}

template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::walkTree_recur(QBranchNB *branch,PosType const *ray,PosType *alpha,KappaType *kappa,KappaType *gamma, KappaType *phi){

  PosType xcm[2],rcm2cell,rcm2,tmp,boxsize2;
  IndexType i;
  std::size_t tmp_index;
  PosType prefac;
  /*bool notscreen = true;

   if(inv_screening_scale2 != 0) notscreen = BoxIntersectCircle(ray,3*sqrt(1.0/inv_screening_scale2), branch->boundary_p1, branch->boundary_p2);
   */
  if(branch->nparticles > 0)
  {
    xcm[0]=branch->center[0]-ray[0];
    xcm[1]=branch->center[1]-ray[1];

    rcm2cell = xcm[0]*xcm[0] + xcm[1]*xcm[1];

    boxsize2 = (branch->boundary_p2[0]-branch->boundary_p1[0])*(branch->boundary_p2[0]-branch->boundary_p1[0]);

    if( rcm2cell < (branch->rcrit_angle)*(branch->rcrit_angle) || rcm2cell < 5.83*boxsize2)
    {

      // Treat all particles in a leaf as a point particle
      if(tree->atLeaf(branch))
      {

        for(i = 0 ; i < branch->nparticles ; ++i){

          xcm[0] = tree->xxp[branch->particles[i]][0] - ray[0];
          xcm[1] = tree->xxp[branch->particles[i]][1] - ray[1];

          rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];
          double screening = exp(-rcm2*inv_screening_scale2);
          if(rcm2 < 1e-20) rcm2 = 1e-20;

          tmp_index = MultiMass*branch->particles[i];

          prefac = halos[tmp_index]->get_mass();
          prefac /= rcm2*PI/screening;

          alpha[0] += -1.0*prefac*xcm[0];
          alpha[1] += -1.0*prefac*xcm[1];

          {
            tmp = -2.0*prefac/rcm2;

            gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
            gamma[1] += xcm[0]*xcm[1]*tmp;

            *phi += prefac*rcm2*0.5*log(rcm2);
          }
        }
      }

      // Find the particles that intersect with ray and add them individually.
      if(rcm2cell < 5.83*boxsize2)
      {

        for(i = 0 ; i < branch->Nbig_particles ; ++i)
        {

          tmp_index = branch->big_particles[i];

          xcm[0] = tree->xxp[tmp_index][0] - ray[0];
          xcm[1] = tree->xxp[tmp_index][1] - ray[1];
          rcm2 = xcm[0]*xcm[0] + xcm[1]*xcm[1];

          /////////////////////////////////////////
          double screening = exp(-rcm2*inv_screening_scale2);
          halos[tmp_index]->force_halo(alpha,kappa,gamma,phi,xcm,true,screening);
        }
      }

      if(branch->child0 != NULL)
        walkTree_recur(branch->child0,&ray[0],&alpha[0],kappa,&gamma[0],&phi[0]);
      if(branch->child1 != NULL)
        walkTree_recur(branch->child1,&ray[0],&alpha[0],kappa,&gamma[0],&phi[0]);
      if(branch->child2 != NULL)
        walkTree_recur(branch->child2,&ray[0],&alpha[0],kappa,&gamma[0],&phi[0]);
      if(branch->child3 != NULL)
        walkTree_recur(branch->child3,&ray[0],&alpha[0],kappa,&gamma[0],&phi[0]);

    }
    else
    { // use whole cell

      double screening = exp(-rcm2cell*inv_screening_scale2);
      double tmp = -1.0*branch->mass/rcm2cell/PI*screening;

      alpha[0] += tmp*xcm[0];
      alpha[1] += tmp*xcm[1];

      {      //  taken out to speed up
        tmp=-2.0*branch->mass/PI/rcm2cell/rcm2cell*screening;
        gamma[0] += 0.5*(xcm[0]*xcm[0]-xcm[1]*xcm[1])*tmp;
        gamma[1] += xcm[0]*xcm[1]*tmp;

        *phi += 0.5*tree->current->mass*log( rcm2cell )/PI*screening;
        *phi -= 0.5*( tree->current->quad[0]*xcm[0]*xcm[0] + tree->current->quad[1]*xcm[1]*xcm[1] + 2*tree->current->quad[2]*xcm[0]*xcm[1] )/(PI*rcm2cell*rcm2cell)*screening;
      }

      // quadrapole contribution
      //   the kappa and gamma are not calculated to this order
      alpha[0] -= (branch->quad[0]*xcm[0] + branch->quad[2]*xcm[1])
      /(rcm2cell*rcm2cell)/PI*screening;
      alpha[1] -= (branch->quad[1]*xcm[1] + branch->quad[2]*xcm[0])
      /(rcm2cell*rcm2cell)/PI*screening;

      tmp = 4*(branch->quad[0]*xcm[0]*xcm[0] + branch->quad[1]*xcm[1]*xcm[1]
               + 2*branch->quad[2]*xcm[0]*xcm[1])/(rcm2cell*rcm2cell*rcm2cell)/PI*screening;

      alpha[0] += tmp*xcm[0];
      alpha[1] += tmp*xcm[1];

      return;
    }

  }
  return;
}

/** This is a diagnostic routine that prints the position of every point in a
 * given branch of the tree.
 */
template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::printParticlesInBranch(unsigned long number){
  unsigned long i;

  tree->moveTop();
  do{
    if(tree->current->number == number){
      std::cout << tree->current->nparticles << std::endl;
      for(i=0;i<tree->current->nparticles;++i){
        std::cout << xp[tree->current->particles[i]][0] << "  " << xp[tree->current->particles[i]][1] << std::endl;
      }
      return;
    }
  }while(tree->WalkStep(true));

  return;
}
/**
 * Prints to stdout the borders of each branch in the tree below level.
 * If level < 0 or not specified the whole tree will be printed.
 */

template <typename LensHaloType>
void TreeQuadHalos<LensHaloType>::printBranchs(int level){

  bool decend = true;
  tree->moveTop();
  do{
    std::cout << tree->current->boundary_p1[0] << "  " << tree->current->boundary_p1[1] << "   "
    << tree->current->boundary_p2[0] << "  " << tree->current->boundary_p2[1] << std::endl;
    if(tree->current->level == level) decend = false;
    else decend = true;
  }while(tree->WalkStep(decend));

  return;
}

#endif /* quadTreeHalos_h */

redpajama_set_name: RedPajamaGithub


text:
The Energy Edge: SEIA Says Solar Tax Credit Extension Would Boost Economy, Jobs, Renewable Energy Scale
The Solar Energy Industries Association (SEIA) just gave Congress 87 billion reasons to extend the solar Investment Tax Credit (ITC). Maintaining the credit through 2030 would create $87 billion in new private sector investment and add 113,000 American jobs, according to a recent SEIA forecast.
The solar ITC covers 30 percent of the value of a solar energy system and is slated to begin phasing out at the end of 2019. By 2022, the commercial credit will be slashed to 10 percent, and the residential incentive will be removed entirely.
A current forecast makes a strong economic case for continuing the credit. It projects an additional 82 gigawatts of additional solar power over the next decade if the incentive is re-upped. That's enough to power almost two-thirds of all American single-family homes.
A bulk of the extension's benefits would be felt in the utility-scale segment, analysts say. It would strengthen solar's increasing ability to compete on cost against other generation resources in existing and emerging markets. Distributed generation uses, such as for local homes and businesses, would benefit as well by speeding up the timeline for solar to achieve parity with other generation sources.
Extension Faces an Uphill Political Battle
The SEIA has poured all of its political will into its "Defend the ITC" campaign focused on getting this extension passed. And for good reason – the group called the ITC "the single most successful policy driver for deploying clean energy." It's anchored solar's staggering role in the growing renewable sector over the last 13 years. The U.S. solar industry has grown by more than 10,000 percent since the ITC took effect in 2006. It's had a powerful economic impact to the tune of 200,000-plus jobs and $140 billion in private investment.
The economic and environmental impacts of the solar ITC have not been lost on Congress. But the political path to renewal is complex and dates back to a compromise struck by Republicans and Democrats in 2015. At that time, Democrats agreed to end the 40-year export ban on crude oil in exchange for an extension on the solar ITC and similar wind power incentives. As part of that bipartisan deal, Democrats agreed the 2015 extension would be the last.
But many lawmakers now argue the Trump administration's policies have shifted the energy debate and are pushing to re-up the credits for another decade. U.S. Senator Chuck Grassley (R-IA) is not among them. The Republican Senate Finance chair, a longtime supporter of the credit, has stated he intends to honor his 2015 commitment to let it expire. Any path to getting the incentive passed in the Senate would have to go through Sen. Grassley and other Republicans.
The Edge: A Vote with Implications for the Entire Energy Industry
The debate over extending the solar ITC highlights the clear power lawmakers have to use incentives to influence the energy outlook in the U.S. That's nothing new. The credit has established solar as a leading renewable energy source over the last 15 years, and the economic impact is undeniable. It only makes sense that the solar industry wants to extend those benefits for another decade.
Meanwhile, Congress' vote on the incentives will have repercussions beyond just the solar sector. If approved, the extension of the ITC will continue to reshape pricing dynamics and shake up solar power's competitive position relative to other energy sources These factors represent opportunities for businesses operating in the solar space.
If the ITC extension doesn't pass, it will likely result in changes in the renewable sector and beyond. It will be worth keeping a close eye on where Congress shifts its attention next.
ALAN M. SELTZER
JOHN F. POVILAITIS


Today was rough…at least it was in the morning. Blowing $%&( up late into the night (but not as late as the majority of the neighborhood) makes for rough mornings. But it is July, and I don't really have much need at this point to even know what day it is.
But two days ago, I wrote a list of things that I needed to do (wp.me/p25DFv-5y). Today, I did two of the things on the list: I cleaned out (ok, archived) my Classroom (thanks to @alicekeeler for all the great helps, tips, everything to do with Classroom), I finished my district paperwork for reimbursement (which wasn't on the list at all), and I have managed to stay out of trouble on the iPads.
Mostly because I deleted the apps that are distracting.
There is no more Tapped Out, Facebook, or Facebook Messenger on any device. It has only been one day, and I do not miss any of it. I may try to delete Twitterriffic…but my Twitter addiction needs to be fed. Or maybe I'll feed it on my computer. I have so much more to do, so I may try it. Temporarily.
← Hi…my name is Lori…I have a Twitter addiction…and I keep everything.


The dr. prescribed this unit. Anyone try it yet? Any relief? Just wondering if it will really work or not and if my husband should try it? Anyone??????
Thank you for your question and being part of our community. Let me see what information I can give you.
The Spring TMS unit has been FDA approved for migraine which you can read about here; https://migraine.com/news/springtms-transcranial-magnetic-stimulation-device-migraine-receives-fda-approval/.
I've not tried it, but know a few people with migraine who are having good results from this unit.


text:
Godsway Donyoh: Finding a Family 8,000 km Away From Home
In December of 2018 I went to Farum, Denmark, a suburb of Copenhagen, to interview several people connected with FC Nordsjælland and the Right to Dream Academy. This is where I met 24-year-old forward, Godsway Donyoh. This is his story.
I grew up in the capital city of Ghana called Accra, in a town called Achimota, [more specifically] Christian Village. I grew up there as a young kid dreaming of playing soccer.
I was playing street football with my friends and a guy introduced me to a local team in our area, but I had to walk like 30 minutes to training. I joined this club and a few months later RtD came to do like trials, and they picked players, but I didn't get the opportunity to go at that time. So I was still playing, focusing on doing what I could do to get an opportunity.
And the question that I always asked myself when I woke up is 'how am I going to make it to the top level'?
I'm from a poor background so it was really difficult growing up trying to achieve my dreams. And I always wanted to play football so bad - so I wasn't actually concentrating at school. All of my dreams was to play football. I got like punished by my dad and my mom all the time.
Actually my parents could not afford to buy me football shoes. Like that even motivated me more to play. I always played with my school sneakers. So then I was playing with this local team and then Right to Dream came in again to do another trial.
And then I got a chance and I was picked. Then I told my parents about it and they're not going to let me go, especially my mom. My dad wanted me to join the academy, because that's what I've been dreaming about. My mom was like I have to go to school so I can't join the academy.
I had to talk to Right to Dream coaches and scouts to come down to my parents to explain how things work. I didn't even know it was about football and school. So Right to Dream came in and explained everything to my family. And my mom was like, okay if there's education at the Right to Dream Academy then I have to go.
Joining the Right to Dream Academy
When I joined the Right to Dream Academy I always missed my brother and my family, because I was young when I joined it. It was really tough for me.
He [Godsway's brother] died in 2004 before I went to the academy. He had a hole in the heart so it was really tough.
And then I remember one time I had to lie to the coaches and staff at the Right to Dream Academy. I was there and it was difficult because there were different guys from different cities in Ghana and we had a few guys from Cote d'Ivoire and Nigeria as well. The culture is totally different and I didn't know anyone there.
So I felt a little bit lonely even though we were trying to work together and get to know each other. I always thought about my brother, like how we used to hang out because I was playing football with him like all of the time - and he was really good at football as well.
Then I had to lie to the coaches that I missed my brother. I asked if they can give me a day off so I could go and see my family. They granted me that so I went back to see my mom and my dad and my little sister. But then my dad was really mad at me and he actually asked me to go back to the academy.
It was late when I got to the house so the next day he took me himself, and he took me back to the academy - because he said to me 'this is the best opportunity I could ever get in life, so I don't want you to waste this'. So I had to go back to the academy.
And then I went back and stayed even though I was still missing my brother. I was always crying – but I totally understand because I was still young and trying to get stronger.
Life at Right to Dream
When I was there we acted a play called The Lion King whereby I had to play a role as a lady and it was really funny. But that's how we work to get each other together.
Because like without doing all this stuff it's going to be difficult to get close to each other and work together as a team. Doing all of this was to bring all the boys together and learn a lot of stuff, like building the confidence and to get ready for any challenges they're going to face in the future.
Trial at Manchester City
It gets to a point like you are going to get questioned about what do you want to do. If you want to go as a professional or do you want to go to the States and further your education? Or do you want to go to a college in the UK? So mine was like I had two opportunities: to go to college in the UK or to sign a professional contract.
So it was really tough for me and I didn't know which to choose, but I went into take an exam called the IELTS. Then I can pass to the college but I needed, I think I had to get the score of 5 I think, and then I got 4.5 so I didn't pass the test, but then we had a game against a local club from Accra, and I did well in that game. I scored two goals and we drew the game 2-2.
Then there was a call from Espanyol in Spain and in Manchester City. They were interested in me coming to their clubs to do trials, but then we were in partnership with Man City. So then the guy from City asked me if I want to join Man City and do trials, and maybe get a chance to sign for Man City. I was like 'yes I want to.'
Then he asked me to go to Tom Vernon and tell him that I want to go to Manchester City. Then I was like, 'oh no I can go to Tom and tell him that I want to do this', but he took it like really offensively. He thought I was rejecting what he's saying to me, but he didn't really understand what I meant by that. Because in Ghana we have a lot of respect for elderly people. So I was saying about how to be respectful but he said it like I was trying to be rude or something.
So then like Tom called me into his office and asked me like, "what did I say to Figgle [the Manchester City representative]?"
And I was like this is what I said to him, and he was like, "yes, I understand you." He asked me do I want to go to Man City, and I was like "yes of course like it's going be a dream come true." Then he was like "okay than get ready you're going to go to Man City and have a trial." Then I went to City and had a trial with them, and everything went well and I got a contract with them.
Loaned From Man City
I was loaned to Sweden for three years, whereby I didn't like it because I wasn't having any of the Right to Dream staff around or any of my friends around to motivate me and keep me on the right track. So it was really difficult for me.
Because I was too young and they have like experienced players and all of that. So they are more focused on that. It's not like FC Nordsjælland, where they're going to guide every player to help every player you know. It was different in Sweden. And in Right to Dream and Nordsjælland, when we are done with main training we normally do personal training. But when I was in Sweden, they don't even care.
If you're done with training you're done. There's nothing more to do like they don't care. But here it's more like they try to push you. They try to like tell you that these are the basics that you have to work on. So they are focusing more on like everyone here, so it was different from Sweden when I was there. So that was why I was I couldn't succeed.
I was injured from 2014 to 2015 and I had like a really terrible season in those two years. So then I remember I came to Ghana in December 2015. And then Tom gave me a call and he asked me to come by his place, and then I went and he introduced like what they're doing here in Nordsjælland and the kind of partnership and what they want to do. And he asked me if I'm looking forward to joining Nordsjælland. I said to him yes I would definitely like to be here.
When I joined Nordsjælland the first six months was tough because I was still having like injuries. So they were helping me to build up my strength and all of that so I could be ready for the next season. Since then it has been like the best moment of my career, joining in Nordsjælland. So I have never regretted anything coming here making that decision.
Why He Signed a Contract Extension
There were opportunities for me to go to other clubs [He was linked with Leicester City, Bournemouth], but I feel like I'm not done with what I started here. One more reason why I signed the contract was that I had a one-year contract with FC Nordsjælland.
I wanted to stay here and if I'm going to stay here then I need to have more control with FC Nordsjælland. Because if I don't then that means that I'm going to leave the club as a free player, whereby Nordsjælland is not going to get anything or going to get enough from me. So it's like appreciating and showing appreciation to the club.
And also like showing the young ones like there's no need to rush in life, because everything you do it starts gradually. You don't just wake up one day and end up at the top. It doesn't work like that. So like they have laid the foundation for me. If someone lay a foundation for you to build you up as a person, and make you a better person in life you always have to give back to the person.
And it's the same like your mom and dad looking after you, educating you and making sure that you have the best education for you- to become someone better in life. And when they get old and they cannot work anymore, you have to look after them - that's the culture back in Africa. So Right to Dream and FC Nordsjælland are just like my family.
Agents and Outside Influences
I am a loyal person so I don't go about lying about stuff that is not happening. So yes I've got a lot of text and calls from agents trying to influence me. From last year up to now. This is the second time I'm renewing my contract with FC Nordsjælland. The first time I had a call three or four.
And even a guy who was working in Right to Dream before gave me a call not to renew the contract - because I got call up to the National Team, the A, Nordsjælland Team. Then these guys started advising me trying to influence me to not renew the contract. Because I still had one year and I could wait to leave as a free player. But I just said to him, 'okay yes I'll make sure I don't sign the contract' just to play along with him.
I came back to Nordsjælland and I didn't say a word to Tom or anyone. I just kept it to myself because at the end of the day, no one is going to make the decision for me, I have to make my own decisions. Then I signed this contract and the guy was so mad at me.
Then there were like a few guys from the Right to Dream Academy - the young ones- and I was trying to advise one guy to sign a contract with Nordsjælland. Not influencing him not to sign the contract, but I said to him 'before you go and sign the contract just make sure that you know what you've signed, and don't listen to what people are saying to you. Don't listen to people influencing you.'
So this guy went back to the same guy who asked me not to renew my contract, that this is what I am saying to him. So this guy called me and he was really mad - he was like 'why would you tell these guys to sign the contract with FC Nordsjælland whereby you know it's not going to help him.'
And then I was like 'I didn't say to him to sign the contract.' I was just saying to him he has to make sure what he's doing, it's from his heart and not listening to anyone else.
Then this guy actually told me he can tell the coaches and everyone at the National team not to give me a call-up to the National Team you know.
A lot of agents were texting and calling not to renew my contract, so I can leave as a free player and they going to give me this amount of money. And I will be good playing in a big club playing in a bigger league. So I actually have this guy called Joe who is my manager. So he also gets the same text and all of that, then he always ignores them and all that.
So I said to him just be careful about who he's texting and who he's calling, you know so it's just crazy. And he has also played a bigger role in my life since I joined FC Nordsjælland. So I think I have the best people in my life right now.
How African Football Can Improve
Using Ghana as an example we have a lot of talented players, like some have made it and they are still making it in football right now, but they never get called up to the national team which is bad.
They'd rather call favourites. Like if you're my favourite then you're going to play for the national team.
We just have to be honest because we're doing this to build a country, because then we are never going to call it a national team. It's not about favourites, it's about players who are performing and players who are ready to show something for the country.
And in Ghana it's like when you've been called to the national team and you've played there before, it's going to be the same guys all the time. They don't look on performance, they are just focusing on the favourite guys. So I think that's one thing we really have to change. And we're going to progress because we have a lot of talent.
They [my friends] didn't get the opportunity. That was the point I wanted to make. Like without Right to Dream I don't know where I would be right now.
Because I know where I'm from, so I always have this dream of building an orphanage, and I've had this conversation with Tom and as well I had it with my mom, because my dad is no more. I lost my dad too.


Find out how easy it is to order any Ford-built car you want at a discount, for shipment anwhere.
This item is made available for use in research, teaching, and private study, with permission from Ford Motor Company. No commercial use or derivative works are authorized under this license. For all uses beyond the scope of this license it is the responsibility of the user to obtain whatever permissions are necessary from the rights holders. Although we don't require you to contact us in advance for these purposes, we do appreciate hearing from teachers, students, and researchers who are using our resources in interesting ways (send e-mail to the Hartman Center at hartman-center@duke.edu).
Advertisements created by the J. Walter Thompson advertising agency for Ford Motor Company's lines of consumer and commercial vehicles, tractors, auto parts, and dealerships.


text:
Dr David Cavallucci
VMO in general surgery/St Andrews Hospital
Dr David Cavallucci is Brisbane raised and completed his medical studies at the University of Queensland. Dr Cavallucci's early training was at the Princess Alexandria Hospital in Brisbane and he completed his rural terms at Goondoowindi, Childers, and Dirranbandi.
David concluded his surgical training in Sydney and following his FRACS completed a post fellowship year studying laparoscopic hepatobiliary, upper gastrointestinal and bariatric surgery. A second fellowship year followed in Brisbane where he worked in advanced hepatobiliary surgery at the Royal Brisbane Hospital. Dr Cavallucci was then offered a position in Toronto, Canada working in liver, kidney and pancreas transplantation to complete his American Society of Transplant Surgeons accreditation.
Dr Cavallucci is now based at St Andrews Hospital as a VMO in general surgery with a specific focus on liver, gall bladder and pancreas oncology and benign diseases. With David's extensive background in transplantation, he is also doing a large proportion of specialist surgery dealing with major vascular resection and hopes to continue his work with transplantation in the future.


text:
Jacobson Announces She Will Step Down as US Envoy to Mexico in May
MEXICO CITY – US Ambassador to Mexico, Roberta Jacobson, announced on Thursday that she will step down from her post in early May after 31 years of government service "to pursue other opportunities."
"It has been an honor and privilege to serve my country as ambassador to Mexico. After serving the U.S. government for 31 years, I will be parting ways in May to pursue other opportunities," the diplomat said in a statement released on Twitter.
Jacobson said that she is leaving her post knowing that US-Mexican relations are strong.
"I have come to the difficult decision that it is the right time to move on to new challenges and adventures," Jacobson wrote, The New York Times reported. "This decision is all the more difficult because of my profound belief in the importance of the U.S.-Mexico relationship and knowledge that it is at a crucial moment."
Jacobson has headed the US Embassy in Mexico since May 2016 and she said that – for the time being – she has no information on who might succeed her.
From 2012-2016, Jacobson served as assistant secretary of state for Western Hemisphere affairs and was nominated by former President Barack Obama to be the envoy to Mexico in June 2015, receiving Senate confirmation in April 2016 after a grueling process.
Jacobson is the first woman in US history to lead Washington's diplomatic mission in Mexico, a country she got to know well between 2002-2007 when she headed the State Department's Office of Mexican Affairs, later becoming deputy assistant secretary for Mexico and Canada until 2010.
She is also known for having been the chief US negotiator in the process to reestablish diplomatic relations with Cuba launched by Obama in December 2014.
Enter your email address to subscribe to free headlines (and great cartoons so every email has a happy ending!) from the Latin American Herald Tribune:


text:
import { InanoSQLAdapter, InanoSQLTable, InanoSQLPlugin, InanoSQLInstance, adapterCreateIndexFilter, adapterConnectFilter, adapterDeleteIndexFilter, adapterAddIndexValueFilter, adapterDeleteIndexValueFilter, adapterReadIndexKeyFilter, adapterReadIndexKeysFilter, adapterWriteFilter, adapterReadFilter, adapterReadMultiFilter, adapterDisconnectFilter, adapterCreateTableFilter, adapterDropTableFilter, adapterDeleteFilter, adapterGetTableIndexFilter, adapterGetTableIndexLengthFilter, postConnectFilter, willConnectFilter, InanoSQLQuery } from "@nano-sql/core/lib/interfaces";
import { generateID, deepSet, chainAsync, allAsync, blankTableDefinition, adapterFilters, buildQuery, noop } from "@nano-sql/core/lib/utilities";
import { SyncStorage } from "@nano-sql/core/lib/adapters/syncStorage";

export const nSQLCache = (args?: {
    cacheAll?: boolean;
    batchSize?: number;
    batchInterval?: number;
}): InanoSQLPlugin => {

    let _tableConfigs: {
        [tableName: string]: InanoSQLTable;
    } = {};
    let id: string;
    let cacheAdapter: InanoSQLAdapter = new SyncStorage();
    let cachedTables: {[tableName: string]: "loading" | "ready"} = {};
    let connected = false;
    const setArgs = {
        cacheAll: false,
        batchSize: 1000,
        batchInterval: 500,
        ...(args || {}),
    };
    let nSQL: InanoSQLInstance;

    setInterval(() => {
        if (connected) {

        }
    }, setArgs.batchInterval);

    const loadCache = (tableId: string) => {
        const tableName = Object.keys(nSQL._tableIds).reduce((prev, cur) => {
            if (nSQL._tableIds[cur] === tableId) return cur;
            return prev;
        }, "");
        adapterFilters(nSQL).getTableIndex(tableId, (index) => {
            let i = 0;
            const next = () => {
                let loadThese = index.splice(setArgs.batchSize * i, (setArgs.batchSize * i) + setArgs.batchSize);
                if (!loadThese.length) {
                    cachedTables[tableId] = "ready";
                    return;
                }
                allAsync(loadThese, (pk, i, next, err) => {
                    adapterFilters(nSQL).read(tableId, pk, next, err);
                }).then((rows) => {
                    nSQL.triggerQuery({
                        ...buildQuery(nSQL, tableName, "upsert"),
                        actionArgs: rows,
                        tags: ["load-cache"]
                    }, noop, () => {
                        i++;
                        setTimeout(next);
                    }, (err) => {
                        throw new Error(err);
                    });

                }).catch((err) => {
                    throw new Error(err);
                })
            }
            next();
        }, (err) => {
            throw new Error(err);
        })
    }

    return {
        name: "Cache",
        version: 2.00,
        filters: [
            {
                name: "willConnect",
                priority: 1500,
                call: (inputArgs: willConnectFilter, complete: (args: willConnectFilter) => void, cancel: (info: any) => void) => {
                    nSQL = inputArgs.res;
                    complete(inputArgs);
                }
            },
            {
                name: "adapterConnect",
                priority: 1500,
                call: (inputArgs: adapterConnectFilter, complete: (args: adapterConnectFilter) => void, cancel: (info: any) => void) => {
                    cacheAdapter.connect(inputArgs.res.id, () => {
                        connected = true;
                        complete(inputArgs);
                    }, cancel);
                }
            },
            {
                name: "adapterWrite",
                priority: 1500,
                call: (inputArgs: adapterWriteFilter, complete: (args: any) => void, cancel: (info: any) => void) => {
                    const loadCache = ((inputArgs.query || {} as InanoSQLQuery).tags || []).indexOf("load-cache") !== -1;
                    if (loadCache || cachedTables[inputArgs.res.table] === "ready") {

                    }
                }
            },
            {
                name: "adapterRead",
                priority: 1500,
                call: (inputArgs: adapterReadFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterReadMulti",
                priority: 1500,
                call: (inputArgs: adapterReadMultiFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterReadMulti",
                priority: 1500,
                call: (inputArgs: adapterReadMultiFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterDisconnect",
                priority: 1500,
                call: (inputArgs: adapterDisconnectFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterCreateTable",
                priority: 1500,
                call: (inputArgs: adapterCreateTableFilter, complete: (args: any) => void, cancel: (info: any) => void) => {
                    const doCache = setArgs.cacheAll || (inputArgs.res.tableData.props || {}).cache;
                    if (doCache) {
                        cachedTables[inputArgs.res.tableName] = "loading";
                        cacheAdapter.createTable(inputArgs.res.tableName, inputArgs.res.tableData, () => {
                            complete(inputArgs);
                            loadCache(inputArgs.res.tableName);
                        }, inputArgs.res.error);
                    } else {
                        complete(inputArgs);
                    }
                }
            },
            {
                name: "adapterDropTable",
                priority: 1500,
                call: (inputArgs: adapterDropTableFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterDelete",
                priority: 1500,
                call: (inputArgs: adapterDeleteFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterGetTableIndex",
                priority: 1500,
                call: (inputArgs: adapterGetTableIndexFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterGetTableIndexLength",
                priority: 1500,
                call: (inputArgs: adapterGetTableIndexLengthFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterCreateIndex",
                priority: 1500,
                call: (inputArgs: adapterCreateIndexFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterDeleteIndex",
                priority: 1500,
                call: (inputArgs: adapterDeleteIndexFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterAddIndexValue",
                priority: 1500,
                call: (inputArgs: adapterAddIndexValueFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterDeleteIndexValue",
                priority: 1500,
                call: (inputArgs: adapterDeleteIndexValueFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterReadIndexKey",
                priority: 1500,
                call: (inputArgs: adapterReadIndexKeyFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            },
            {
                name: "adapterReadIndexKeys",
                priority: 1500,
                call: (inputArgs: adapterReadIndexKeysFilter, complete: (args: any) => void, cancel: (info: any) => void) => {

                }
            }
        ]
    }
}