<?xml version="1.0" encoding="utf-8"?>
<!--
    Copyright (C) 2020 The Android Open Source Project

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
  -->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minWidth="80dp"
    android:gravity="center"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:background="?attr/selectableItemBackgroundBorderless">

    <ImageView
        android:id="@+id/accessibility_button_target_icon"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:layout_marginBottom="3dp"
        android:scaleType="fitCenter"/>

    <TextView
        android:id="@+id/accessibility_button_target_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:textAppearance="?attr/textAppearanceSmall"
        android:textColor="?attr/textColorPrimary"
        android:textSize="12sp"
        android:fontFamily="sans-serif-condensed"
        android:gravity="top|center_horizontal"
        android:minLines="2"
        android:maxLines="2"
        android:ellipsize="marquee"/>
</LinearLayout>

{'repo_name': 'aosp-mirror/platform_frameworks_base', 'stars': '9245', 'repo_language': 'Java', 'file_name': 'DatabaseCursorTest.java', 'mime_type': 'text/x-java', 'hash': 4668339031767319254, 'source_dataset': 'data'}


//=========================================================
//  MusE
//  Linux Music Editor
//    $Id: scldiv.cpp,v 1.1.1.1 2003/10/27 18:54:32 wschweer Exp $
//
//    Copyright (C) 1997  Josef Wilgen
//    (C) Copyright 2000 Werner Schweer (ws@seh.de)
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; version 2 of
//  the License, or (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
//=========================================================

#include <algorithm>

#include "muse_math.h"
#include "scldiv.h"
#include "mmath.h"

namespace MusEGui {

//	ScaleDiv - A class for building scale divisions
//
//	The ScaleDiv class can build
//	linear and logarithmic scale divisions for specified
//	intervals. It uses an adjustable algorithm to
//	generate the major and minor step widths automatically.
//	A scale division has a minimum value, a maximum value,
//	a vector of major marks, and a vector of minor marks.
//
//	ScaleDiv uses implicit sharing for the mark vectors.
//
//	Build a logarithmic scale division from 0.01 to 1000
//	and print out the major and minor marks.
//.c
//      #include <scldiv.h>
//      #include <iostream.h>
//
//      main()
//      {
//          int i,k;
//          ScaleDiv sd;
//
//          sd.rebuild(0.01, 100, 10, 10, TRUE, 0.0);
//
//          k=0;
//          for (i=0;i<sd.majCnt();i++)
//          {
//              while(k < sd.minCnt())
//              {
//                  if(sd.minMark(k) < sd.majMark(i))
//                  {
//                      cout << " - " << sd.minMark(i) << "\n";
//                      k++;
//                  }
//                  else
//                     break;
//              }
//              cout << "-- " << sd.majMark(i) << "\n";
//          }
//          while(k < sd.minCnt())
//          {
//              cout << " - " << sd.minMark(i) << "\n";
//              k++;
//          }
//      }
//
//------------------------------------------------------------

static const double step_eps = 1.0e-3;
static const double border_eps = 1.0e-10;

static bool limRange(double &val, double v1, double v2, double eps_rel = 0.0,
                     double eps_abs = 0.0)
{

   bool rv = true;
   double vmin = MusECore::qwtMin(v1, v2);
   double vmax = MusECore::qwtMax(v1, v2);
   double delta_min = MusECore::qwtMax(MusECore::qwtAbs(eps_rel * vmin), MusECore::qwtAbs(eps_abs));
   double delta_max = MusECore::qwtMax(MusECore::qwtAbs(eps_rel * vmax), MusECore::qwtAbs(eps_abs));

   if (val < vmin)
   {
      if (val < vmin - delta_min) rv = false;
      val = vmin;
   }
   else if (val > vmax)
   {
      if (val > vmax + delta_max) rv = false;
      val = vmax;
   }
   return rv;

}

//------------------------------------------------------------
//.F	ScaleDiv::ScaleDiv
//	Construct a ScaleDiv instance.
//
//.u	Syntax
//.f	 ScaleDiv::ScaleDiv()
//------------------------------------------------------------

ScaleDiv::ScaleDiv()
{
   d_lBound = 0.0;
   d_hBound = 0.0;
   d_majStep = 0.0;
   d_log = false;
}

//------------------------------------------------------------
//.F	ScaleDiv::~ScaleDiv
//	Destroy a ScaleDiv instance.
//
//.u	Syntax
//.f	 ScaleDiv::~ScaleDiv()
//------------------------------------------------------------

ScaleDiv::~ScaleDiv()
{
}

//------------------------------------------------------------
//.F	ScaleDiv::ScaleDiv
//      Copy Constructor
//
//.u	Syntax
//.f	 ScaleDiv::ScaleDiv(const ScaleDiv &s)
//
//.u	Parameters
//.p	const ScaleDiv &s -- scale division to be copied
//------------------------------------------------------------

ScaleDiv::ScaleDiv(const ScaleDiv &s)
{
   copy(s);
}

//------------------------------------------------------------
//.F	ScaleDiv::operator=
//	Assignment operator
//
//.u	Syntax
//.f	ScaleDiv & ScaleDiv::operator=(const ScaleDiv &s)
//
//.u	Parameters
//.p	const ScaleDiv &s -- scale division to be assigned
//------------------------------------------------------------

ScaleDiv& ScaleDiv::operator=(const ScaleDiv &s)
{
   copy(s);
   return *this;
}

//------------------------------------------------------------
//.F	ScaleDiv::copy
//	Copy member data from another ScaleDiv instance.
//
//.u	Syntax
//.f	void ScaleDiv::copy(const ScaleDiv &s)
//
//.u	Parameters
//.p	const ScaleDiv &s
//------------------------------------------------------------

void ScaleDiv::copy(const ScaleDiv &s)
{
   d_lBound = s.d_lBound;
   d_hBound = s.d_hBound;
   d_log = s.d_log;
   d_majStep = s.d_majStep;
   d_minMarks = s.d_minMarks;
   d_majMarks = s.d_majMarks;
}

//------------------------------------------------------------
//.F	ScaleDiv::rebuild
//	Build a scale width major and minor divisions
//
//.p
//	double x1	--	first boundary value
//	double x2	--	second boundary value
//	int maxMajSteps	--	max. number of major step intervals
//	int maxMinSteps	--	max. number of minor step intervals
//      bool log	--	logarithmic division (TRUE/FALSE)
//	double step 	--	fixed major step width. Defaults to 0.0.
//	bool ascend	--	if TRUE, sort in ascending order from min(x1, x2)
//				to max(x1, x2). If FALSE, sort in the direction
//				from x1 to x2.	Defaults to TRUE.
//
//.u Return Value
//	True if the arrays have been allocated successfully.
//
//.u Description
//	If no fixed step width is specified or if it is set to 0, the
//	major step width will be calculated automatically according to the
//	the value of maxMajSteps. The maxMajSteps parameter has no effect
//	if a fixed step size is specified. The minor step width is always
//	calculated automatically.
//	If the step width is to be calculated automatically, the algorithm
//	tries to find reasonable values fitting into the scheme {1,2,5}*10^n
//	with an integer number n for linear scales.
//	For logarithmic scales, there are three different cases:
//.i
//	-- If the major step width is one decade, the minor marks
//		will fit into one of the schemes {1,2,...9}, {2,4,6,8}, {2,5} or {5},
//		depending on the maxMinSteps parameter.
//	-- If the major step size spans
//		more than one decade, the minor step size will be {1,2,5}*10^n decades
//		with a natural number n.
//	-- If the whole range is less than one decade, a linear scale
//		division will be built
//
//.u Note
//	For logarithmic scales, the step width is measured in decades.
//------------------------------------------------------------

bool ScaleDiv::rebuild(double x1, double x2, int maxMajSteps, int maxMinSteps,
                       bool log, double step, bool ascend)
{

   int rv;

   d_lBound = MusECore::qwtMin(x1, x2);
   d_hBound = MusECore::qwtMax(x1, x2);
   d_log = log;

//   printf("*** MajSteps %d / MinSteps %d / step %f / x1 %f / x2 %f \n",
//          maxMajSteps, maxMinSteps, step, x1, x2);
   if (step > (d_hBound - d_lBound))
       step = 0.0;

   if (d_log)
      rv = buildLogDiv(maxMajSteps,maxMinSteps,step);
   else
      rv = buildLinDiv(maxMajSteps, maxMinSteps, step);

   if ((!ascend) && (x2 < x1))
   {
      d_lBound = x1;
      d_hBound = x2;
      MusECore::qwtTwistArray(d_majMarks.data(), d_majMarks.size());
      MusECore::qwtTwistArray(d_minMarks.data(), d_minMarks.size());
   }

   return rv;

}

//------------------------------------------------------------
//.F	ScaleDiv::buildLinDiv
//	Build a linear scale division in ascending order
//
//.u	Syntax
//.f	bool ScaleDiv::buildLinDiv(int majSteps, int minSteps, double step)
//
//.u	Parameters
//.p	int maxSteps -- max. number of step intervals
//	double step -- fixed step width
//
//.u	Return Value
//		TRUE if array has been successfully resized
//
//.u	Description
//		If the 'step' parameter is set to 0.0, this function
//		cal[culates the step width automatically according to
//		the value of 'maxSteps'. MaxSteps must be greater than or
//		equal to 2. It will be guessed if an invalid value is specified.
//		The maximum possible number of steps is	limited to 10000.
//		The maxSteps parameter has no effect if a fixed step width is
//		specified.
//
//.u	Note
//	This function uses the data members d_lBound and d_hBound and assumes
//	that d_hBound > d_lBound.
//------------------------------------------------------------

bool ScaleDiv::buildLinDiv(int maxMajSteps, int maxMinSteps, double step)
{

   int nMaj, nMin, minSize, i0,i,k;
   double val, mval;
   double firstTick, lastTick;
   double minStep;
   QVector<double> buffer;
   bool rv = true;

   // parameter range check
   maxMajSteps = MusECore::qwtMax(1, maxMajSteps);
   maxMinSteps = MusECore::qwtMax(0, maxMinSteps);
   step = MusECore::qwtAbs(step);

   // reset vectors
   d_minMarks.resize(0);
   d_majMarks.resize(0);

   if (d_lBound == d_hBound) return true;

   //
   // Set up major divisions
   //
   if (step == 0.0)
      d_majStep = MusECore::qwtCeil125(MusECore::qwtAbs(d_hBound - d_lBound) * 0.999999
                                       / double(maxMajSteps));
   else
      d_majStep = step;

   if (d_majStep == 0.0) return true;

   firstTick = ceil( (d_lBound - step_eps * d_majStep) / d_majStep) * d_majStep;
   lastTick = floor( (d_hBound + step_eps * d_majStep) / d_majStep) * d_majStep;

   nMaj = MusECore::qwtMin(10000, int(rint((lastTick - firstTick) / d_majStep)) + 1);

   d_majMarks.resize(nMaj);
   MusECore::qwtLinSpace(d_majMarks.data(), d_majMarks.size(), firstTick, lastTick);

   //
   // Set up minor divisions
   //
   if (maxMinSteps < 1) // no minor divs
      return true;

   minStep = MusECore::qwtCeil125( d_majStep  /  double(maxMinSteps) );

   if (minStep == 0.0) return true;

   nMin = MusECore::qwtAbs(int(rint(d_majStep / minStep))) - 1; // # minor steps per interval

   // Do the minor steps fit into the interval?
   if ( MusECore::qwtAbs(double(nMin +  1) * minStep - d_majStep) >  step_eps * d_majStep)
   {
      nMin = 1;
      minStep = d_majStep * 0.5;
   }

   // Are there minor ticks below the first major tick?
   if (!d_majMarks.empty() && d_majMarks[0] > d_lBound )
      i0 = -1;
   else
      i0 = 0;

   // resize buffer to the maximum possible number of minor ticks
   buffer.resize(nMin * (nMaj + 1));

   // calculate minor ticks
   if (rv)
   {
      minSize = 0;
      for (i = i0; i < (int)d_majMarks.size(); i++)
      {
         if (i >= 0)
            val = d_majMarks[i];
         else
            val = d_majMarks[0] - d_majStep;

         for (k=0; k< nMin; k++)
         {
            mval = (val += minStep);
            if (limRange(mval, d_lBound, d_hBound, border_eps))
            {
               buffer[minSize] = mval;
               minSize++;
            }
         }
      }
      //d_minMarks.duplicate(buffer.data(), minSize);
      d_minMarks.resize(minSize);
      std::copy(buffer.data(), buffer.data() + minSize, d_minMarks.begin());
   }

   return rv;
}

//------------------------------------------------------------
//.F	ScaleDiv::buildLogDiv
//	Build a logarithmic scale division
//
//.u	Syntax
//.f	bool ScaleDiv::buildLogDiv(int maxMajSteps, int maxMinSteps, int majStep)
//
//.u	Parameters
//.p	int maxMajSteps, int maxMinSteps, int majStep
//
//.u	Return Value
//		True if memory has been successfully allocated
//
//.u	Note
//	This function uses the data members d_lBound and d_hBound and assumes
//	that d_hBound > d_lBound.
//------------------------------------------------------------

bool ScaleDiv::buildLogDiv(int maxMajSteps, int maxMinSteps, double majStep)
{
   double firstTick, lastTick;
   double lFirst, lLast;
   double val, sval, minStep, minFactor;
   int nMaj, nMin, minSize, i, k, k0, kstep, kmax, i0;
   bool rv = true;
   double width;

   QVector<double> buffer;

   // Parameter range check
   maxMajSteps = MusECore::qwtMax(1, MusECore::qwtAbs(maxMajSteps));
   maxMinSteps = MusECore::qwtMax(0, MusECore::qwtAbs(maxMinSteps));
   majStep = MusECore::qwtAbs(majStep);

   // boundary check
   limRange(d_hBound, LOG_MIN, LOG_MAX);
   limRange(d_lBound, LOG_MIN, LOG_MAX);

   // reset vectors
   d_minMarks.resize(0);
   d_majMarks.resize(0);

   if (d_lBound == d_hBound) return true;

   // scale width in decades
   width = log10(d_hBound) - log10(d_lBound);

   // scale width is less than one decade -> build linear scale
   if (width < 1.0)
   {
      rv = buildLinDiv(maxMajSteps, maxMinSteps, 0.0);
      // convert step width to decades
      if (d_majStep > 0)
         d_majStep = log10(d_majStep);

      return rv;
   }

   //
   //  Set up major scale divisions
   //
   if (majStep == 0.0)
      d_majStep = MusECore::qwtCeil125( width * 0.999999 / double(maxMajSteps));
   else
      d_majStep = majStep;

   // major step must be >= 1 decade
   d_majStep = MusECore::qwtMax(d_majStep, 1.0);

   lFirst = ceil((log10(d_lBound) - step_eps * d_majStep) / d_majStep) * d_majStep;
   lLast = floor((log10(d_hBound) + step_eps * d_majStep) / d_majStep) * d_majStep;

   firstTick = exp10(lFirst);
   lastTick = exp10(lLast);

   nMaj = MusECore::qwtMin(10000, int(rint(MusECore::qwtAbs(lLast - lFirst) / d_majStep)) + 1);

   d_majMarks.resize(nMaj);
   MusECore::qwtLogSpace(d_majMarks.data(), d_majMarks.size(), firstTick, lastTick);

   //
   // Set up minor scale divisions
   //

   if ((d_majMarks.size() < 1) || (maxMinSteps < 1)) return true; // no minor marks

   if (d_majStep < 1.1)			// major step width is one decade
   {
      if (maxMinSteps >= 8)
      {
         k0 = 2;
         kmax = 9;
         kstep = 1;
         minSize = (d_majMarks.size() + 1) * 8;
      }
      else if (maxMinSteps >= 4)
      {
         k0 = 2;
         kmax = 8;
         kstep = 2;
         minSize = (d_majMarks.size() + 1) * 4;
      }
      else if (maxMinSteps >= 2)
      {
         k0 = 2;
         kmax = 5;
         kstep = 3;
         minSize = (d_majMarks.size() + 1) * 2;
      }
      else
      {
         k0 = 5;
         kmax = 5;
         kstep = 1;
         minSize = (d_majMarks.size() + 1);
      }

      // resize buffer to the max. possible number of minor marks
      buffer.resize(minSize);

      // Are there minor ticks below the first major tick?
      if ( d_lBound < firstTick )
         i0 = -1;
      else
         i0 = 0;

      minSize = 0;
      for (i = i0; i< (int)d_majMarks.size(); i++)
      {
         if (i >= 0)
            val = d_majMarks[i];
         else
            val = d_majMarks[0] / exp10(d_majStep);

         for (k=k0; k<= kmax; k+=kstep)
         {
            sval = val * double(k);
            if (limRange(sval, d_lBound, d_hBound, border_eps))
            {
               buffer[minSize] = sval;
               minSize++;
            }
         }
      }

      // copy values into the minMarks array
      //d_minMarks.duplicate(buffer.data(), minSize);
      d_minMarks.resize(minSize);
      std::copy(buffer.data(), buffer.data() + minSize, d_minMarks.begin());

   }
   else				// major step > one decade
   {

      // substep width in decades, at least one decade
      minStep = MusECore::qwtCeil125( (d_majStep - step_eps * (d_majStep / double(maxMinSteps)))
                                      /  double(maxMinSteps) );
      minStep = MusECore::qwtMax(1.0, minStep);

      // # subticks per interval
      nMin = int(rint(d_majStep / minStep)) - 1;

      // Do the minor steps fit into the interval?
      if ( MusECore::qwtAbs( double(nMin + 1) * minStep - d_majStep)  >  step_eps * d_majStep)
         nMin = 0;

      if (nMin < 1) return true;		// no subticks

      // resize buffer to max. possible number of subticks
      buffer.resize((d_majMarks.size() + 1) * nMin );

      // substep factor = 10^substeps
      minFactor = MusECore::qwtMax(exp10(minStep), 10.0);

      // Are there minor ticks below the first major tick?
      if ( d_lBound < firstTick )
         i0 = -1;
      else
         i0 = 0;

      minSize = 0;
      for (i = i0; i< (int)d_majMarks.size(); i++)
      {
         if (i >= 0)
            val = d_majMarks[i];
         else
            val = firstTick / exp10(d_majStep);

         for (k=0; k< nMin; k++)
         {
            sval = (val *= minFactor);
            if (limRange(sval, d_lBound, d_hBound, border_eps))
            {
               buffer[minSize] = sval;
               minSize++;
            }
         }
      }
      //d_minMarks.duplicate(buffer.data(), minSize);
      d_minMarks.resize(minSize);
      std::copy(buffer.data(), buffer.data() + minSize, d_minMarks.begin());

   }

   return rv;
}

//------------------------------------------------------------
//.F	ScaleDiv::operator==
//	Equality operator
//
//.u	Syntax
//.f	int ScaleDiv::operator==(const ScaleDiv &s)
//
//.u	Parameters
//.p	const ScaleDiv &s
//
//.u	Return Value
//		TRUE if this instance is equal to s
//------------------------------------------------------------

int ScaleDiv::operator==(const ScaleDiv &s) const
{
   if (d_lBound != s.d_lBound)
      return 0;
   if (d_hBound != s.d_hBound)
      return 0;
   if (d_log != s.d_log)
      return 0;
   if (d_majStep != s.d_majStep)
      return 0;
   if (d_majMarks != s.d_majMarks)
      return 0;
   return (d_minMarks == s.d_minMarks);
}

//------------------------------------------------------------
//.F	ScaleDiv::operator!=
//	Inequality
//
//.u	Syntax
//.f	int ScaleDiv::operator!=(const ScaleDiv &s)
//
//.u	Parameters
//.p	const ScaleDiv &s
//
//.u	Return Value
//		TRUE if this instance is not equal to s
//------------------------------------------------------------

int ScaleDiv::operator!=(const ScaleDiv &s) const
{
   return (!(*this == s));
}

//------------------------------------------------------------
//.F	ScaleDiv::reset
//	Detach the shared data and set everything to zero.
//
//.u	Syntax
//.f	void ScaleDiv::reset()
//------------------------------------------------------------

void ScaleDiv::reset()
{
   // reset vectors
   d_minMarks.resize(0);
   d_majMarks.resize(0);

   d_lBound = 0.0;
   d_hBound = 0.0;
   d_majStep = 0.0;
   d_log = false;
}

} // namespace MusEGui

{'repo_name': 'muse-sequencer/muse', 'stars': '158', 'repo_language': 'C++', 'file_name': 'doublechorus.cpp', 'mime_type': 'text/x-c', 'hash': 648061909926956092, 'source_dataset': 'data'}


/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.htmlui;

import java.util.concurrent.CountDownLatch;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javax.swing.JComponent;
import javax.swing.JFrame;
import net.java.html.BrwsrCtx;
import org.netbeans.api.htmlui.HTMLComponent;
import org.netbeans.html.context.spi.Contexts;
import static org.testng.Assert.*;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 *
 * @author Jaroslav Tulach
 */
public class ComponentsTest {
    public ComponentsTest() {
    }

    @BeforeClass public void initNbResLoc() {
        NbResloc.init();
    }

    @Test(timeOut = 9000)
    public void loadSwing() throws Exception {
        CountDownLatch cdl = new CountDownLatch(1);
        JComponent p = TestPages.getSwing(10, cdl);
        JFrame f = new JFrame();
        f.getContentPane().add(p);
        f.pack();
        f.setVisible(true);
        cdl.await();
    }

    @Test(timeOut = 9000)
    public void loadFX() throws Exception {
        final CountDownLatch cdl = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(1);
        final JFXPanel p = new JFXPanel();
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                Node wv = TestPages.getFX(10, cdl);
                Scene s = new Scene(new Group(wv));
                p.setScene(s);
                done.countDown();
            }
        });
        done.await();
        JFrame f = new JFrame();
        f.getContentPane().add(p);
        f.pack();
        f.setVisible(true);
        cdl.await();
    }

    @HTMLComponent(
        url = "simple.html", className = "TestPages",
        type = JComponent.class,
        techIds = "second"
    )
    static void getSwing(int param, CountDownLatch called) {
        assertEquals(param, 10, "Correct value passed in");
        called.countDown();
        ATech t = Contexts.find(BrwsrCtx.findDefault(ComponentsTest.class), ATech.class);
        assertNotNull(t, "A technology found");
        assertEquals(t.getClass(), ATech.Second.class);
    }

    @HTMLComponent(
        url = "simple.html", className = "TestPages",
        type = Node.class,
        techIds = "first"
    )
    static void getFX(int param, CountDownLatch called) {
        assertEquals(param, 10, "Correct value passed in");
        called.countDown();
        ATech t = Contexts.find(BrwsrCtx.findDefault(ComponentsTest.class), ATech.class);
        assertNotNull(t, "A technology found");
        assertEquals(t.getClass(), ATech.First.class);
    }

}

{'repo_name': 'apache/netbeans', 'stars': '1393', 'repo_language': 'Java', 'file_name': 'l10n.list', 'mime_type': 'text/plain', 'hash': 6963935922452415277, 'source_dataset': 'data'}


{-# LANGUAGE DataKinds          #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric      #-}
{-# LANGUAGE FlexibleInstances  #-}
{-# LANGUAGE NoImplicitPrelude  #-}
{-# LANGUAGE OverloadedStrings  #-}
{-# LANGUAGE RecordWildCards    #-}
{-# LANGUAGE TypeFamilies       #-}
{-# LANGUAGE TypeOperators      #-}

{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds      #-}
{-# OPTIONS_GHC -fno-warn-unused-imports    #-}

-- |
-- Module      : Network.Google.Resource.YouTube.Activities.List
-- Copyright   : (c) 2015-2016 Brendan Hay
-- License     : Mozilla Public License, v. 2.0.
-- Maintainer  : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability   : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a list of channel activity events that match the request
-- criteria. For example, you can retrieve events associated with a
-- particular channel, events associated with the user\'s subscriptions and
-- Google+ friends, or the YouTube home page feed, which is customized for
-- each user.
--
-- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.activities.list@.
module Network.Google.Resource.YouTube.Activities.List
    (
    -- * REST Resource
      ActivitiesListResource

    -- * Creating a Request
    , activitiesList
    , ActivitiesList

    -- * Request Lenses
    , alPublishedAfter
    , alPart
    , alHome
    , alMine
    , alRegionCode
    , alChannelId
    , alPageToken
    , alMaxResults
    , alPublishedBefore
    ) where

import           Network.Google.Prelude
import           Network.Google.YouTube.Types

-- | A resource alias for @youtube.activities.list@ method which the
-- 'ActivitiesList' request conforms to.
type ActivitiesListResource =
     "youtube" :>
       "v3" :>
         "activities" :>
           QueryParam "part" Text :>
             QueryParam "publishedAfter" DateTime' :>
               QueryParam "home" Bool :>
                 QueryParam "mine" Bool :>
                   QueryParam "regionCode" Text :>
                     QueryParam "channelId" Text :>
                       QueryParam "pageToken" Text :>
                         QueryParam "maxResults" (Textual Word32) :>
                           QueryParam "publishedBefore" DateTime' :>
                             QueryParam "alt" AltJSON :>
                               Get '[JSON] ActivityListResponse

-- | Returns a list of channel activity events that match the request
-- criteria. For example, you can retrieve events associated with a
-- particular channel, events associated with the user\'s subscriptions and
-- Google+ friends, or the YouTube home page feed, which is customized for
-- each user.
--
-- /See:/ 'activitiesList' smart constructor.
data ActivitiesList =
  ActivitiesList'
    { _alPublishedAfter  :: !(Maybe DateTime')
    , _alPart            :: !Text
    , _alHome            :: !(Maybe Bool)
    , _alMine            :: !(Maybe Bool)
    , _alRegionCode      :: !(Maybe Text)
    , _alChannelId       :: !(Maybe Text)
    , _alPageToken       :: !(Maybe Text)
    , _alMaxResults      :: !(Textual Word32)
    , _alPublishedBefore :: !(Maybe DateTime')
    }
  deriving (Eq, Show, Data, Typeable, Generic)

-- | Creates a value of 'ActivitiesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'alPublishedAfter'
--
-- * 'alPart'
--
-- * 'alHome'
--
-- * 'alMine'
--
-- * 'alRegionCode'
--
-- * 'alChannelId'
--
-- * 'alPageToken'
--
-- * 'alMaxResults'
--
-- * 'alPublishedBefore'
activitiesList
    :: Text -- ^ 'alPart'
    -> ActivitiesList
activitiesList pAlPart_ =
  ActivitiesList'
    { _alPublishedAfter = Nothing
    , _alPart = pAlPart_
    , _alHome = Nothing
    , _alMine = Nothing
    , _alRegionCode = Nothing
    , _alChannelId = Nothing
    , _alPageToken = Nothing
    , _alMaxResults = 5
    , _alPublishedBefore = Nothing
    }

-- | The publishedAfter parameter specifies the earliest date and time that
-- an activity could have occurred for that activity to be included in the
-- API response. If the parameter value specifies a day, but not a time,
-- then any activities that occurred that day will be included in the
-- result set. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
-- format.
alPublishedAfter :: Lens' ActivitiesList (Maybe UTCTime)
alPublishedAfter
  = lens _alPublishedAfter
      (\ s a -> s{_alPublishedAfter = a})
      . mapping _DateTime

-- | The part parameter specifies a comma-separated list of one or more
-- activity resource properties that the API response will include. If the
-- parameter identifies a property that contains child properties, the
-- child properties will be included in the response. For example, in an
-- activity resource, the snippet property contains other properties that
-- identify the type of activity, a display title for the activity, and so
-- forth. If you set part=snippet, the API response will also contain all
-- of those nested properties.
alPart :: Lens' ActivitiesList Text
alPart = lens _alPart (\ s a -> s{_alPart = a})

-- | Set this parameter\'s value to true to retrieve the activity feed that
-- displays on the YouTube home page for the currently authenticated user.
alHome :: Lens' ActivitiesList (Maybe Bool)
alHome = lens _alHome (\ s a -> s{_alHome = a})

-- | Set this parameter\'s value to true to retrieve a feed of the
-- authenticated user\'s activities.
alMine :: Lens' ActivitiesList (Maybe Bool)
alMine = lens _alMine (\ s a -> s{_alMine = a})

-- | The regionCode parameter instructs the API to return results for the
-- specified country. The parameter value is an ISO 3166-1 alpha-2 country
-- code. YouTube uses this value when the authorized user\'s previous
-- activity on YouTube does not provide enough information to generate the
-- activity feed.
alRegionCode :: Lens' ActivitiesList (Maybe Text)
alRegionCode
  = lens _alRegionCode (\ s a -> s{_alRegionCode = a})

-- | The channelId parameter specifies a unique YouTube channel ID. The API
-- will then return a list of that channel\'s activities.
alChannelId :: Lens' ActivitiesList (Maybe Text)
alChannelId
  = lens _alChannelId (\ s a -> s{_alChannelId = a})

-- | The pageToken parameter identifies a specific page in the result set
-- that should be returned. In an API response, the nextPageToken and
-- prevPageToken properties identify other pages that could be retrieved.
alPageToken :: Lens' ActivitiesList (Maybe Text)
alPageToken
  = lens _alPageToken (\ s a -> s{_alPageToken = a})

-- | The maxResults parameter specifies the maximum number of items that
-- should be returned in the result set.
alMaxResults :: Lens' ActivitiesList Word32
alMaxResults
  = lens _alMaxResults (\ s a -> s{_alMaxResults = a})
      . _Coerce

-- | The publishedBefore parameter specifies the date and time before which
-- an activity must have occurred for that activity to be included in the
-- API response. If the parameter value specifies a day, but not a time,
-- then any activities that occurred that day will be excluded from the
-- result set. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
-- format.
alPublishedBefore :: Lens' ActivitiesList (Maybe UTCTime)
alPublishedBefore
  = lens _alPublishedBefore
      (\ s a -> s{_alPublishedBefore = a})
      . mapping _DateTime

instance GoogleRequest ActivitiesList where
        type Rs ActivitiesList = ActivityListResponse
        type Scopes ActivitiesList =
             '["https://www.googleapis.com/auth/youtube",
               "https://www.googleapis.com/auth/youtube.force-ssl",
               "https://www.googleapis.com/auth/youtube.readonly"]
        requestClient ActivitiesList'{..}
          = go (Just _alPart) _alPublishedAfter _alHome _alMine
              _alRegionCode
              _alChannelId
              _alPageToken
              (Just _alMaxResults)
              _alPublishedBefore
              (Just AltJSON)
              youTubeService
          where go
                  = buildClient (Proxy :: Proxy ActivitiesListResource)
                      mempty

{'repo_name': 'brendanhay/gogol', 'stars': '220', 'repo_language': 'Haskell', 'file_name': 'GetBillingInfo.hs', 'mime_type': 'text/plain', 'hash': -3800003823192624780, 'source_dataset': 'data'}


/*
 * Copyright 2012, Red Hat, Inc. and individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution for a full
 * listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
 * site: http://www.fsf.org.
 */
package org.zanata.service.impl;

import static org.zanata.transaction.TransactionUtilImpl.runInTransaction;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.enterprise.context.RequestScoped;
import javax.persistence.EntityManager;
import com.google.common.collect.ImmutableList;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.deltaspike.jpa.api.transaction.Transactional;
import org.jetbrains.annotations.NotNull;
import org.zanata.async.Async;
import org.zanata.async.AsyncTaskHandle;
import org.zanata.async.AsyncTaskResult;
import org.zanata.common.ContentState;
import org.zanata.common.LocaleId;
import org.zanata.common.MergeType;
import org.zanata.common.util.ContentStateUtil;
import org.zanata.dao.DocumentDAO;
import org.zanata.dao.ProjectIterationDAO;
import org.zanata.dao.TextFlowDAO;
import org.zanata.dao.TextFlowTargetDAO;
import org.zanata.events.DocStatsEvent;
import org.zanata.events.DocumentLocaleKey;
import org.zanata.events.DocumentUploadedEvent;
import org.zanata.events.TextFlowTargetStateEvent;
import org.zanata.exception.ZanataServiceException;
import org.zanata.i18n.Messages;
import org.zanata.lock.Lock;
import org.zanata.model.HAccount;
import org.zanata.model.HDocument;
import org.zanata.model.HLocale;
import org.zanata.model.HPerson;
import org.zanata.model.HProjectIteration;
import org.zanata.model.HSimpleComment;
import org.zanata.model.HTextFlow;
import org.zanata.model.HTextFlowTarget;
import org.zanata.model.HTextFlowTargetHistory;
import org.zanata.model.type.EntityType;
import org.zanata.rest.dto.TranslationSourceType;
import org.zanata.rest.dto.resource.TextFlowTarget;
import org.zanata.rest.dto.resource.TranslationsResource;
import org.zanata.rest.service.ResourceUtils;
import org.zanata.security.ZanataIdentity;
import org.zanata.security.annotations.Authenticated;
import org.zanata.service.LocaleService;
import org.zanata.service.LockManagerService;
import org.zanata.service.TranslationMergeService;
import org.zanata.service.TranslationService;
import org.zanata.service.ValidationService;
import javax.enterprise.event.Event;
import org.zanata.util.ShortString;
import org.zanata.webtrans.shared.model.TransUnitId;
import org.zanata.webtrans.shared.model.TransUnitUpdateInfo;
import org.zanata.webtrans.shared.model.TransUnitUpdateRequest;
import org.zanata.webtrans.shared.model.ValidationAction;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import static org.zanata.events.TextFlowTargetStateEvent.TextFlowTargetStateChange;

@Named("translationServiceImpl")
@RequestScoped
public class TranslationServiceImpl implements TranslationService {
    private static final org.slf4j.Logger log =
            org.slf4j.LoggerFactory.getLogger(TranslationServiceImpl.class);
    private static final long serialVersionUID = -4409365256354251534L;

    @SuppressFBWarnings(value = "SE_BAD_FIELD")
    @Inject
    private EntityManager entityManager;
    @Inject
    private ProjectIterationDAO projectIterationDAO;
    @Inject
    private DocumentDAO documentDAO;
    @Inject
    private TextFlowDAO textFlowDAO;
    @Inject
    private TextFlowTargetDAO textFlowTargetDAO;
    @Inject
    private ResourceUtils resourceUtils;
    @Inject
    private LocaleService localeServiceImpl;
    @Inject
    private LockManagerService lockManagerServiceImpl;
    @Inject
    private ValidationService validationServiceImpl;
    @Inject
    @Authenticated
    private HAccount authenticatedAccount;
    @Inject
    private ZanataIdentity identity;
    @Inject
    private TranslationMergeServiceFactory translationMergeServiceFactory;
    @Inject
    private Messages msgs;
    @SuppressFBWarnings(value = "SE_BAD_FIELD")
    @Inject
    private Event<DocumentUploadedEvent> documentUploadedEvent;
    @SuppressFBWarnings(value = "SE_BAD_FIELD")
    @Inject
    private Event<TextFlowTargetStateEvent> textFlowTargetStateEvent;
    @SuppressFBWarnings(value = "SE_BAD_FIELD")
    @Inject
    private Event<DocStatsEvent> docStatsEvent;

    @Transactional
    @Override
    public List<TranslationResult> translate(LocaleId localeId,
            List<TransUnitUpdateRequest> translationRequests) {
        return translate(localeId, translationRequests, true);
    }

    /**
     * This is used when reverting translation
     *
     * @param localeId
     * @param translationRequests
     * @return
     */
    private List<TranslationResult> translateWithoutValidating(
            LocaleId localeId,
            List<TransUnitUpdateRequest> translationRequests) {
        return translate(localeId, translationRequests, false);
    }

    private List<TranslationResult> translate(LocaleId localeId,
            List<TransUnitUpdateRequest> translationRequests,
            boolean runValidation) {
        List<TranslationResult> results = new ArrayList<TranslationResult>();
        // avoid locale check if there is nothing to translate
        if (translationRequests.isEmpty()) {
            return results;
        }
        // single locale check - assumes update requests are all from the same
        // project-iteration
        HTextFlow sampleHTextFlow = entityManager.find(HTextFlow.class,
                translationRequests.get(0).getTransUnitId().getValue());
        HProjectIteration projectIteration =
                sampleHTextFlow.getDocument().getProjectIteration();
        HLocale hLocale = validateLocale(localeId, projectIteration);
        // single permission check - assumes update requests are all from same
        // project
        validateReviewPermissionIfApplicable(translationRequests,
                projectIteration, hLocale);
        List<TextFlowTargetStateChange> targetStates = Lists.newArrayList();
        Map<ContentState, Long> contentStateDeltas = Maps.newHashMap();
        for (TransUnitUpdateRequest request : translationRequests) {
            ContentState newContentState = request.getNewContentState();
            HTextFlow hTextFlow = entityManager.find(HTextFlow.class,
                    request.getTransUnitId().getValue());
            TranslationResultImpl result = new TranslationResultImpl();
            result.similarityPercent = request.getSimilarityPercent();
            if (runValidation) {
                String validationMessage = validateTranslations(
                        newContentState, projectIteration,
                        request.getTransUnitId().toString(),
                        hTextFlow.getContents(), request.getNewContents());
                boolean failedValidation = !StringUtils.isEmpty(validationMessage);
                if (failedValidation) {
                    ContentState existingState =
                            getTranslationState(hLocale, hTextFlow);
                    if (existingState.isTranslated()) {
                        // don't replace an existing translation with an invalid translation
                        log.warn(validationMessage);
                        result.isSuccess = false;
                        result.errorMessage = validationMessage;
                        results.add(result);
                        continue;
                    } else {
                        // if TFT was untranslated or fuzzy, use the new
                        // translation, but mark as fuzzy
                        newContentState = ContentState.NeedReview;
                    }
                }
            }
            result.newContentState = newContentState;
            HTextFlowTarget hTextFlowTarget =
                    textFlowTargetDAO.getOrCreateTarget(hTextFlow, hLocale);
            // if hTextFlowTarget is created, any further hibernate fetch will
            // trigger an implicit flush
            // (which will save this target even if it's not fully ready!!!)
            if (request.hasTargetComment()) {
                // FIXME this creates orphan comments, and replaces identical
                // comments with copies
                hTextFlowTarget.setComment(
                        new HSimpleComment(request.getTargetComment()));
            }
            result.baseVersion = hTextFlowTarget.getVersionNum();
            result.baseContentState = hTextFlowTarget.getState();
            if (request.getBaseTranslationVersion() == hTextFlowTarget
                    .getVersionNum()) {
                try {
                    int nPlurals = getNumPlurals(hLocale, hTextFlow);
                    ContentState currentState = hTextFlowTarget.getState();
                    result.targetChanged =
                            translate(hTextFlowTarget, request.getNewContents(),
                                    newContentState, nPlurals,
                                    new TranslationDetails(request));
                    // fire event after flush
                    if (result.targetChanged
                            || hTextFlowTarget.getVersionNum() == 0) {
                        HTextFlow textFlow = hTextFlowTarget.getTextFlow();
                        aggregateChanges(textFlow, hTextFlowTarget,
                                currentState, targetStates, contentStateDeltas);
                    }
                    result.isSuccess = true;
                } catch (HibernateException e) {
                    result.isSuccess = false;
                    log.warn("HibernateException while translating");
                }
            } else {
                // concurrent edits not allowed
                String errorMessage = "translation failed for textflow "
                        + hTextFlow.getId() + ": base versionNum + "
                        + request.getBaseTranslationVersion()
                        + " does not match current versionNum "
                        + hTextFlowTarget.getVersionNum();
                log.warn(errorMessage);
                result.errorMessage = errorMessage;
                result.isVersionNumConflict = true;
                result.isSuccess = false;
            }
            result.translatedTextFlowTarget = hTextFlowTarget;
            results.add(result);
        }
        if (!targetStates.isEmpty()) {
            DocumentLocaleKey documentLocaleKey =
                    new DocumentLocaleKey(sampleHTextFlow.getDocument().getId(),
                            hLocale.getLocaleId());
            TextFlowTargetStateEvent tftUpdatedEvent =
                    new TextFlowTargetStateEvent(documentLocaleKey,
                            projectIteration.getId(),
                            authenticatedAccount.getPerson().getId(),
                            ImmutableList.copyOf(targetStates));
            textFlowTargetStateEvent.fire(tftUpdatedEvent);
            DocStatsEvent docEvent = new DocStatsEvent(documentLocaleKey,
                    projectIteration.getId(), contentStateDeltas,
                    Iterables.getLast(targetStates).getTextFlowTargetId());
            docStatsEvent.fire(docEvent);
        }
        return results;
    }

    @NotNull
    private ContentState getTranslationState(HLocale hLocale,
            HTextFlow hTextFlow) {
        HTextFlowTarget hTextFlowTarget =
                textFlowTargetDAO.getTextFlowTarget(hTextFlow, hLocale);
        return hTextFlowTarget != null ? hTextFlowTarget.getState()
                : ContentState.New;
    }

    private void validateReviewPermissionIfApplicable(
            List<TransUnitUpdateRequest> translationRequests,
            HProjectIteration projectIteration, HLocale hLocale) {
        boolean hasReviewRequest = translationRequests.stream()
                .anyMatch(it -> isReviewState(it.getNewContentState()));
        if (hasReviewRequest) {
            identity.checkPermission("translation-review",
                    projectIteration.getProject(), hLocale);
        }
    }

    private static boolean isReviewState(ContentState contentState) {
        return contentState == ContentState.Approved
                || contentState == ContentState.Rejected;
    }

    /**
     * Generate a {@link HLocale} for the given localeId and check that
     * translations for this locale are permitted.
     *
     * @param localeId
     * @param projectIteration
     * @return the valid hLocale
     * @throws ZanataServiceException
     *             if the locale is not enabled for the project-iteration or
     *             server
     */
    private HLocale validateLocale(LocaleId localeId,
            HProjectIteration projectIteration) throws ZanataServiceException {
        String projectSlug = projectIteration.getProject().getSlug();
        return localeServiceImpl.validateLocaleByProjectIteration(localeId,
                projectSlug, projectIteration.getSlug());
    }

    public static class TranslationDetails {
        private final String revisionComment;
        private final EntityType copiedEntityType;
        private final TranslationSourceType sourceType;
        private final Long copiedEntityId;

        public TranslationDetails(String revisionComment,
                EntityType copiedEntityType, TranslationSourceType sourceType,
                Long copiedEntityId) {
            this.revisionComment = revisionComment;
            this.sourceType = sourceType;
            this.copiedEntityType = copiedEntityType;
            this.copiedEntityId = copiedEntityId;
        }

        public TranslationDetails(TransUnitUpdateRequest request) {
            this.revisionComment = request.getRevisionComment();
            this.copiedEntityId = request.getCopiedEntityId();
            copiedEntityType =
                    StringUtils.isEmpty(request.getCopiedEntityType()) ? null
                            : EntityType
                                    .getValueOf(request.getCopiedEntityType());
            sourceType = StringUtils.isEmpty(request.getSourceType()) ? null
                    : TranslationSourceType.getValueOf(request.getSourceType());
        }

        public String getRevisionComment() {
            return revisionComment;
        }

        public EntityType getCopiedEntityType() {
            return copiedEntityType;
        }

        public TranslationSourceType getSourceType() {
            return sourceType;
        }

        public Long getCopiedEntityId() {
            return copiedEntityId;
        }
    }

    private boolean translate(@Nonnull HTextFlowTarget hTextFlowTarget,
            @Nonnull List<String> contentsToSave, ContentState requestedState,
            int nPlurals, TranslationDetails details) {
        boolean targetChanged = false;
        targetChanged |= setContentIfChanged(hTextFlowTarget, contentsToSave);
        targetChanged |= setContentStateIfChanged(requestedState,
                hTextFlowTarget, nPlurals);
        if (targetChanged || hTextFlowTarget.getVersionNum() == 0) {
            HTextFlow textFlow = hTextFlowTarget.getTextFlow();
            hTextFlowTarget.setVersionNum(hTextFlowTarget.getVersionNum() + 1);
            hTextFlowTarget.setTextFlowRevision(textFlow.getRevision());
            hTextFlowTarget.setLastModifiedBy(authenticatedAccount.getPerson());
            hTextFlowTarget.setRevisionComment(details.getRevisionComment());
            hTextFlowTarget.setCopiedEntityType(details.getCopiedEntityType());
            hTextFlowTarget.setSourceType(details.getSourceType());
            hTextFlowTarget.setCopiedEntityId(details.getCopiedEntityId());
            log.debug("last modified by :{}",
                    authenticatedAccount.getPerson().getName());
        }
        // save the target histories
        entityManager.flush();
        return targetChanged;
    }

    /**
     * @return true if the content was changed, false otherwise
     */
    private boolean setContentIfChanged(
            @Nonnull HTextFlowTarget hTextFlowTarget,
            @Nonnull List<String> contentsToSave) {
        if (!contentsToSave.equals(hTextFlowTarget.getContents())) {
            hTextFlowTarget.setContents(contentsToSave);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Check that requestedState is valid for the given content, adjust if
     * necessary and set the new state if it has changed.
     *
     * @return true if the content state or contents list were updated, false
     *         otherwise
     * @see #adjustContentsAndState(org.zanata.model.HTextFlowTarget, int,
     *      java.util.List)
     */
    private boolean setContentStateIfChanged(
            @Nonnull ContentState requestedState,
            @Nonnull HTextFlowTarget target, int nPlurals) {
        boolean changed = false;
        ContentState previousState = target.getState();
        target.setState(requestedState);
        ArrayList<String> warnings = new ArrayList<String>();
        changed |= adjustContentsAndState(target, nPlurals, warnings);
        for (String warning : warnings) {
            log.warn(warning);
        }
        if (isReviewState(target.getState())) {
            // reviewer saved it
            target.setReviewer(authenticatedAccount.getPerson());
            if (previousState == ContentState.New) {
                target.setTranslator(authenticatedAccount.getPerson());
            }
        } else {
            target.setTranslator(authenticatedAccount.getPerson());
        }
        if (target.getState() != previousState) {
            changed = true;
        }
        return changed;
    }

    /**
     * Checks target state against its contents. If necessary, modifies target
     * state and generates a warning
     *
     * @param target
     *            HTextFlowTarget to check/modify
     * @param nPlurals
     *            number of plurals for this locale for this message: use 1 if
     *            message does not support plurals
     * @param warnings
     *            a warning string will be added if state is adjusted
     * @return true if and only if some state was changed
     */
    private static boolean adjustContentsAndState(
            @Nonnull HTextFlowTarget target, int nPlurals,
            @Nonnull List<String> warnings) {
        ContentState oldState = target.getState();
        String resId = target.getTextFlow().getResId();
        boolean contentsChanged =
                ensureContentsSize(target, nPlurals, resId, warnings);
        List<String> contents = target.getContents();
        target.setState(ContentStateUtil.determineState(oldState, contents,
                resId, warnings));
        boolean stateChanged = (oldState != target.getState());
        return contentsChanged || stateChanged;
    }

    /**
     * Ensures that target.contents has exactly legalSize elements
     *
     * @param target
     *            HTextFlowTarget to check/modify
     * @param legalSize
     *            required number of contents
     * @param resId
     *            ID of target
     * @param warnings
     *            if elements were added or removed
     * @return
     */
    private static boolean ensureContentsSize(HTextFlowTarget target,
            int legalSize, String resId, @Nonnull List<String> warnings) {
        int contentsSize = target.getContents().size();
        if (contentsSize < legalSize) {
            String warning = "Should have " + legalSize
                    + " contents; adding empty strings: TextFlowTarget " + resId
                    + " with contents: " + target.getContents();
            warnings.add(warning);
            List<String> newContents = new ArrayList<String>(legalSize);
            newContents.addAll(target.getContents());
            while (newContents.size() < legalSize) {
                newContents.add("");
            }
            target.setContents(newContents);
            return true;
        } else if (contentsSize > legalSize) {
            String warning = "Should have " + legalSize
                    + " contents; discarding extra strings: TextFlowTarget "
                    + resId + " with contents: " + target.getContents();
            warnings.add(warning);
            List<String> newContents = new ArrayList<String>(legalSize);
            for (int i = 0; i < legalSize; i++) {
                String content = target.getContents().get(i);
                newContents.add(content);
            }
            target.setContents(newContents);
            return true;
        }
        return false;
    }
    // This will not run in a transaction. Instead, transactions are controlled
    // within the method itself.

    @Override
    @Async
    public CompletableFuture<List<String>> translateAllInDocAsync(String projectSlug,
            String iterationSlug, String docId, LocaleId locale,
            TranslationsResource translations, Set<String> extensions,
            MergeType mergeType, boolean assignCreditToUploader, boolean lock,
            AsyncTaskHandle<?> handle,
            TranslationSourceType translationSourceType) {
        // Lock this document for push
        Lock transLock = null;
        if (lock) {
            transLock =
                    new Lock(projectSlug, iterationSlug, docId, locale, "push");
            lockManagerServiceImpl.attain(transLock);
        }
        List<String> warnings;
        try {
            warnings = this.translateAllInDoc(projectSlug, iterationSlug, docId,
                    locale, translations, extensions, mergeType,
                    assignCreditToUploader, handle, translationSourceType);
        } finally {
            if (lock) {
                lockManagerServiceImpl.release(transLock);
            }
        }
        return AsyncTaskResult.completed(warnings);
    }

    /**
     * Run enforced validation check(Error) if target has changed and
     * translation saving as 'Translated' or 'Approved'
     *
     * @param newState
     * @param projectVersion
     * @param targetId
     * @param sources
     * @param translations
     * @return error messages
     */
    private String validateTranslations(ContentState newState,
            HProjectIteration projectVersion, String targetId,
            List<String> sources, List<String> translations) {
        String message = null;
        if (newState.isTranslated()) {
            List<String> validationMessages = validationServiceImpl
                    .validateWithServerRules(projectVersion, sources,
                            translations, ValidationAction.State.Error);
            if (!validationMessages.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (String validationMessage : validationMessages) {
                    sb.append(validationMessage).append("\n");
                }
                message = msgs.format("jsf.TranslationContainsError",
                        ShortString.shorten(translations.get(0)),
                        sb.toString());
            }
        }
        return message;
    }

    @Override
    @Transactional
    public List<String> translateAllInDoc(final String projectSlug,
            final String iterationSlug, final String docId,
            final LocaleId locale, final TranslationsResource translations,
            final Set<String> extensions, final MergeType mergeType,
            final boolean assignCreditToUploader,
            final TranslationSourceType translationSourceType) {
        return translateAllInDoc(projectSlug, iterationSlug, docId, locale,
                translations, extensions, mergeType, assignCreditToUploader,
                null, translationSourceType);
    }
    // can't use @Transactional because we call runInTransaction

    @Override
    public List<String> translateAllInDoc(final String projectSlug,
            final String iterationSlug, final String docId,
            final LocaleId locale, final TranslationsResource translations,
            final Set<String> extensions, final MergeType mergeType,
            final boolean assignCreditToUploader, AsyncTaskHandle<?> handle,
            final TranslationSourceType translationSourceType) {
        final HProjectIteration hProjectIteration =
                projectIterationDAO.getBySlug(projectSlug, iterationSlug);
        if (hProjectIteration == null) {
            throw new ZanataServiceException("Version \'" + iterationSlug
                    + "\' for project \'" + projectSlug + "\' ");
        }
        if (mergeType == MergeType.IMPORT) {
            identity.checkPermission("import-translation", hProjectIteration);
        }
        ResourceUtils.validateExtensions(extensions);
        log.debug("pass evaluate");
        final HDocument document =
                documentDAO.getByDocIdAndIteration(hProjectIteration, docId);
        if (document == null || document.isObsolete()) {
            throw new ZanataServiceException("A document was not found.", 404);
        }
        log.debug("start put translations entity:{}", translations);
        boolean changed = false;
        final HLocale hLocale =
                localeServiceImpl.validateLocaleByProjectIteration(locale,
                        projectSlug, iterationSlug);
        final Optional<AsyncTaskHandle<?>> handleOp =
                Optional.fromNullable(handle);
        if (handleOp.isPresent()) {
            handleOp.get()
                    .setMaxProgress(translations.getTextFlowTargets().size());
        }
        try {
            changed |= runInTransaction(() ->
            // handle extensions
            resourceUtils.transferFromTranslationsResourceExtensions(
                    translations.getExtensions(true), document, extensions,
                    hLocale, mergeType));
        } catch (Exception e) {
            log.error(
                    "exception in transferFromTranslationsResourceExtensions: {}",
                    e.getMessage());
            throw new ZanataServiceException("Error during translation.", 500,
                    e);
        }
        // NB: removedTargets only applies for MergeType.IMPORT
        final Collection<Long> removedTextFlowTargetIds = new HashSet<>();
        final List<String> warnings = new ArrayList<String>();
        if (mergeType == MergeType.IMPORT) {
            for (HTextFlow textFlow : document.getTextFlows()) {
                HTextFlowTarget hTarget =
                        textFlow.getTargets().get(hLocale.getId());
                if (hTarget != null) {
                    removedTextFlowTargetIds.add(hTarget.getId());
                }
            }
        }
        // Break the target into batches
        List<List<TextFlowTarget>> batches =
                Lists.partition(translations.getTextFlowTargets(), BATCH_SIZE);
        for (final List<TextFlowTarget> batch : batches) {
            try {
                changed |= runInTransaction(
                        () -> saveBatch(extensions, warnings, hLocale, document,
                                mergeType, removedTextFlowTargetIds, handleOp,
                                hProjectIteration.getId(), batch,
                                assignCreditToUploader, translationSourceType));
            } catch (Exception e) {
                log.error("exception saving translation batch: {}",
                        e.getMessage());
                throw new ZanataServiceException("Error during translation.",
                        500, e);
            }
        }
        if (changed || !removedTextFlowTargetIds.isEmpty()) {
            try {
                runInTransaction(() -> {
                    for (Long targetId : removedTextFlowTargetIds) {
                        // need to refresh from persistence
                        HTextFlowTarget target =
                                textFlowTargetDAO.findById(targetId, true);
                        target.clear();
                    }
                    textFlowTargetDAO.flush();
                    documentDAO.flush();
                    return null;
                });
                Long actorId = authenticatedAccount.getPerson().getId();
                documentUploadedEvent.fire(new DocumentUploadedEvent(actorId,
                        document.getId(), false, hLocale.getLocaleId()));
            } catch (Exception e) {
                log.error("exception in removeTargets: {}", e.getMessage());
                throw new ZanataServiceException("Error during translation.",
                        500, e);
            }
        }
        return warnings;
    }

    private int getNumPlurals(HLocale hLocale, HTextFlow textFlow) {
        int nPlurals;
        if (!textFlow.isPlural()) {
            nPlurals = 1;
        } else {
            nPlurals = resourceUtils.getNumPlurals(textFlow.getDocument(),
                    hLocale);
        }
        return nPlurals;
    }

    private Boolean saveBatch(final Set<String> extensions,
            final List<String> warnings, final HLocale locale,
            HDocument document, final MergeType mergeType,
            final Collection<Long> removedTextFlowTargetIds,
            final Optional<AsyncTaskHandle<?>> handleOp,
            final Long projectIterationId, final List<TextFlowTarget> batch,
            final boolean assignCreditToUploader,
            final TranslationSourceType translationSourceType) {
        // we need to call clear at the beginning because text flow target
        // history rely on after commit callback.
        textFlowTargetDAO.clear();
        document = entityManager.find(HDocument.class, document.getId());
        boolean changed = false;
        // we need a fresh object in this session,
        // so that it can lazily load associated objects
        HProjectIteration iteration =
                projectIterationDAO.findById(projectIterationId);
        List<String> resIds = batch.stream()
                .map(TextFlowTarget::getResId)
                .collect(Collectors.toList());
        Map<String, HTextFlow> resIdToTextFlowMap =
                textFlowDAO.getByDocumentAndResIds(document, resIds);
        final int numPlurals = resourceUtils.getNumPlurals(document, locale);
        List<TextFlowTargetStateChange> targetStates = Lists.newArrayList();
        Map<ContentState, Long> contentStateDeltas = Maps.newHashMap();
        for (TextFlowTarget incomingTarget : batch) {
            String resId = incomingTarget.getResId();
            String sourceHash = incomingTarget.getSourceHash();
            HTextFlow textFlow = resIdToTextFlowMap.get(resId);
            if (textFlow == null) {
                // return warning for unknown resId to caller
                String warning = "Could not find TextFlow for TextFlowTarget "
                        + resId + " with contents: "
                        + incomingTarget.getContents();
                warnings.add(warning);
                log.warn("skipping TextFlowTarget with unknown resId: {}",
                        resId);
            } else if (sourceHash != null
                    && !sourceHash.equals(textFlow.getContentHash())) {
                String warning = MessageFormat.format(
                        "TextFlowTarget {0} may be obsolete; associated source hash: {1}; expected hash is {2} for source: {3}",
                        resId, sourceHash, textFlow.getContentHash(),
                        textFlow.getContents());
                warnings.add(warning);
                log.warn(
                        "skipping TextFlowTarget {} with unknown sourceHash: {}",
                        resId, sourceHash);
            } else {
                String validationMessage = validateTranslations(
                        incomingTarget.getState(), iteration,
                        incomingTarget.getResId(), textFlow.getContents(),
                        incomingTarget.getContents());
                if (!StringUtils.isEmpty(validationMessage)) {
                    warnings.add(validationMessage);
                    log.warn(validationMessage);
                    continue;
                }
                int nPlurals = textFlow.isPlural() ? numPlurals : 1;
                // we have eagerly loaded all targets upfront
                HTextFlowTarget hTarget =
                        textFlow.getTargets().get(locale.getId());
                ContentState oldState = ContentState.New;
                if (hTarget != null) {
                    oldState = hTarget.getState();
                    if (mergeType == MergeType.IMPORT) {
                        removedTextFlowTargetIds.remove(hTarget.getId());
                    }
                }
                TranslationMergeServiceFactory.MergeContext mergeContext =
                        new TranslationMergeServiceFactory.MergeContext(
                                mergeType, textFlow, locale, hTarget, nPlurals);
                TranslationMergeService mergeService =
                        translationMergeServiceFactory
                                .getMergeService(mergeContext);
                boolean targetChanged =
                        mergeService.merge(incomingTarget, hTarget, extensions);
                if (hTarget == null) {
                    // in case hTarget was null, we need to
                    // retrieve it after merge
                    hTarget = textFlow.getTargets().get(locale.getId());
                }
                targetChanged |=
                        adjustContentsAndState(hTarget, nPlurals, warnings);
                // update translation information if applicable
                if (targetChanged) {
                    hTarget.setVersionNum(hTarget.getVersionNum() + 1);
                    changed = true;
                    if (assignCreditToUploader) {
                        HPerson hPerson = authenticatedAccount.getPerson();
                        hTarget.setTranslator(hPerson);
                        hTarget.setLastModifiedBy(hPerson);
                    } else {
                        hTarget.setTranslator(null);
                        hTarget.setLastModifiedBy(
                                authenticatedAccount.getPerson());
                    }
                    hTarget.setSourceType(translationSourceType);
                    hTarget.setCopiedEntityId(null);
                    hTarget.setCopiedEntityId(null);
                    textFlowTargetDAO.makePersistent(hTarget);
                    aggregateChanges(textFlow, hTarget, oldState, targetStates,
                            contentStateDeltas);
                }
            }
            if (handleOp.isPresent()) {
                handleOp.get().increaseProgress(1);
            }
        }
        if (!targetStates.isEmpty()) {
            Long actorId = assignCreditToUploader
                    ? authenticatedAccount.getPerson().getId() : null;
            DocumentLocaleKey documentLocaleKey = new DocumentLocaleKey(
                    document.getId(), locale.getLocaleId());
            TextFlowTargetStateEvent tftUpdatedEvent =
                    new TextFlowTargetStateEvent(documentLocaleKey,
                            projectIterationId, actorId,
                            ImmutableList.copyOf(targetStates));
            textFlowTargetStateEvent.fire(tftUpdatedEvent);
            DocStatsEvent docEvent = new DocStatsEvent(documentLocaleKey,
                    projectIterationId, contentStateDeltas,
                    Iterables.getLast(tftUpdatedEvent.getStates())
                            .getTextFlowTargetId());
            docStatsEvent.fire(docEvent);
        }
        textFlowTargetDAO.flush();
        return changed;
    }

    private void aggregateChanges(HTextFlow textFlow, HTextFlowTarget hTarget,
            ContentState oldState, List<TextFlowTargetStateChange> targetStates,
            Map<ContentState, Long> contentStateDeltas) {
        TextFlowTargetStateChange state =
                new TextFlowTargetStateChange(textFlow.getId(), hTarget.getId(),
                        hTarget.getState(), oldState);
        targetStates.add(state);
        DocStatsEvent.updateContentStateDeltas(contentStateDeltas,
                state.getNewState(), state.getPreviousState(),
                textFlow.getWordCount());
    }

    public static class TranslationResultImpl implements TranslationResult {

        private HTextFlowTarget translatedTextFlowTarget;
        private boolean isSuccess;
        private boolean targetChanged = false;
        private boolean isVersionNumConflict = false;
        private int baseVersion;
        private ContentState baseContentState;
        private ContentState newContentState;
        private String errorMessage;
        private double similarityPercent;

        TranslationResultImpl() {
        }

        @Override
        public boolean isTranslationSuccessful() {
            return isSuccess;
        }

        @Override
        public boolean isVersionNumConflict() {
            return isVersionNumConflict;
        }

        @Override
        public boolean isTargetChanged() {
            return targetChanged;
        }

        @Override
        public HTextFlowTarget getTranslatedTextFlowTarget() {
            return translatedTextFlowTarget;
        }

        @Override
        public int getBaseVersionNum() {
            return baseVersion;
        }

        @Override
        public ContentState getBaseContentState() {
            return baseContentState;
        }

        @Override
        public ContentState getNewContentState() {
            return newContentState;
        }

        @Override
        public String getErrorMessage() {
            return errorMessage;
        }

        @Override
        public double getSimilarityPercent() {
            return similarityPercent;
        }

    }

    @Override
    @Transactional
    public List<TranslationResult> revertTranslations(LocaleId localeId,
            List<TransUnitUpdateInfo> translationsToRevert) {
        List<TranslationResult> results = new ArrayList<TranslationResult>();
        List<TransUnitUpdateRequest> updateRequests =
                new ArrayList<TransUnitUpdateRequest>();
        if (!translationsToRevert.isEmpty()) {
            HTextFlow sampleHTextFlow =
                    entityManager.find(HTextFlow.class, translationsToRevert
                            .get(0).getTransUnit().getId().getValue());
            HLocale hLocale = validateLocale(localeId,
                    sampleHTextFlow.getDocument().getProjectIteration());
            for (TransUnitUpdateInfo info : translationsToRevert) {
                if (!info.isSuccess() || !info.isTargetChanged()) {
                    continue;
                }
                TransUnitId tuId = info.getTransUnit().getId();
                HTextFlow hTextFlow =
                        entityManager.find(HTextFlow.class, tuId.getValue());
                HTextFlowTarget hTextFlowTarget =
                        textFlowTargetDAO.getOrCreateTarget(hTextFlow, hLocale);
                // check that version has not advanced
                // TODO probably also want to check that source has not been
                // updated
                Integer versionNum = hTextFlowTarget.getVersionNum();
                log.debug(
                        "about to revert hTextFlowTarget version {} to TransUnit version {}",
                        versionNum, info.getTransUnit().getVerNum());
                if (versionNum.equals(info.getTransUnit().getVerNum())) {
                    // look up replaced version
                    HTextFlowTargetHistory oldTarget = hTextFlowTarget
                            .getHistory().get(info.getPreviousVersionNum());
                    if (oldTarget != null) {
                        // generate request
                        List<String> oldContents = oldTarget.getContents();
                        ContentState oldState = oldTarget.getState();
                        String copiedEntityType =
                                oldTarget.getCopiedEntityType() == null ? null
                                        : oldTarget.getCopiedEntityType()
                                                .getAbbr();
                        String sourceType = oldTarget.getSourceType() == null
                                ? TranslationSourceType.UNKNOWN.getAbbr()
                                : oldTarget.getSourceType().getAbbr();
                        TransUnitUpdateRequest request =
                                new TransUnitUpdateRequest(tuId, oldContents,
                                        oldState, versionNum,
                                        oldTarget.getRevisionComment(),
                                        oldTarget.getCopiedEntityId(),
                                        copiedEntityType, sourceType);
                        // add to list
                        updateRequests.add(request);
                    } else {
                        log.info(
                                "got null previous target for tu with id {}, version {}. Assuming previous state is untranslated",
                                hTextFlow.getId(),
                                info.getPreviousVersionNum());
                        List<String> emptyContents = Lists.newArrayList();
                        for (int i = 0; i < hTextFlowTarget.getContents()
                                .size(); i++) {
                            emptyContents.add("");
                        }
                        TransUnitUpdateRequest request =
                                new TransUnitUpdateRequest(tuId, emptyContents,
                                        ContentState.New, versionNum,
                                        TranslationSourceType.UNKNOWN
                                                .getAbbr());
                        updateRequests.add(request);
                    }
                } else {
                    log.info(
                            "attempt to revert target version {} for tu with id {}, but current version is {}. Not reverting.",
                            new Object[] { info.getTransUnit().getVerNum(),
                                    tuId, versionNum });
                    results.add(buildFailResult(hTextFlowTarget));
                }
            }
        }
        results.addAll(translateWithoutValidating(localeId, updateRequests));
        return results;
    }

    /**
     * @param hTextFlowTarget
     * @return
     */
    private TranslationResultImpl
            buildFailResult(HTextFlowTarget hTextFlowTarget) {
        TranslationResultImpl result = new TranslationResultImpl();
        result.baseVersion = hTextFlowTarget.getVersionNum();
        result.baseContentState = hTextFlowTarget.getState();
        result.isSuccess = false;
        result.isVersionNumConflict = false;
        result.translatedTextFlowTarget = hTextFlowTarget;
        result.errorMessage = null;
        return result;
    }
}

{'repo_name': 'zanata/zanata-platform', 'stars': '271', 'repo_language': 'Java', 'file_name': 'QueryParserTest.java', 'mime_type': 'text/x-java', 'hash': 5492381028441145298, 'source_dataset': 'data'}


package io.dddbyexamples.cqrs.sink;

class CreditCardStateChanged {

    private String op;
    private String ts_ms;
    private Card before;
    private Card after;

    String getOp() {
        return op;
    }

    void setOp(String op) {
        this.op = op;
    }

    Card getBefore() {
        return before;
    }

    void setBefore(Card before) {
        this.before = before;
    }

    String getTs_ms() {
        return ts_ms;
    }

    void setTs_ms(String ts_ms) {
        this.ts_ms = ts_ms;
    }

    Card getAfter() {
        return after;
    }

    void setAfter(Card after) {
        this.after = after;
    }
}

{'repo_name': 'ddd-by-examples/all-things-cqrs', 'stars': '407', 'repo_language': 'Java', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 453933335011542578, 'source_dataset': 'data'}


import { BoundingSphere } from "../../Source/Cesium.js";
import { Cartesian3 } from "../../Source/Cesium.js";
import { Ellipsoid } from "../../Source/Cesium.js";
import { EllipsoidalOccluder } from "../../Source/Cesium.js";
import { IntersectionTests } from "../../Source/Cesium.js";
import { Math as CesiumMath } from "../../Source/Cesium.js";
import { Ray } from "../../Source/Cesium.js";
import { Rectangle } from "../../Source/Cesium.js";

describe("Core/EllipsoidalOccluder", function () {
  it("uses ellipsoid", function () {
    var ellipsoid = new Ellipsoid(2.0, 3.0, 4.0);
    var occluder = new EllipsoidalOccluder(ellipsoid);
    expect(occluder.ellipsoid).toEqual(ellipsoid);
  });

  it("throws if ellipsoid is not provided to constructor", function () {
    function createOccluderWithoutEllipsoid() {
      return new EllipsoidalOccluder(undefined, new Cartesian3(1.0, 2.0, 3.0));
    }
    expect(createOccluderWithoutEllipsoid).toThrowDeveloperError();
  });

  it("isPointVisible example works as claimed", function () {
    var cameraPosition = new Cartesian3(0, 0, 2.5);
    var ellipsoid = new Ellipsoid(1.0, 1.1, 0.9);
    var occluder = new EllipsoidalOccluder(ellipsoid, cameraPosition);
    var point = new Cartesian3(0, -3, -3);
    expect(occluder.isPointVisible(point)).toEqual(true);
  });

  it("isScaledSpacePointVisible example works as claimed", function () {
    var cameraPosition = new Cartesian3(0, 0, 2.5);
    var ellipsoid = new Ellipsoid(1.0, 1.1, 0.9);
    var occluder = new EllipsoidalOccluder(ellipsoid, cameraPosition);
    var point = new Cartesian3(0, -3, -3);
    var scaledSpacePoint = ellipsoid.transformPositionToScaledSpace(point);
    expect(occluder.isScaledSpacePointVisible(scaledSpacePoint)).toEqual(true);
  });

  it("isScaledSpacePointVisiblePossiblyUnderEllipsoid example works as claimed", function () {
    // Tests points that are halfway inside a unit sphere:
    // 1) on the diagonal
    // 2) on the +y-axis
    // The camera is on the +z-axis so it will be able to see the diagonal point but not the +y-axis point.

    var cameraPosition = new Cartesian3(0, 0, 1.0);
    var ellipsoid = new Ellipsoid(1.0, 1.0, 1.0);
    var occluder = new EllipsoidalOccluder(ellipsoid, cameraPosition);
    var height = -0.5;

    var direction = Cartesian3.normalize(
      new Cartesian3(1.0, 1.0, 1.0),
      new Cartesian3()
    );
    var point = Cartesian3.multiplyByScalar(direction, 0.5, new Cartesian3());
    var scaledSpacePoint = occluder.computeHorizonCullingPoint(point, [point]);
    var scaledSpacePointShrunk = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
      point,
      [point],
      height
    );

    expect(occluder.isScaledSpacePointVisible(scaledSpacePoint)).toEqual(false);
    expect(
      occluder.isScaledSpacePointVisiblePossiblyUnderEllipsoid(
        scaledSpacePointShrunk,
        height
      )
    ).toEqual(true);

    direction = new Cartesian3(0.0, 1.0, 0.0);
    point = Cartesian3.multiplyByScalar(direction, 0.5, new Cartesian3());
    scaledSpacePoint = occluder.computeHorizonCullingPoint(point, [point]);
    scaledSpacePointShrunk = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
      point,
      [point],
      height
    );

    expect(occluder.isScaledSpacePointVisible(scaledSpacePoint)).toEqual(false);
    expect(
      occluder.isScaledSpacePointVisiblePossiblyUnderEllipsoid(
        scaledSpacePointShrunk,
        height
      )
    ).toEqual(false);
  });

  it("reports not visible when point is directly behind ellipsoid", function () {
    var ellipsoid = Ellipsoid.WGS84;
    var occluder = new EllipsoidalOccluder(ellipsoid);
    occluder.cameraPosition = new Cartesian3(7000000.0, 0.0, 0.0);

    var point = new Cartesian3(-7000000, 0.0, 0.0);
    expect(occluder.isPointVisible(point)).toEqual(false);
  });

  it("reports not visible when point is directly behind ellipsoid and camera is inside the ellispoid", function () {
    var ellipsoid = Ellipsoid.WGS84;
    var occluder = new EllipsoidalOccluder(ellipsoid);
    occluder.cameraPosition = new Cartesian3(
      ellipsoid.minimumRadius - 100,
      0.0,
      0.0
    );

    var point = new Cartesian3(-7000000, 0.0, 0.0);
    expect(occluder.isPointVisible(point)).toEqual(false);
  });

  it("reports visible when point is in front of ellipsoid", function () {
    var ellipsoid = Ellipsoid.WGS84;
    var occluder = new EllipsoidalOccluder(ellipsoid);
    occluder.cameraPosition = new Cartesian3(7000000.0, 0.0, 0.0);

    var point = new Cartesian3(6900000.0, 0.0, 0.0);
    expect(occluder.isPointVisible(point)).toEqual(true);
  });

  it("reports visible when point is in opposite direction from ellipsoid", function () {
    var ellipsoid = Ellipsoid.WGS84;
    var occluder = new EllipsoidalOccluder(ellipsoid);
    occluder.cameraPosition = new Cartesian3(7000000.0, 0.0, 0.0);

    var point = new Cartesian3(7100000.0, 0.0, 0.0);
    expect(occluder.isPointVisible(point)).toEqual(true);
  });

  it("reports not visible when point is over horizon", function () {
    var ellipsoid = Ellipsoid.WGS84;
    var occluder = new EllipsoidalOccluder(ellipsoid);
    occluder.cameraPosition = new Cartesian3(7000000.0, 0.0, 0.0);

    var point = new Cartesian3(4510635.0, 4510635.0, 0.0);
    expect(occluder.isPointVisible(point)).toEqual(false);
  });

  describe("computeHorizonCullingPoint", function () {
    it("requires directionToPoint and positions", function () {
      var ellipsoid = new Ellipsoid(12345.0, 12345.0, 12345.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var positions = [new Cartesian3(-12345.0, 12345.0, 12345.0)];
      var directionToPoint = BoundingSphere.fromPoints(positions).center;

      expect(function () {
        ellipsoidalOccluder.computeHorizonCullingPoint(undefined, positions);
      }).toThrowDeveloperError();

      expect(function () {
        ellipsoidalOccluder.computeHorizonCullingPoint(
          directionToPoint,
          undefined
        );
      }).toThrowDeveloperError();
    });

    it("returns point on ellipsoid when single position is on center line", function () {
      var ellipsoid = new Ellipsoid(12345.0, 4567.0, 8910.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var positions = [new Cartesian3(12345.0, 0.0, 0.0)];
      var directionToPoint = new Cartesian3(1.0, 0.0, 0.0);

      var result = ellipsoidalOccluder.computeHorizonCullingPoint(
        directionToPoint,
        positions
      );

      expect(result.x).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
      expect(result.y).toEqualEpsilon(0.0, CesiumMath.EPSILON14);
      expect(result.z).toEqualEpsilon(0.0, CesiumMath.EPSILON14);
    });

    it("returns undefined when horizon of single point is parallel to center line", function () {
      var ellipsoid = new Ellipsoid(12345.0, 4567.0, 8910.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var positions = [new Cartesian3(0.0, 4567.0, 0.0)];
      var directionToPoint = new Cartesian3(1.0, 0.0, 0.0);

      var result = ellipsoidalOccluder.computeHorizonCullingPoint(
        directionToPoint,
        positions
      );
      expect(result).toBeUndefined();
    });

    it("returns undefined when single point is in the opposite direction of the center line", function () {
      var ellipsoid = new Ellipsoid(12345.0, 4567.0, 8910.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var positions = [new Cartesian3(-14000.0, -1000.0, 0.0)];
      var directionToPoint = new Cartesian3(1.0, 0.0, 0.0);

      var result = ellipsoidalOccluder.computeHorizonCullingPoint(
        directionToPoint,
        positions
      );
      expect(result).toBeUndefined();
    });

    it("returns undefined when any point is in the opposite direction of the center line", function () {
      var ellipsoid = new Ellipsoid(1.0, 1.0, 1.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var positions = [
        new Cartesian3(2.0, 0.0, 0.0),
        new Cartesian3(-1.0, 0.0, 0.0),
      ];
      var directionToPoint = new Cartesian3(1.0, 0.0, 0.0);

      var result = ellipsoidalOccluder.computeHorizonCullingPoint(
        directionToPoint,
        positions
      );
      expect(result).toBeUndefined();
    });

    it("returns undefined when the direction is zero", function () {
      var ellipsoid = new Ellipsoid(1.0, 1.0, 1.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var positions = [new Cartesian3(1.0, 0.0, 0.0)];
      var directionToPoint = new Cartesian3(0.0, 0.0, 0.0);

      var result = ellipsoidalOccluder.computeHorizonCullingPoint(
        directionToPoint,
        positions
      );
      expect(result).toBeUndefined();
    });

    it("computes a point from a single position with a grazing altitude close to zero", function () {
      var ellipsoid = new Ellipsoid(12345.0, 12345.0, 12345.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);

      var positions = [
        new Cartesian3(-12345.0, 12345.0, 12345.0),
        new Cartesian3(-12346.0, 12345.0, 12345.0),
      ];
      var boundingSphere = BoundingSphere.fromPoints(positions);

      var firstPositionArray = [positions[0]];
      var result = ellipsoidalOccluder.computeHorizonCullingPoint(
        boundingSphere.center,
        firstPositionArray
      );
      var unscaledResult = Cartesian3.multiplyComponents(
        result,
        ellipsoid.radii,
        new Cartesian3()
      );

      // The grazing altitude of the ray from the horizon culling point to the
      // position used to compute it should be very nearly zero.
      var direction = Cartesian3.normalize(
        Cartesian3.subtract(positions[0], unscaledResult, new Cartesian3()),
        new Cartesian3()
      );
      var nearest = IntersectionTests.grazingAltitudeLocation(
        new Ray(unscaledResult, direction),
        ellipsoid
      );
      var nearestCartographic = ellipsoid.cartesianToCartographic(nearest);
      expect(nearestCartographic.height).toEqualEpsilon(
        0.0,
        CesiumMath.EPSILON5
      );
    });

    it("computes a point from multiple positions with a grazing altitude close to zero for one of the positions and less than zero for the others", function () {
      var ellipsoid = new Ellipsoid(12345.0, 12345.0, 12345.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);

      var positions = [
        new Cartesian3(-12345.0, 12345.0, 12345.0),
        new Cartesian3(-12346.0, 12345.0, 12345.0),
        new Cartesian3(-12446.0, 12445.0, 12445.0),
      ];
      var boundingSphere = BoundingSphere.fromPoints(positions);

      var result = ellipsoidalOccluder.computeHorizonCullingPoint(
        boundingSphere.center,
        positions
      );
      var unscaledResult = Cartesian3.multiplyComponents(
        result,
        ellipsoid.radii,
        new Cartesian3()
      );

      // The grazing altitude of the ray from the horizon culling point to the
      // position used to compute it should be very nearly zero.
      var foundOneNearZero = false;
      for (var i = 0; i < positions.length; ++i) {
        var direction = Cartesian3.normalize(
          Cartesian3.subtract(positions[i], unscaledResult, new Cartesian3()),
          new Cartesian3()
        );
        var nearest = IntersectionTests.grazingAltitudeLocation(
          new Ray(unscaledResult, direction),
          ellipsoid
        );
        var nearestCartographic = ellipsoid.cartesianToCartographic(nearest);
        if (Math.abs(nearestCartographic.height) < CesiumMath.EPSILON5) {
          foundOneNearZero = true;
        } else {
          expect(nearestCartographic.height).toBeLessThan(0.0);
        }
      }

      expect(foundOneNearZero).toBe(true);
    });

    it("computes a point under the ellipsoid with computeHorizonCullingPointPossiblyUnderEllipsoid", function () {
      var ellipsoid = new Ellipsoid(12345.0, 4567.0, 8910.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var positions = [new Cartesian3(12344.0, 0.0, 0.0)];
      var directionToPoint = new Cartesian3(1.0, 0.0, 0.0);

      var result = ellipsoidalOccluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
        directionToPoint,
        positions,
        -1.0
      );

      expect(result.x).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
      expect(result.y).toEqualEpsilon(0.0, CesiumMath.EPSILON14);
      expect(result.z).toEqualEpsilon(0.0, CesiumMath.EPSILON14);
    });
  });

  describe("computeHorizonCullingPointFromVertices", function () {
    it("requires directionToPoint, vertices, and stride", function () {
      var ellipsoid = new Ellipsoid(12345.0, 12345.0, 12345.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);

      var positions = [
        new Cartesian3(-12345.0, 12345.0, 12345.0),
        new Cartesian3(-12346.0, 12345.0, 12345.0),
        new Cartesian3(-12446.0, 12445.0, 12445.0),
      ];
      var boundingSphere = BoundingSphere.fromPoints(positions);

      var vertices = [];
      for (var i = 0; i < positions.length; ++i) {
        var position = positions[i];
        vertices.push(position.x);
        vertices.push(position.y);
        vertices.push(position.z);
        vertices.push(1.0);
        vertices.push(2.0);
        vertices.push(3.0);
        vertices.push(4.0);
      }

      ellipsoidalOccluder.computeHorizonCullingPointFromVertices(
        boundingSphere.center,
        vertices,
        7
      );

      expect(function () {
        ellipsoidalOccluder.computeHorizonCullingPointFromVertices(
          undefined,
          vertices,
          7
        );
      }).toThrowDeveloperError();

      expect(function () {
        ellipsoidalOccluder.computeHorizonCullingPointFromVertices(
          boundingSphere.center,
          undefined,
          7
        );
      }).toThrowDeveloperError();

      expect(function () {
        ellipsoidalOccluder.computeHorizonCullingPointFromVertices(
          boundingSphere.center,
          vertices,
          undefined
        );
      }).toThrowDeveloperError();
    });

    it("produces same answers as computeHorizonCullingPoint", function () {
      var ellipsoid = new Ellipsoid(12345.0, 12345.0, 12345.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);

      var positions = [
        new Cartesian3(-12345.0, 12345.0, 12345.0),
        new Cartesian3(-12346.0, 12345.0, 12345.0),
        new Cartesian3(-12446.0, 12445.0, 12445.0),
      ];
      var boundingSphere = BoundingSphere.fromPoints(positions);

      var center = new Cartesian3(-12000.0, 12000.0, 12000.0);

      var vertices = [];
      for (var i = 0; i < positions.length; ++i) {
        var position = positions[i];
        vertices.push(position.x - center.x);
        vertices.push(position.y - center.y);
        vertices.push(position.z - center.z);
        vertices.push(1.0);
        vertices.push(2.0);
        vertices.push(3.0);
        vertices.push(4.0);
      }

      var result1 = ellipsoidalOccluder.computeHorizonCullingPoint(
        boundingSphere.center,
        positions
      );
      var result2 = ellipsoidalOccluder.computeHorizonCullingPointFromVertices(
        boundingSphere.center,
        vertices,
        7,
        center
      );

      expect(result1.x).toEqualEpsilon(result2.x, CesiumMath.EPSILON14);
      expect(result1.y).toEqualEpsilon(result2.y, CesiumMath.EPSILON14);
      expect(result1.z).toEqualEpsilon(result2.z, CesiumMath.EPSILON14);
    });

    it("computes a point under the ellipsoid with computeHorizonCullingPointFromVerticesPossiblyUnderEllipsoid", function () {
      var ellipsoid = new Ellipsoid(12345.0, 4567.0, 8910.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var vertices = [12344.0, 0.0, 0.0];
      var directionToPoint = new Cartesian3(1.0, 0.0, 0.0);
      var center = Cartesian3.ZERO;

      var result = ellipsoidalOccluder.computeHorizonCullingPointFromVerticesPossiblyUnderEllipsoid(
        directionToPoint,
        vertices,
        3,
        center,
        -1.0
      );

      expect(result.x).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
      expect(result.y).toEqualEpsilon(0.0, CesiumMath.EPSILON14);
      expect(result.z).toEqualEpsilon(0.0, CesiumMath.EPSILON14);
    });
  });

  describe("computeHorizonCullingPointFromRectangle", function () {
    it("returns undefined for global rectangle", function () {
      var ellipsoid = new Ellipsoid(12345.0, 12345.0, 12345.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);
      var rectangle = Rectangle.MAX_VALUE;
      var result = ellipsoidalOccluder.computeHorizonCullingPointFromRectangle(
        rectangle,
        ellipsoid
      );
      expect(result).toBeUndefined();
    });

    it("computes a point with a grazing altitude close to zero for one of the rectangle corners and less than or equal to zero for the others", function () {
      var ellipsoid = new Ellipsoid(12345.0, 12345.0, 12345.0);
      var ellipsoidalOccluder = new EllipsoidalOccluder(ellipsoid);

      var rectangle = new Rectangle(0.1, 0.2, 0.3, 0.4);
      var result = ellipsoidalOccluder.computeHorizonCullingPointFromRectangle(
        rectangle,
        ellipsoid
      );
      expect(result).toBeDefined();
      var unscaledResult = Cartesian3.multiplyComponents(
        result,
        ellipsoid.radii,
        new Cartesian3()
      );

      // The grazing altitude of the ray from the horizon culling point to the
      // position used to compute it should be very nearly zero.
      var positions = [
        ellipsoid.cartographicToCartesian(Rectangle.southwest(rectangle)),
        ellipsoid.cartographicToCartesian(Rectangle.southeast(rectangle)),
        ellipsoid.cartographicToCartesian(Rectangle.northwest(rectangle)),
        ellipsoid.cartographicToCartesian(Rectangle.northeast(rectangle)),
      ];

      var foundOneNearZero = false;
      for (var i = 0; i < positions.length; ++i) {
        var direction = Cartesian3.normalize(
          Cartesian3.subtract(positions[i], unscaledResult, new Cartesian3()),
          new Cartesian3()
        );
        var nearest = IntersectionTests.grazingAltitudeLocation(
          new Ray(unscaledResult, direction),
          ellipsoid
        );
        var nearestCartographic = ellipsoid.cartesianToCartographic(nearest);
        if (Math.abs(nearestCartographic.height) < CesiumMath.EPSILON5) {
          foundOneNearZero = true;
        } else {
          expect(nearestCartographic.height).toBeLessThanOrEqualTo(0.0);
        }
      }

      expect(foundOneNearZero).toBe(true);
    });
  });
});

{'repo_name': 'CesiumGS/cesium', 'stars': '5938', 'repo_language': 'JavaScript', 'file_name': 'lighter.css', 'mime_type': 'text/plain', 'hash': 2075983701387829812, 'source_dataset': 'data'}


// SPDX-License-Identifier: GPL-2.0+
/*
 * Fixed-Link phy
 *
 * Copyright 2017 Bernecker & Rainer Industrieelektronik GmbH
 */

#include <config.h>
#include <common.h>
#include <phy.h>
#include <dm.h>
#include <fdt_support.h>

DECLARE_GLOBAL_DATA_PTR;

int fixedphy_probe(struct phy_device *phydev)
{
	struct fixed_link *priv;
	int ofnode = phydev->addr;
	u32 val;

	/* check for mandatory properties within fixed-link node */
	val = fdt_getprop_u32_default_node(gd->fdt_blob,
					   ofnode, 0, "speed", 0);
	if (val != SPEED_10 && val != SPEED_100 && val != SPEED_1000) {
		printf("ERROR: no/invalid speed given in fixed-link node!");
		return -EINVAL;
	}

	priv = malloc(sizeof(*priv));
	if (!priv)
		return -ENOMEM;
	memset(priv, 0, sizeof(*priv));

	phydev->priv = priv;

	priv->link_speed = val;
	priv->duplex = fdtdec_get_bool(gd->fdt_blob, ofnode, "full-duplex");
	priv->pause = fdtdec_get_bool(gd->fdt_blob, ofnode, "pause");
	priv->asym_pause = fdtdec_get_bool(gd->fdt_blob, ofnode, "asym-pause");

	/* fixed-link phy must not be reset by core phy code */
	phydev->flags |= PHY_FLAG_BROKEN_RESET;

	return 0;
}

int fixedphy_startup(struct phy_device *phydev)
{
	struct fixed_link *priv = phydev->priv;

	phydev->asym_pause = priv->asym_pause;
	phydev->pause = priv->pause;
	phydev->duplex = priv->duplex;
	phydev->speed = priv->link_speed;
	phydev->link = 1;

	return 0;
}

int fixedphy_shutdown(struct phy_device *phydev)
{
	return 0;
}

static struct phy_driver fixedphy_driver = {
	.uid		= PHY_FIXED_ID,
	.mask		= 0xffffffff,
	.name		= "Fixed PHY",
	.features	= PHY_GBIT_FEATURES | SUPPORTED_MII,
	.probe		= fixedphy_probe,
	.startup	= fixedphy_startup,
	.shutdown	= fixedphy_shutdown,
};

int phy_fixed_init(void)
{
	phy_register(&fixedphy_driver);
	return 0;
}

{'repo_name': 'linux-sunxi/u-boot-sunxi', 'stars': '292', 'repo_language': 'C', 'file_name': 'Kconfig', 'mime_type': 'text/plain', 'hash': -7861459415130199410, 'source_dataset': 'data'}


<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Autoplay</title>

    <video width="320" height="240" controls autoplay onplay="playing()">
      <source src="video/autoplay.mp4" type="video/mp4">
    </video>

{'repo_name': 'brave/browser-laptop', 'stars': '8110', 'repo_language': 'JavaScript', 'file_name': 'bookmarkActions.js', 'mime_type': 'text/plain', 'hash': -8357637509001389755, 'source_dataset': 'data'}