text:
"""Test for catching non-exceptions."""
# pylint: disable=too-many-ancestors, print-statement, no-absolute-import
import socket

class MyException(object):
    """Custom 'exception'."""

class MySecondException(object):
    """Custom 'exception'."""

class MyGoodException(Exception):
    """Custom exception."""

class MySecondGoodException(MyGoodException):
    """Custom exception."""

class SkipException(socket.error):
    """Not an exception for Python 2, but one in 3."""

class SecondSkipException(SkipException):
    """Also a good exception."""

try:
    1 + 1
except MyException:  # [catching-non-exception]
    print "caught"

try:
    1 + 2
# +1:[catching-non-exception,catching-non-exception]
except (MyException, MySecondException):
    print "caught"

try:
    1 + 3
except MyGoodException:
    print "caught"

try:
    1 + 3
except (MyGoodException, MySecondGoodException):
    print "caught"

try:
    1 + 3
except (SkipException, SecondSkipException):
    print "caught"

try:
    1 + 42
# +1:[catching-non-exception,catching-non-exception]
except (None, list()):
    print "caught"

try:
    1 + 24
except None: # [catching-non-exception]
    print "caught"

EXCEPTION = None
EXCEPTION = ZeroDivisionError
try:
    1 + 46
except EXCEPTION:
    print "caught"

try:
    1 + 42
# +1:[catching-non-exception,catching-non-exception,catching-non-exception]
except (list([4, 5, 6]), None, ZeroDivisionError, 4):
    print "caught"


text:
Q: How do I break up a dataset in R so that particular values of a categorical variable are together, and I can then perform analysis of those values? I'm doing a project for my stats class in which I need to make an infographic, and I have chosen a dataset involving all flights in the US in June 2016. All 500000 of them. I am trying to sort all of the flights by airport, then calculate the average delay and the percentage of cancelled flights by airport to create a "consistency" statistic to see which airports are the most reliable, and I need to do this with R because the dataset is too large to do anything in Excel. I can't use the by() function, because I cannot perform functions on other variables after categorizing the data. Help?

A: This would be much easier to answer if you gave an example of your data set.
If you have an airport name you can filter to that by running something like this. I'll just use msp as an example.
Dat[airport=="msp',]
If you have a variable called delay you can calculate the average delay by running
mean(Dat[airport=="msp", "delay"])
You could create a list of all airports and use a for loop to go over it to calculate all means.
Or, an easier way would be to turn it into a data table and run
Dat[,.(mean(delay)),by=.(airport)]

A: A useful package for this may be dplyr. I'll use a couple of bogus variables from the included iris dataset to give an indication of how this would work. In your case, replace iris with your dataset, and change the various calculations to what you need.
require(dplyr)

iris %>%
  mutate(# Calculate required variables at the level of your raw data
    Sepal.Area = Sepal.Length * Sepal.Width,
    Petal.Area = Petal.Length * Petal.Width
    ) %>%
  group_by(# Choose variable to group by
    Species
    ) %>%
  summarize(# Perform some grouping calculations
    Mean.Sepal.Area = mean(Sepal.Area),
    Mean.Petal.Area = mean(Petal.Area),
    count = n()
    ) %>%
  mutate(# Calculate required variables at the level of your summarized data
    Sepal.Times.Petal = Mean.Sepal.Area * Mean.Petal.Area) ->
  output

redpajama_set_name: RedPajamaStackExchange


Have you made your 2016 New Year resolutions yet? Well, The Washington Post reports that 40% of Americans make annual resolutions, but only 8% actually stick to them. We can help you make a resolution you can stick with: spend more time with your family having fun while staying healthy!
We understand the importance of spending time with your family. And if you are hoping to spend more quality time with your family in 2016, Skate-N-Fun Zone can help. Our entertainment center has something to offer your entire family, no matter your age or skating experience. The best part? We have a wide selection of skates including inline to quads allowing your family to roll however they choose. Our facility features state of the art attractions that provide an aerobic exercise without seeming like exercise. Plus, Skating alone is recommended by The American Heart Association as a fitness sport and is equivalent to jogging.
Bring the family together for a fun afternoon or night out where your family will bond while having a great time. We will ensure your family has a meaningful experience in our family focused entertainment center!


text:
namespace base {
class SequencedTaskRunner;
}  // namespace base

namespace gl {
class VSyncThreadWin;

class GL_EXPORT DirectCompositionChildSurfaceWin : public GLSurfaceEGL,
                                                   public VSyncObserver {
 public:
  using VSyncCallback =
      base::RepeatingCallback<void(base::TimeTicks, base::TimeDelta)>;
  DirectCompositionChildSurfaceWin(GLDisplayEGL* display,
                                   VSyncCallback vsync_callback,
                                   bool use_angle_texture_offset,
                                   size_t max_pending_frames,
                                   bool force_full_damage,
                                   bool force_full_damage_always);

  DirectCompositionChildSurfaceWin(const DirectCompositionChildSurfaceWin&) =
      delete;
  DirectCompositionChildSurfaceWin& operator=(
      const DirectCompositionChildSurfaceWin&) = delete;

  // GLSurfaceEGL implementation.
  bool Initialize(GLSurfaceFormat format) override;
  void Destroy() override;
  gfx::Size GetSize() override;
  bool IsOffscreen() override;
  void* GetHandle() override;
  gfx::SwapResult SwapBuffers(PresentationCallback callback) override;
  gfx::SurfaceOrigin GetOrigin() const override;
  bool SupportsPostSubBuffer() override;
  bool OnMakeCurrent(GLContext* context) override;
  bool SupportsDCLayers() const override;
  bool SetDrawRectangle(const gfx::Rect& rect) override;
  gfx::Vector2d GetDrawOffset() const override;
  void SetVSyncEnabled(bool enabled) override;
  bool Resize(const gfx::Size& size,
              float scale_factor,
              const gfx::ColorSpace& color_space,
              bool has_alpha) override;
  bool SetEnableDCLayers(bool enable) override;
  gfx::VSyncProvider* GetVSyncProvider() override;
  bool SupportsGpuVSync() const override;
  void SetGpuVSyncEnabled(bool enabled) override;

  // VSyncObserver implementation.
  void OnVSync(base::TimeTicks vsync_time, base::TimeDelta interval) override;

  static bool IsDirectCompositionSwapChainFailed();

  const Microsoft::WRL::ComPtr<IDCompositionSurface>& dcomp_surface() const {
    return dcomp_surface_;
  }

  const Microsoft::WRL::ComPtr<IDXGISwapChain1>& swap_chain() const {
    return swap_chain_;
  }

  uint64_t dcomp_surface_serial() const { return dcomp_surface_serial_; }

  void SetDCompSurfaceForTesting(
      Microsoft::WRL::ComPtr<IDCompositionSurface> surface);

 protected:
  ~DirectCompositionChildSurfaceWin() override;

 private:
  struct PendingFrame {
    PendingFrame(Microsoft::WRL::ComPtr<ID3D11Query> query,
                 PresentationCallback callback);
    PendingFrame(PendingFrame&& other);
    ~PendingFrame();
    PendingFrame& operator=(PendingFrame&& other);

    // Event query issued after frame is presented.
    Microsoft::WRL::ComPtr<ID3D11Query> query;

    // Presentation callback enqueued in SwapBuffers().
    PresentationCallback callback;
  };

  void EnqueuePendingFrame(PresentationCallback callback);
  void CheckPendingFrames();

  void StartOrStopVSyncThread();

  bool VSyncCallbackEnabled() const;

  void HandleVSyncOnMainThread(base::TimeTicks vsync_time,
                               base::TimeDelta interval);

  // Release the texture that's currently being drawn to. If will_discard is
  // true then the surface should be discarded without swapping any contents
  // to it. Returns false if this fails.
  bool ReleaseDrawTexture(bool will_discard);

  Microsoft::WRL::ComPtr<ID3D11Texture2D> GetOffscreenTexture();
  void CopyOffscreenTextureToDrawTexture();

  gfx::Size size_ = gfx::Size(1, 1);
  bool enable_dc_layers_ = false;
  bool has_alpha_ = true;
  bool vsync_enabled_ = true;
  gfx::ColorSpace color_space_;

  // This is a placeholder surface used when not rendering to the
  // DirectComposition surface.
  EGLSurface default_surface_ = 0;

  // This is the real surface representing the backbuffer. It may be null
  // outside of a BeginDraw/EndDraw pair.
  EGLSurface real_surface_ = 0;
  bool first_swap_ = true;
  gfx::Rect swap_rect_;
  gfx::Vector2d draw_offset_;

  // This is a number that increments once for every EndDraw on a surface, and
  // is used to determine when the contents have changed so Commit() needs to
  // be called on the device.
  uint64_t dcomp_surface_serial_ = 0;

  Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_;
  Microsoft::WRL::ComPtr<IDCompositionDevice2> dcomp_device_;
  Microsoft::WRL::ComPtr<IDCompositionSurface> dcomp_surface_;
  Microsoft::WRL::ComPtr<IDXGISwapChain1> swap_chain_;
  Microsoft::WRL::ComPtr<ID3D11Texture2D> draw_texture_;
  POINT dcomp_update_offset_ = {};

  // Used only for kDirectCompositionVerifyDrawOffset to
  // verify a draw offset bug.
  Microsoft::WRL::ComPtr<ID3D11Texture2D> offscreen_texture_;

  const VSyncCallback vsync_callback_;
  const bool use_angle_texture_offset_;
  const size_t max_pending_frames_;
  const bool force_full_damage_;
  const bool force_full_damage_always_;

  const raw_ptr<VSyncThreadWin> vsync_thread_;
  scoped_refptr<base::SequencedTaskRunner> task_runner_;

  bool vsync_thread_started_ = false;
  bool vsync_callback_enabled_ GUARDED_BY(vsync_callback_enabled_lock_) = false;
  mutable base::Lock vsync_callback_enabled_lock_;

  // Queue of pending presentation callbacks.
  base::circular_deque<PendingFrame> pending_frames_;

  base::TimeTicks last_vsync_time_;
  base::TimeDelta last_vsync_interval_;

  base::WeakPtrFactory<DirectCompositionChildSurfaceWin> weak_factory_{this};
};

}  // namespace gl

#endif  // UI_GL_DIRECT_COMPOSITION_CHILD_SURFACE_WIN_H_

redpajama_set_name: RedPajamaGithub


text:
Gary Fong Collapsible Lightsphere Packaging
Yeah, but: Just the wrap, man, just the wrap.
The Long Version: Gary Fong is the Ken Rockwell of lighting modifiers. And that's fine - this review doesn't have anything to do with either one of them, or even the actual product that's in the Gary Fong Lightsphere® Collapsible™ box. It's not even about how the hell someone managed to trademark the word 'Collapsible™'. And for the record, yes, the Gary Fong Lightsphere® Collapsible™ does what it says it does. Two ping-pong balls taped to the top of your flash would also do what the Gary Fong Lightsphere® Collapsible™ does, but that's not the point. This review is just about the package that it comes in.
The box itself is thin black cardboard with a sticker that carries all of the text, graphics, and photos. This is a cost-effective way to create the multi-lingual packaging that's needed for international sales, and the box follows the current trend of keeping it as small as possible. It does fall down a bit by having plastic shrink-wrap around it, but that may add enough integrity to let them use a lighter grade of boxboard. There are also some style points involved by having the actual Lightsphere® Collapsible™ wrapped in coloured tissue paper instead of more unnecessary plastics. But that's hardly enough to motivate a review: the photos are where things start to get interesting.
We see an attractive model in the advertising version of the classic Comedy / Tragedy masks, known as the 'before' and 'after' photo. The one labeled "Without" shows a woman who's rehearsing for her passport photo, while the "With" looks like she's just heard a funny joke from a good friend. Sure, it's a blatant and obvious attempt to manipulate the viewer, but it's so clumsily done that it's impossible to take offense. Besides, given what these things look like when they're stuffed on top of a speedlight, I'm sure that lots of people really do laugh and smile when they see them. But let's look closer, shall we?
(make it bigger)
Here's the "Without / Sans" photo. It's a pretty standard straight-blast flash photo: the hallmark of novice camera users and really abysmal wedding photography. Nothing too remarkable here, so let's move on to the "With / Avec" image.
It's a huge improvement, verging on school portrait quality. It's so good, it's almost impossible to believe that a single on-camera flash could possibly create these results. Take a good look at the catchlights in her eyes in this photo, and compare them to the "Without / Sans" image. It really is impossible to believe that this was taken using a single on-camera light source, no matter how artfully it's bounced. In fact, the soft caressing shadows look even better than in the similar images on the Gary Fong Product Page, where our attractive model has only one catchlight reflected in her eyes.
Fancy that.
Categories: 2, advertising, expensive, flash, lighting gear, Matthew, packaging, photography, plastics
Bill August 6, 2010 at 10:41 AM
Maybe I'm just old fashioned, but if I'm going to take some time and effort to pose the subject of the portrait, then I'll take a remote flash in an umbrella/soft box over Gary Fong any day. If it's on-the-fly photojournalism-style then I'll use available light or a ring flash. Having something that large (a flash + lighting gizmo du jour) is a great way to increase the risk of breaking something near the flash shoe of a camera.
I bought recently (does its function, of course) and recently I realized that point, it is laughable really, knowing that the vast majority of people who are professional photographers buying... LOL
Kirk Gleason
eBay E46 Hood & the Panasonic 20/1.7
Concrete Toronto: A Guidebook to Concrete Architec...
Zeiss Ikon (First Impressions)

redpajama_set_name: RedPajamaCommonCrawl


Our real estate attorneys have significant experience and knowledge about all aspects of commercial real estate. They understand that the goal of our clients is to make and close the deal, so they use innovative solutions to help them achieve those objectives.
We advise our clients on a wide variety of real estate matters, including the negotiation of purchase agreements and finance documents, review of due diligence materials and the closing of transactions. Our clients include developers of commercial properties involved in acquisitions, entitlements, zoning and land use and environmental issues, and both landlords and tenants involved in the negotiation of commercials leases for shopping centers, outparcel retail locations and industrial and office space. Working hand-in-hand with our Corporate/Business Transactions attorneys, we also assist both developers and investors in entity selection and formation.


text:
park tematyczny
 aquapark
 lunapark

Zobacz też
 centrum nauki

redpajama_set_name: RedPajamaWikipedia


text:
If any more proof were needed of the government's rigging of the election, you can find it if you dig down into the constituency results at a polling station level.
The Daily Star has done this in the district of Barisal - with the most egregious constituency being the constituency of Barisal-1 which had a total of 115 polling centres/stations.
The BNP candidate Jahiruddin Swapan received:
- 0 votes in 26 stations
- 1 vote in 9 station
- less than 10 votes in 40 stations.
The BNP candidate received a total of 1,305 votes
The AL candidate, Abul Hasnat Abdullah, received 211,507 votes.
In seven polling stations the AL candidate received every single vote - not a single vote from any of the other candidates (there was a third party, the Islami Andolan Bangladesh)
The AL candidate, Hasnat, received 98.7% of the vote.
These two candidates have faced each other before, 17 years earlier.
In the 2001 polls, Swapan (BNP) beat Hasnat (AL) by around 14,000 votes. BNP got 81,791 votes while the AL obtained 67,760 votes.
This must constitute one of the biggest swings from one party to another in the history of 'democratic' elections.
In the 2008 elections, there was also a close contest between the AL and BNP - with different candidates. The AL candidate received 98,245 votes and the BNP secured 70,969 votes.
You will notice how carefully The Daily Star has written this article.
For example, rather than having a headline which could reasonably read, "Polling station data suggest rigging in Barisal" it reads, "Voting Pattern in Barishal Dist: From well-contested to lopsided".
This is what is known as media self-censorship
Posted by David Bergman at 8:06 PM


text:
Free online learning
Research & Innovation Services
Commercialising research
Researcher support
Winchester School of Art
Employability & enterprise
Our news, seminars & events
WSA Transport
At Winchester School of Art we are proud to be recognised and respected as one of the UK's leading and progressive art and design institutions within the world-renowned University of Southampton, part of the Russell Group of Universities.
Our Reputation and Rankings
Ranked 7th in subject area 'Art'
We are ranked 7th in subject area for 'Art' in the 2019 Guardian University League Table.
Top 20 UK University
We're at 18th place in The Sunday Times Good University Guide 2019, up 12 places from last year's ranking.
We've been awarded Silver in the Teaching Excellence and Student Outcomes Framework (TEF) for our quality teaching and learning.
Top 100 University Worldwide
We're in the top 100 in the QS World University Rankings 2019, based on indicators such as research excellence and employability.
Our staff and students actively initiate and participate in a wide range of high quality and impactful projects across the art and design landscape. To stay informed and read more about what we have accomplished recently, we encourage you to browse our social media channels:
Employers & recruiters
Connect with us on Instagram
Explore our Youtube channel
Download University of Southampton prospectus
Download a PDF of our prospectus or order a printed copy to be delivered to your door.


text:
Истрага над беспрекорним грађанином () је италијански криминалистички филм из 1970. године редитеља Елиа Петрија, са Ђан Маријом Волонтеом и Флориндом Болкан у главним улогама. Представља психолошку, црнохуморну сатиру о корупцији на високој функцији, прати полицајца који убије своју љубавницу а затим тестира да ли би га полиција оптужила за овај злочин. Филм је у Италији објавио Euro International Pictures 9. фебруара 1970. Освојио је награду жирија на Канском филмском фестивалу 1970. и награду Давид ди Донатело за најбољи филм и најбољу главну глумицу. У Сједињеним Америчким Државама је освојио Оскара за најбољи међународни филм и за најбољи оригинални сценарио. Године 2008. је стављен на листу Министарства културе Италије "100 филмова које треба сачувати".

Радња
Недавно унапређени полицијски инспектор под надимком Доктор убија своју љубавницу, а затим прикрива злочин. Поставља трагове како би своје подређене официре усмерио ка низу других осумњичених, укључујући њеног хомосексуалног супруга и студента радикалне левице. Затим ослобађа остале осумњичене и води истражитеље ка себи како би доказао да може да се извуче са било чим, чак и док је под истрагом. На крају признаје злочин пред својим претпостављенима који одбијају да му верују. Сигуран да је безбедан, повлачи признање и добија одобрење полицијског комесара. Открива се да је испитивање у његовом дому секвенца из снова и филм се завршава стварним доласком комесара и других колега.

Улоге

 Ђан Марија Волонте — Доктор
 Флоринда Болкан — Августа Терзи
 Ђани Сантучо — Полицијски комесар
 Салво Рандоне — Водоинсталатер
 Артуро Доминичи — Мангани
 Алдо Рендине — Никола Панунцио
 Масимо Фоски — Клаудио Терци
 Виторио Дузе — Кан
 Алека Паизи — Кућна помоћница
 Пино Пети — Супервизор прислушкивања
 Ђанфранко Бара — Агент Ђусти

Референце

Спољашње везе

 Истрага над беспрекорним грађанином

Филмови 1970.
Филмови снимљени у Риму
Италијански филмови
Филмови на италијанском језику
Филмске драме
Трилери


Check out the full taxonomy and distribution of Common Squirrel-cuckoo on HBW Alive.
A bird looking around while perched in a tree.
A close dorsal view of a perched bird, eventually flying away.
Taking of calls (probably alarm).
Josep del Hoyo, Juan Sanabria, Pieter de Groot Boersma, Stefan Behrens, Pere Sugranyes, Keith Blomerley, Thore Noernberg, Keith and Lynn Youngs, Max Roth, Daniêl Jimenez, Martin Manassero, Greg Baker, jacob.wijpkema, nelsonlage, manakincarmelo, Virgilio Yábar Calderón, Robert Schaefer, Antonio Silveira, Bob Humphries and Sally Robinson, Paul Molina Abril, agustin carrasco, Yoël Jimenez.
Margareta Wieser, Eduardo Freitez Gassan, manuel retana, Carlos Gussoni, David M. Gascoigne, Antonio Silveira, Stanislav Harvančík, Juan Fdo. Alvarez Castro, richardgreenhalgh031, Josep del Hoyo, Orlando Jarquín G., Horacio Luna, Luis R Figueroa, Róger Rodríguez, marvinhyett, Lars Petersson, buchert, DiazLucrecia, Phillip Edwards, Mikko Pyhälä, Dannie Polley, Tadeusz Stawarczyk, Pedro H Ramos, Miguel Emmanuelli, Holger Teichmann, Josef Widmer, mauricio rueda, Alberto Lobato, Michael Fritzen, BILLONNEAU Jean Claude, Roger Ahlman, Ian Maton, philgunson, José Frade, Wiloperez, Luis G. Restrepo, Brigitt Marques, David Weaver, Ron Harwood, Christophe Gouraud, delareina, Paul van Giersbergen, Cristiano Crolle, LMArce, Frédéric Pelsy, Sam Shaw, Jerdickens, Andre Zambolli, Lukasz Michal Pulawski, Marco Valentini, Joe Tobias, Evaldo HS Nascimento, srporto, juanjaimemg, Ken Simonite, Daniel Avendaño, Luis Eduardo Urueña, jacob.wijpkema, Joselito Nardy Ribeiro, Joe Prasil, jacqueserard, Ken Havard, nigel lallsingh, Auger Benjamin, Jens Thalund, Lutz Duerselen, manakincarmelo, José M. Formentí, wagnermclemes, Juanfran Herrera Cueva, Guy Poisson, Hal and Kirsten Snyder, Digitalbcon, jomacomo, Lindolfo Souto, Samantha Klein, Batitu, Rafael Merchante, Tomas Grim, Miriam Bauman, Miguel Andina, Jeremy Gatten, Sanjiv Parasram.
Josep del Hoyo, Joe Klaiber, Ciro Albano, Noé Eiterer.


The datacenter location is the key to ensuring the seamless performance of your website. With us, you can make sure that your Australia-based visitors will enjoy much faster web page load speeds. We partner with a top-of-the-line data center facility, which is located in Sydney, Australia, and which offers perfect conditions for your web site. You can select the Australian datacenter facility on the order form. We'll set up your web hosting account within a couple of minutes and will give you access to our in-house developed, point & click hosting CP. We offer a 24/7 customer support service and if you are not happy with the offered speeds, you can take advantage of our thirty-day MBG.


text:
package org.apache.spark.sql.execution.aggregate

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
import org.apache.spark.sql.execution.metric.SQLMetric

/**
 * This is a variant of SortAggregateIterator which merges the session windows based on the fact
 * input rows are sorted by "group keys + the start time of session window".
 *
 * When merging windows, it also applies aggregations on merged window, which eliminates the
 * necessity on buffering inputs (which requires copying rows) and update the session spec
 * for each input.
 */
class MergingSessionsIterator(
    partIndex: Int,
    groupingExpressions: Seq[NamedExpression],
    sessionExpression: NamedExpression,
    valueAttributes: Seq[Attribute],
    inputIterator: Iterator[InternalRow],
    aggregateExpressions: Seq[AggregateExpression],
    aggregateAttributes: Seq[Attribute],
    initialInputBufferOffset: Int,
    resultExpressions: Seq[NamedExpression],
    newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
    numOutputRows: SQLMetric)
  extends AggregationIterator(
    partIndex,
    groupingExpressions,
    valueAttributes,
    aggregateExpressions,
    aggregateAttributes,
    initialInputBufferOffset,
    resultExpressions,
    newMutableProjection) {

  val groupingWithoutSession: Seq[NamedExpression] =
    groupingExpressions.diff(Seq(sessionExpression))
  val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)

  /**
   * Creates a new aggregation buffer and initializes buffer values
   * for all aggregate functions.
   */
  private def newBuffer: InternalRow = {
    val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
    val bufferRowSize: Int = bufferSchema.length

    val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
    val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)

    val buffer = if (useUnsafeBuffer) {
      val unsafeProjection =
        UnsafeProjection.create(bufferSchema.map(_.dataType))
      unsafeProjection.apply(genericMutableBuffer)
    } else {
      genericMutableBuffer
    }
    initializeBuffer(buffer)
    buffer
  }

  ///////////////////////////////////////////////////////////////////////////
  // Mutable states for sort based aggregation.
  ///////////////////////////////////////////////////////////////////////////

  // The partition key of the current partition.
  private[this] var currentGroupingKey: UnsafeRow = _

  private[this] var currentSession: UnsafeRow = _

  // The partition key of next partition.
  private[this] var nextGroupingKey: UnsafeRow = _

  private[this] var nextGroupingSession: UnsafeRow = _

  // The first row of next partition.
  private[this] var firstRowInNextGroup: InternalRow = _

  // Indicates if we has new group of rows from the sorted input iterator
  private[this] var sortedInputHasNewGroup: Boolean = false

  // The aggregation buffer used by the sort-based aggregation.
  private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer

  private[this] val groupingWithoutSessionProjection: UnsafeProjection =
    UnsafeProjection.create(groupingWithoutSession, valueAttributes)

  private[this] val sessionProjection: UnsafeProjection =
    UnsafeProjection.create(Seq(sessionExpression), valueAttributes)

  // The flag indicating there's error on iterator, sort precondition is not fulfilled.
  private var errorOnIterator: Boolean = false

  protected def initialize(): Unit = {
    if (inputIterator.hasNext) {
      initializeBuffer(sortBasedAggregationBuffer)
      val inputRow = inputIterator.next()
      nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
      val session = sessionProjection(inputRow)
      nextGroupingSession = session.getStruct(0, 2).copy()
      firstRowInNextGroup = inputRow.copy()
      sortedInputHasNewGroup = true
    } else {
      // This inputIter is empty.
      sortedInputHasNewGroup = false
    }
  }

  initialize()

  /** Processes rows in the current group. It will stop when it find a new group. */
  protected def processCurrentSortedGroup(): Unit = {
    currentGroupingKey = nextGroupingKey
    currentSession = nextGroupingSession

    // Now, we will start to find all rows belonging to this group.
    // We create a variable to track if we see the next group.
    var findNextGroup = false
    // firstRowInNextGroup is the first row of this group. We first process it.
    processRow(sortBasedAggregationBuffer, firstRowInNextGroup)

    // The search will stop when we see the next group or there is no
    // input row left in the iter.
    while (!findNextGroup && inputIterator.hasNext) {
      // Get the grouping key.
      val currentRow = inputIterator.next()
      val groupingKey = groupingWithoutSessionProjection(currentRow)

      val session = sessionProjection(currentRow)
      val sessionStruct = session.getStruct(0, 2)
      val sessionStart = getSessionStart(sessionStruct)
      val sessionEnd = getSessionEnd(sessionStruct)

      // Check if the current row belongs the current input row.
      if (currentGroupingKey == groupingKey) {
        if (sessionStart < getSessionStart(currentSession)) {
          errorOnIterator = true
          throw new IllegalStateException("Input iterator is not sorted based on session!")
        } else if (sessionStart <= getSessionEnd(currentSession)) {
          // expanding session length if needed
          expandEndOfCurrentSession(sessionEnd)
          processRow(sortBasedAggregationBuffer, currentRow)
        } else {
          // We find a new session window in the same group.
          findNextGroup = true
          startNewSession(currentRow, groupingKey, sessionStruct)
        }
      } else {
        // We find a new group.
        findNextGroup = true
        startNewSession(currentRow, groupingKey, sessionStruct)
      }
    }

    // We have not seen a new group. It means that there is no new row in the input
    // iter. The current group is the last group of the iter.
    if (!findNextGroup) {
      sortedInputHasNewGroup = false
    }
  }

  private def startNewSession(
      currentRow: InternalRow,
      groupingKey: UnsafeRow,
      sessionStruct: UnsafeRow): Unit = {
    nextGroupingKey = groupingKey.copy()
    nextGroupingSession = sessionStruct.copy()
    firstRowInNextGroup = currentRow.copy()
  }

  private def getSessionStart(sessionStruct: UnsafeRow): Long = {
    sessionStruct.getLong(0)
  }

  private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
    sessionStruct.getLong(1)
  }

  private def expandEndOfCurrentSession(sessionEnd: Long): Unit = {
    if (sessionEnd > getSessionEnd(currentSession)) {
      currentSession.setLong(1, sessionEnd)
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  // Iterator's public methods
  ///////////////////////////////////////////////////////////////////////////

  override final def hasNext: Boolean = {
    if (errorOnIterator) {
      throw new IllegalStateException("The iterator is already corrupted.")
    }
    sortedInputHasNewGroup
  }

  override final def next(): UnsafeRow = {
    if (hasNext) {
      // Process the current group.
      processCurrentSortedGroup()
      // Generate output row for the current group.
      val groupingKey = generateGroupingKey()

      val outputRow = generateOutput(groupingKey, sortBasedAggregationBuffer)
      // Initialize buffer values for the next group.
      initializeBuffer(sortBasedAggregationBuffer)
      numOutputRows += 1
      outputRow
    } else {
      // no more result
      throw new NoSuchElementException
    }
  }

  private val join = new JoinedRow

  private val groupingKeyProj = GenerateUnsafeProjection.generate(groupingExpressions,
    groupingWithoutSessionAttributes :+ sessionExpression.toAttribute)

  private def generateGroupingKey(): UnsafeRow = {
    val sessionStruct = new SpecificInternalRow(Seq(sessionExpression.toAttribute).toStructType)
    sessionStruct.update(0, currentSession)
    val joined = join(currentGroupingKey, sessionStruct)

    groupingKeyProj(joined)
  }

  def outputForEmptyGroupingKeyWithoutInput(): UnsafeRow = {
    initializeBuffer(sortBasedAggregationBuffer)
    generateOutput(UnsafeRow.createFromByteArray(0, 0), sortBasedAggregationBuffer)
  }
}


text:
Q: R get row number of the first row that has a string variable in a data frame column I am working with data frames that are dynamically generated.
structure(list(`4` = c(NA, NA, "Location", NA), `5` = c(NA, NA,
"Size", "W")), row.names = c(NA, 4L), class = "data.frame")

The above looks like this:
                                      4    5
1                                  <NA> <NA>
2                                  <NA> <NA>
3                              Location Size
4                                  <NA>    W

From each column in the data frame I want to get the first character variable.  For example from the above table, I want to retrieve Location and Size and use them as my column header.
Since the tables are dynamically generated, I am not sure in which line the string variable would appear.

A: An option is to loop through the columns, get the first non-NA element with summarise_all
library(dplyr)
df1 %>%
  summarise_all(funs(.[!is.na(.)][1]))

Or with sapply, use the same logic
sapply(df1, function(x) x[!is.na(x)][1])

Or with which on logical matrix (!is.na(df1)), subset the data, get the first element of each column by filtering out the duplicate column index
ind <- which(!is.na(df1), arr.ind = TRUE)
df1[ind][!duplicated(ind[,2])]
#[1] "Location" "Size"