text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_SDK_SIMD_PACK_PACK_HPP_INCLUDED
#define BOOST_SIMD_SDK_SIMD_PACK_PACK_HPP_INCLUDED

#include <boost/simd/sdk/simd/pack/forward.hpp>
#include <boost/simd/sdk/simd/pack/expression.hpp>

#include <boost/simd/sdk/details/aliasing.hpp>
#include <boost/simd/sdk/simd/pack/meta.hpp>
#include <boost/simd/sdk/simd/pack/fusion_iterator.hpp>
#include <boost/simd/sdk/simd/pack/fusion.hpp>

#include <boost/dispatch/dsl/call.hpp>
#include <boost/simd/sdk/simd/details/operators.hpp>
#include <boost/simd/sdk/simd/pack/call.hpp>

#include <boost/simd/include/functions/evaluate.hpp>
#include <boost/simd/include/functions/simd/aligned_load.hpp>
#include <boost/simd/include/functions/simd/splat.hpp>
#include <boost/simd/include/functions/simd/make.hpp>

#include <boost/simd/sdk/simd/meta/vector_of.hpp>
#include <boost/simd/meta/is_power_of_2.hpp>
#include <boost/simd/memory/is_aligned.hpp>

#include <boost/dispatch/meta/is_iterator.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_arithmetic.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/static_assert.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/pointee.hpp>

#include <boost/simd/sdk/simd/extensions.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/simd/sdk/simd/preprocessor/repeat.hpp>

namespace boost { namespace simd
{
  ////////////////////////////////////////////////////////////////////////////
  // pack, implemented in terms of simd::expr via non-inheritance to preserve
  // PODness of pack throughout the whole system.
  ////////////////////////////////////////////////////////////////////////////
  template<class Type, std::size_t Cardinal>
  struct BOOST_SIMD_MAY_ALIAS pack
    : expression< boost::proto::basic_expr< boost::proto::tag::terminal
                                          , boost::proto::term< typename
                                                                meta::vector_of< Type
                                                                               , Cardinal
                                                                               >::type
                                                              >
                                          , 0l
                                          >
                 , typename
                   meta::vector_of< Type
                                  , Cardinal
                                  >::type
                 >
  {
    static const std::size_t static_size = Cardinal;

    typedef typename meta::vector_of<Type, Cardinal>::type  data_type;
    typedef boost::proto::basic_expr< boost::proto::tag::terminal, boost::proto::term<data_type>, 0l > expr_type;

    typedef Type                                value_type;
    typedef typename data_type::reference       reference;
    typedef typename data_type::const_reference const_reference;
    typedef typename data_type::iterator        iterator;
    typedef typename data_type::const_iterator  const_iterator;

    typedef expression< expr_type, data_type > parent;

    //==========================================================================
    /*
     * SIMD pack instanciated with non-power of 2 Cardinal or a Cardinal of 1.
     */
    //==========================================================================
    BOOST_MPL_ASSERT_MSG
    ( (meta::is_power_of_2_c<Cardinal>::value && Cardinal > 1)
    , INVALID_SIMD_PACK_CARDINAL
    , (boost::mpl::int_<Cardinal>)
    );

    BOOST_FORCEINLINE pack() {}

    BOOST_FORCEINLINE pack(data_type const& p)
    {
      proto::value(*this) = p;
    }

#if defined(BOOST_MSVC) || defined(DOXYGEN_ONLY)
    BOOST_FORCEINLINE pack(pack const& other)
    {
      proto::value(*this) = proto::value(other);
    }
#endif

    template<class ScalarIterator>
    BOOST_FORCEINLINE pack( ScalarIterator i
        , typename enable_if< dispatch::meta::is_iterator<ScalarIterator> >::type* = 0)
    {
      typedef typename boost::pointee<ScalarIterator>::type v_type;
      BOOST_STATIC_ASSERT_MSG
      ( (boost::is_same<Type,v_type>::value)
      , "The constructor of pack<T,C> has been called on a iterator"
        "which value_type is different from T."
      );

      value_type* p = &(*i);

      BOOST_ASSERT_MSG
      ( boost::simd::is_aligned(p,sizeof(data_type))
      , "The constructor of pack<T,C> has been called on a iterator"
        "which alignment is not compatible with current SIMD extension."
      );

      proto::value(*this) = aligned_load<data_type >(p,0);
    }

    //==========================================================================
    // Constructor from scalar range
    //==========================================================================
    template<class ScalarIterator>
    BOOST_FORCEINLINE pack( ScalarIterator b, ScalarIterator e
        , typename enable_if< dispatch::meta::is_iterator<ScalarIterator> >::type* = 0)
    {
      BOOST_ASSERT_MSG
      ( ((e-b)==Cardinal)
      , "The constructor of pack<T,C> has been called on a iterator"
        "which alignment is not compatible with current SIMD extension."
      );

      for(int i=0;b!=e;++b,++i)
        (*this)[i] = *b;
    }

    BOOST_SIMD_MEMORY_OVERLOAD_NEW_DELETE(Cardinal*sizeof(value_type))

    //==========================================================================
    // Constructor from unique scalar value -> splat the value
    //==========================================================================
    template<class T>
    BOOST_FORCEINLINE pack(T const& t, typename enable_if< is_arithmetic<T> >::type* = 0)
    {
      proto::value(*this) = simd::splat<data_type>(t);
    }

    //==========================================================================
    // Create constructors for pack according to the extension specification.
    //==========================================================================
    #define M1(z, n, arg)                                                      \
    template<class T>                                                          \
    BOOST_FORCEINLINE pack( BOOST_PP_ENUM_PARAMS(n, T const& a)                \
        , typename enable_if< is_arithmetic<T> >::type* = 0)                   \
    {                                                                          \
      proto::value(*this) = simd::make<data_type>(BOOST_PP_ENUM_PARAMS(n,a));  \
    }                                                                          \
    /**/

    BOOST_SIMD_PP_REPEAT_POWER_OF_2_FROM(2, M1, ~)
    #undef M1

    //==========================================================================
    // Constructor from expression -> evaluate using parent operator=
    //==========================================================================
    template<class T>
    BOOST_FORCEINLINE pack(T const& t, typename T::proto_is_expr_* = 0)
    {
      static_cast<parent&>(*this) = t;
    }

    //==========================================================================
    // operator= for pack
    //==========================================================================
    BOOST_FORCEINLINE pack& operator=(pack const& src)
    {
      boost::proto::value(*this) = boost::proto::value(src);
      return *this;
    }

    template<class Xpr>
    BOOST_FORCEINLINE
    typename boost::disable_if<boost::is_base_of<parent,Xpr>, pack&>::type
    operator=(Xpr const& xpr)
    {
      parent::operator=(xpr);
      return *this;
    }

    BOOST_FORCEINLINE
    reference operator[](std::size_t i)
    {
      return boost::proto::value(*this)[i];
    }

    BOOST_FORCEINLINE
    const_reference  operator[](std::size_t i) const
    {
      return boost::proto::value(*this)[i];
    }

    ////////////////////////////////////////////////////////////////////////////
    // Range interface
    ////////////////////////////////////////////////////////////////////////////
    BOOST_FORCEINLINE
    iterator       begin()       { return boost::proto::value(*this).begin(); }
    BOOST_FORCEINLINE
    const_iterator begin() const { return boost::proto::value(*this).begin(); }
    BOOST_FORCEINLINE
    iterator       end()         { return boost::proto::value(*this).end();   }
    BOOST_FORCEINLINE
    const_iterator end()   const { return boost::proto::value(*this).end();   }

    ////////////////////////////////////////////////////////////////////////////
    // Array like interface
    ////////////////////////////////////////////////////////////////////////////
    static BOOST_FORCEINLINE
    std::size_t size() { return data_type::size(); }

    static BOOST_FORCEINLINE
    bool empty() { return false; }

    ////////////////////////////////////////////////////////////////////////////
    // Fusion RandomAccessSequence interface
    ////////////////////////////////////////////////////////////////////////////
    typedef tag::pack_ fusion_tag;
  };
} }

#endif


text:
/* { dg-do link } */

/* Use the target type definitions if we can.  */
#ifndef __WINT_TYPE__
#define __WINT_TYPE__ int
#endif

#ifndef __WCHAR_TYPE__
#define __WCHAR_TYPE__ int
#endif

void test(int i)
{
  /* All of these ctype functions should be const/pure and thus
     eliminated.  */
#define TEST_IS_WCTYPE(FN) \
  extern int FN(__WINT_TYPE__); \
  extern void link_failure_##FN(void); \
  if (FN(i) != FN(i)) \
    link_failure_##FN()

#define TEST_TO_WCTYPE(FN) \
  extern __WINT_TYPE__ FN(__WINT_TYPE__); \
  extern void link_failure_##FN(void); \
  if (FN(i) != FN(i)) \
    link_failure_##FN()

#ifdef __OPTIMIZE__
  TEST_IS_WCTYPE(iswalnum);
  TEST_IS_WCTYPE(iswalpha);
  TEST_IS_WCTYPE(iswblank);
  TEST_IS_WCTYPE(iswcntrl);
  TEST_IS_WCTYPE(iswdigit);
  TEST_IS_WCTYPE(iswgraph);
  TEST_IS_WCTYPE(iswlower);
  TEST_IS_WCTYPE(iswprint);
  TEST_IS_WCTYPE(iswpunct);
  TEST_IS_WCTYPE(iswspace);
  TEST_IS_WCTYPE(iswupper);
  TEST_IS_WCTYPE(iswxdigit);
  TEST_TO_WCTYPE(towlower);
  TEST_TO_WCTYPE(towupper);
#endif /* __OPTIMIZE__ */
}

int main (void)
{
  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: How to Read CSV Using the iOS SDK
---

Are you working on one of your first iOS apps and eager to start pulling in CSV data from an external source?

There's tons of CSV data available for every domain, but the docs on using it on iOS are a bit sparse.

Here's a quick guide on everything you need to know to get up and running.

Let's get started!

## Guide

### 1. Place your CSV file in the project folder.

Copy the CSV file into your **project folder**. This is the folder which contains your `.xcodeproj` file.

**Protip:** I suggest creating a directory to keep your non-code assets organized. So, create a directory called `PROJECT_ROOT/Resources/Data` and copy your CSV file to `PROJECT_ROOT/Resources/Data/mydata.csv`.

### 2. Add your CSV file to the Xcode project.

Now that the file is in your project folder, you need to add it to your Xcode project.

**Right-click** the file browser in Xcode and use **"Add Files"** to make Xcode aware of your CSV file and bundle it with your app.

<center>
<img src="../images/2016/06/21-ios-csv/xcode.png" /> </center>

### 3. Install CHCSVParser

[CHCSVParser](https://github.com/davedelong/CHCSVParser) is a solid CSV parser library for iOS.

You can add it to your project however you like, but I suggest using [CocoaPods](https://cocoapods.org/).

If you've never used Cocoapods, it goes something like this:

* Close your Xcode project
* `sudo gem install cocoapods`
* `pod init`
* Edit `Podfile`, adding the line, `pod 'CHCSVParser', '2.1.0'`
* `pod install`
* Open the new `.xcworkspace`, NOT the `.xcodeproj` file
* Build and run

### 4. Use CHCSVParser to read in your data

Here are library author, Dave DeLong's, [instructions](http://stackoverflow.com/questions/6961367/basics-introduction-to-using-chcsvparser) for performing basic parsing:

~~~ objc
NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"csv"];

NSError *error = nil;
NSArray *rows = [NSArray arrayWithContentsOfCSVFile:path encoding:NSUTF8StringEncoding error:&error];
if (rows == nil) {
  //something went wrong; log the error and exit
  NSLog(@"error parsing file: %@", error);
  return;
}
~~~

So let's say your CSV file looks like this:

~~~
Barringer,Arizona,United States,Earth
"Chicxulub, Extinction Event Crater",,Mexico,Earth
Tycho,,,Moon
Lonar,Maharashtra,India,Earth
~~~

If you run it through the parser, the variable, `rows`, will now contain:

~~~ objc
[NSArray arrayWithObjects:
 [NSArray arrayWithObjects:@"Barringer",@"Arizona",@"United States",@"Earth",nil],
 [NSArray arrayWithObjects:@"Chicxulub, Extinction Event Crater",@"",@"Mexico",@"Earth",nil],
 [NSArray arrayWithObjects:@"Tycho",@"",@"",@"Moon",nil],
 [NSArray arrayWithObjects:@"Lonar",@"Maharashtra",@"India",@"Earth",nil],
 nil];
~~~

### 5. Render your data to the UI!

Now that you have your data, it's up to you to work with it and render it to the UI!

This step is outside the scope of the current post, but let me know if you need help with this part.

## Thanks

Learn a thing or two? If so, please sign up for my [newsletter](//newsletter) where I share helpful tips on mobile app development.

Still have questions? Please write them below in the comments!

------

*Inspiration for this post comes from Mandias09's [post](https://www.reddit.com/r/iOSProgramming/comments/4p1zyp/how_to_pull_outside_data_into_an_app/) on the iOS programming Reddit.*


text:
extern crate apue;
extern crate libc;
extern crate errno;

use libc::{sigset_t, SIGINT, SIG_SETMASK, sigaddset, sigemptyset};
use apue::{LibcResult, pr_mask};
use apue::my_libc::sigprocmask;

fn main() {
    unsafe {
        let mut sigs: sigset_t = std::mem::uninitialized();
        sigemptyset(&mut sigs);
        sigaddset(&mut sigs, SIGINT);
        sigprocmask(SIG_SETMASK, &sigs, std::ptr::null_mut())
            .check_not_negative()
            .expect("couldn't set signals");
        pr_mask("after setting mask:");
    }
}


text:
"""
jump_game_ii.py

Created by Shengwei on 2014-07-22.
"""

# https://oj.leetcode.com/problems/jump-game-ii/
# tags: medium, array, dp, greedy, logic

"""
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
"""

# https://oj.leetcode.com/discuss/422/is-there-better-solution-for-jump-game-ii

################# adding some logic O(n) #################

class Solution:
    # @param A, a list of integers
    # @return an integer
    def jump(self, A):
        # note: this needs special care
        if len(A) == 1:
            return 0

        step = farthest = 0
        next_farthest = A[0]

        for cursor in xrange(len(A) - 1):
            can_reach = cursor + A[cursor]
            if can_reach >= len(A) - 1:
                return step + 1

            next_farthest = max(next_farthest, can_reach)

            if cursor == farthest:
                if farthest == next_farthest:
                    # this is the farthest position it
                    # can reach; cannot reach the final
                    break

                # it needs one more step to reach further
                # since next potion, i.e., farthest + 1
                step += 1
                farthest = next_farthest

        # cannot reach the last index
        return 1000000

################# bottom-up dp O(n^2) #################

class Solution:
    # @param A, a list of integers
    # @return an integer
    def jump(self, A):
        steps = [0] + [100000] * (len(A) - 1)

        for i in xrange(len(A) - 1):
            for cursor in xrange(i + 1, i + A[i] + 1):
                if cursor >= len(A):
                    break
                steps[cursor] = min(
                    steps[cursor], steps[i] + 1)

        return steps[-1]


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0, minimal-ui" />


text:
							Recherche agence payeur

							<button type="button" class="btn btn-success" onclick="javascript:creerPrestataire();"> Ajouter</button>

					<?php
				        echo $this->session->flashdata('info');
				    ?>
	  				<form action="<?php echo site_url('AgencePaiement_Controller/recherche'); ?>" method="GET" class="form-inline" role="form">
						<input type="hidden" name="page" value="1">

							Nom
							<input type="text" class="form-control" placeholder="Ex: TELMA" name="nom" value="<?php echo $search_criteria["nom"]; ?>">

						<button type="submit" class="btn btn-primary" style="margin-top: 22px;">

						</button>
					</form>

					<form action="<?php echo site_url('AgencePaiement_Controller/create'); ?>" method="POST" id="new">

Creation agence payeur

                                    		* Nom
                                    		<input class="form-control" type="text" name="nom" required>

	                                    	<button type="button" onClick="javascript:confirmation();" class="btn btn-primary">Creer</button>

                    </form>

									#
									Agence payeur

								<?php
									$i = $debut;
									foreach ($agencePaiements as $row) { ?>

										<?php echo $i; $i++; ?>
										<a href="<?php echo site_url('AgencePaiement_Controller/fiche/'.$row->getId()); ?>"><?php echo $row->getNom(); ?>

								<?php } ?>

							<?php
								foreach ($pages as $row)
								{ ?>
									<li class="<?php echo $row->getBootstrapClassName(); ?>"><a href="<?php echo site_url('AgencePaiement_Controller/recherche?page='.$row->getPage().'&'.$search_url); ?>"><?php echo $row->getPage(); ?>

							<?php } ?>

Creation

Voulez-vous vraiment creer cette agence de paiement?

					                Valider
					                <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>

Information

					                OK


text:
'use strict';

/**
 * @ngdoc function
 * @name tedCockpitApp.controller:TestCtrl
 * @description
 * # TestCtrl
 * Controller of the tedCockpitApp
 */
angular.module('tedCockpitApp')
  .controller('CreateDeskCtrl', function ($log, $window, deskService) {

    this.desksModel = deskService;
    this.desk = {
    };

    this.createDesk = function() {
      $log.debug('Creating desk, sending it to backend via $http: ', this.desk);
      deskService.createDeskViaHttp(this.desk);
    };
  });


text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee183a026df">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States District Court District of Columbia</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2013-01-04</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2013-01-03</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-dcd-1_12-cv-00306</identifier>
<identifier type="local">P0b002ee183a026df</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2013-01-04</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2013-01-04</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-dcd-1_12-cv-00306</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-dcd-1_12-cv-00306</accessId>
 <courtType>District</courtType>
 <courtCode>dcd</courtCode>
 <courtCircuit>DC</courtCircuit>
 <courtState>District of Columbia</courtState>
 <courtSortOrder>2100</courtSortOrder>
 <caseNumber>1:12-cv-00306</caseNumber>
 <caseOffice>Washington, DC</caseOffice>
 <caseType>civil</caseType>
 <natureSuitCode>890</natureSuitCode>
 <natureSuit>Other Statutory Actions</natureSuit>
 <cause>28:2201 Declaratory Judgement</cause>
 <party fullName="ASSOCIATION OF AMERICAN RAILROADS" lastName="ASSOCIATION OF AMERICAN RAILROADS" role="Amicus"></party>
 <party fullName="BROTHERHOOD OF LOCOMOTIVE ENGINEERS AND TRAINMEN" lastName="BROTHERHOOD OF LOCOMOTIVE ENGINEERS AND TRAINMEN" role="Movant"></party>
 <party fullName="HIGH POINT, RANDLEMAN, ASHEBORO AND SOUTHERN RAILROAD COMPANY" lastName="HIGH POINT, RANDLEMAN, ASHEBORO AND SOUTHERN RAILROAD COMPANY" role="Plaintiff"></party>
 <party firstName="MICHAEL" fullName="MICHAEL L. MERCIER" lastName="MERCIER" middleName="L." role="Movant"></party>
 <party fullName="MOBILE AND BIRMINGHAM RAILROAD COMPANY" lastName="MOBILE AND BIRMINGHAM RAILROAD COMPANY" role="Plaintiff"></party>
 <party fullName="NORFOLK SOUTHERN CORPORATION" lastName="NORFOLK SOUTHERN CORPORATION" role="Plaintiff"></party>
 <party fullName="NORFOLK SOUTHERN RAILWAY COMPANY" lastName="NORFOLK SOUTHERN RAILWAY COMPANY" role="Plaintiff"></party>
 <party fullName="NORTH CAROLINA MIDLAND RAILROAD COMPANY" lastName="NORTH CAROLINA MIDLAND RAILROAD COMPANY" role="Plaintiff"></party>
 <party firstName="HILDA" fullName="HILDA L. SOLIS" lastName="SOLIS" middleName="L." role="Defendant"></party>
 <party fullName="SOUTH WESTERN RAILROAD COMPANY" lastName="SOUTH WESTERN RAILROAD COMPANY" role="Plaintiff"></party>
 <party fullName="STATE UNIVERSITY RAILROAD COMPANY" lastName="STATE UNIVERSITY RAILROAD COMPANY" role="Plaintiff"></party>
 <party fullName="UNITED TRANSPORTATION UNION" lastName="UNITED TRANSPORTATION UNION" role="Movant"></party>
</extension>
<titleInfo>
 <title>NORFOLK SOUTHERN RAILWAY COMPANY v. SOLIS</title>
 <partNumber>1:12-cv-00306</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-dcd-1_12-cv-00306/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">1:12-cv-00306;12-306</identifier>
<name type="corporate">
 <namePart>United States District Court District of Columbia</namePart>
 <namePart>DC Circuit</namePart>
 <namePart>Washington, DC</namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>ASSOCIATION OF AMERICAN RAILROADS</displayForm>
 <namePart type="family">ASSOCIATION OF AMERICAN RAILROADS</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Amicus</description>
</name>
<name type="personal">
 <displayForm>BROTHERHOOD OF LOCOMOTIVE ENGINEERS AND TRAINMEN</displayForm>
 <namePart type="family">BROTHERHOOD OF LOCOMOTIVE ENGINEERS AND TRAINMEN</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Movant</description>
</name>
<name type="personal">
 <displayForm>HIGH POINT, RANDLEMAN, ASHEBORO AND SOUTHERN RAILROAD COMPANY</displayForm>
 <namePart type="family">HIGH POINT, RANDLEMAN, ASHEBORO AND SOUTHERN RAILROAD COMPANY</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>MICHAEL L. MERCIER</displayForm>
 <namePart type="family">MERCIER</namePart>
 <namePart type="given">MICHAEL</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Movant</description>
</name>
<name type="personal">
 <displayForm>MOBILE AND BIRMINGHAM RAILROAD COMPANY</displayForm>
 <namePart type="family">MOBILE AND BIRMINGHAM RAILROAD COMPANY</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>NORFOLK SOUTHERN CORPORATION</displayForm>
 <namePart type="family">NORFOLK SOUTHERN CORPORATION</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>NORFOLK SOUTHERN RAILWAY COMPANY</displayForm>
 <namePart type="family">NORFOLK SOUTHERN RAILWAY COMPANY</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>NORTH CAROLINA MIDLAND RAILROAD COMPANY</displayForm>
 <namePart type="family">NORTH CAROLINA MIDLAND RAILROAD COMPANY</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>HILDA L. SOLIS</displayForm>
 <namePart type="family">SOLIS</namePart>
 <namePart type="given">HILDA</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<name type="personal">
 <displayForm>SOUTH WESTERN RAILROAD COMPANY</displayForm>
 <namePart type="family">SOUTH WESTERN RAILROAD COMPANY</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>STATE UNIVERSITY RAILROAD COMPANY</displayForm>
 <namePart type="family">STATE UNIVERSITY RAILROAD COMPANY</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>UNITED TRANSPORTATION UNION</displayForm>
 <namePart type="family">UNITED TRANSPORTATION UNION</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Movant</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-dcd-1_12-cv-00306</accessId>
 <courtType>District</courtType>
 <courtCode>dcd</courtCode>
 <courtCircuit>DC</courtCircuit>
 <courtState>District of Columbia</courtState>
 <courtSortOrder>2100</courtSortOrder>
 <caseNumber>1:12-cv-00306</caseNumber>
 <caseOffice>Washington, DC</caseOffice>
 <caseType>civil</caseType>
 <natureSuitCode>890</natureSuitCode>
 <natureSuit>Other Statutory Actions</natureSuit>
 <cause>28:2201 Declaratory Judgement</cause>
 <party fullName="ASSOCIATION OF AMERICAN RAILROADS" lastName="ASSOCIATION OF AMERICAN RAILROADS" role="Amicus"></party>
 <party fullName="BROTHERHOOD OF LOCOMOTIVE ENGINEERS AND TRAINMEN" lastName="BROTHERHOOD OF LOCOMOTIVE ENGINEERS AND TRAINMEN" role="Movant"></party>
 <party fullName="HIGH POINT, RANDLEMAN, ASHEBORO AND SOUTHERN RAILROAD COMPANY" lastName="HIGH POINT, RANDLEMAN, ASHEBORO AND SOUTHERN RAILROAD COMPANY" role="Plaintiff"></party>
 <party firstName="MICHAEL" fullName="MICHAEL L. MERCIER" lastName="MERCIER" middleName="L." role="Movant"></party>
 <party fullName="MOBILE AND BIRMINGHAM RAILROAD COMPANY" lastName="MOBILE AND BIRMINGHAM RAILROAD COMPANY" role="Plaintiff"></party>
 <party fullName="NORFOLK SOUTHERN CORPORATION" lastName="NORFOLK SOUTHERN CORPORATION" role="Plaintiff"></party>
 <party fullName="NORFOLK SOUTHERN RAILWAY COMPANY" lastName="NORFOLK SOUTHERN RAILWAY COMPANY" role="Plaintiff"></party>
 <party fullName="NORTH CAROLINA MIDLAND RAILROAD COMPANY" lastName="NORTH CAROLINA MIDLAND RAILROAD COMPANY" role="Plaintiff"></party>
 <party firstName="HILDA" fullName="HILDA L. SOLIS" lastName="SOLIS" middleName="L." role="Defendant"></party>
 <party fullName="SOUTH WESTERN RAILROAD COMPANY" lastName="SOUTH WESTERN RAILROAD COMPANY" role="Plaintiff"></party>
 <party fullName="STATE UNIVERSITY RAILROAD COMPANY" lastName="STATE UNIVERSITY RAILROAD COMPANY" role="Plaintiff"></party>
 <party fullName="UNITED TRANSPORTATION UNION" lastName="UNITED TRANSPORTATION UNION" role="Movant"></party>
 <state>District of Columbia</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-dcd-1_12-cv-00306-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-dcd-1_12-cv-00306/USCOURTS-dcd-1_12-cv-00306-0/mods.xml">
 <titleInfo>
  <title>NORFOLK SOUTHERN RAILWAY COMPANY v. SOLIS</title>
  <subTitle>MEMORANDUM OPINION re: 27 Order. Signed by Judge Barbara Jacobs Rothstein on 01/03/2013. (lcbjr1)</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2013-01-03</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-dcd-1_12-cv-00306-0.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee183a04e48</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-dcd-1_12-cv-00306/USCOURTS-dcd-1_12-cv-00306-0</identifier>
 <identifier type="former granule identifier">dcd-1_12-cv-00306_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-dcd-1_12-cv-00306/USCOURTS-dcd-1_12-cv-00306-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-dcd-1_12-cv-00306/pdf/USCOURTS-dcd-1_12-cv-00306-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 1:12-cv-00306; NORFOLK SOUTHERN RAILWAY COMPANY v. SOLIS; </searchTitle>
  <courtName>United States District Court District of Columbia</courtName>
  <state>District of Columbia</state>
  <accessId>USCOURTS-dcd-1_12-cv-00306-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2013-01-03</dateIssued>
  <docketText>MEMORANDUM OPINION re: 27 Order. Signed by Judge Barbara Jacobs Rothstein on 01/03/2013. (lcbjr1)</docketText>
</extension>
</relatedItem>
</mods>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>接口 org.kymjs.aframe.http.downloader.I_FileLoader的使用</title>
<meta name="date" content="2014-10-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

接口的使用
org.kymjs.aframe.http.downloader.I_FileLoader

使用I_FileLoader的程序包

程序包
说明

org.kymjs.aframe.http

org.kymjs.aframe.http.downloader

org.kymjs.aframe.http中I_FileLoader的使用

返回I_FileLoader的org.kymjs.aframe.http中的方法

限定符和类型
方法和说明

I_FileLoader
HttpConfig.getDownloader()

文件下载器,默认采用系统自带下载器,你也可以使用自己的下载器

参数类型为I_FileLoader的org.kymjs.aframe.http中的方法

限定符和类型
方法和说明

void
HttpConfig.setDownloader(I_FileLoader downloader)

设置文件下载器,默认采用系统自带下载器,你也可以使用自己的下载器

org.kymjs.aframe.http.downloader中I_FileLoader的使用

org.kymjs.aframe.http.downloader中I_FileLoader的子接口

限定符和类型
接口和说明

interface
I_MulThreadLoader

多线程文件下载器接口协议

 创建时间 2014-8-11

实现I_FileLoader的org.kymjs.aframe.http.downloader中的类

限定符和类型
类和说明

class
FileDownLoader

多线程文件下载器类,你也可以通过实现I_MulThreadLoader或I_FileLoader接口协议来创建自己的下载器

 创建时间 2014-8-11

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.fullscreen;

import android.app.Activity;
import android.content.res.Resources;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.FrameLayout;

import org.chromium.base.ActivityState;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.ApplicationStatus.ActivityStateListener;
import org.chromium.base.BaseChromiumApplication;
import org.chromium.base.BaseChromiumApplication.WindowFocusChangedListener;
import org.chromium.base.ThreadUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.library_loader.LibraryLoader;
import org.chromium.chrome.browser.fullscreen.FullscreenHtmlApiHandler.FullscreenHtmlApiDelegate;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelSelectorTabModelObserver;
import org.chromium.chrome.browser.util.ViewUtils;
import org.chromium.chrome.browser.widget.ControlContainer;
import org.chromium.content.browser.ContentVideoView;
import org.chromium.content.browser.ContentViewCore;
import org.chromium.content_public.common.BrowserControlsState;

import java.util.ArrayList;

/**
 * A class that manages control and content views to create the fullscreen mode.
 */
public class ChromeFullscreenManager
        extends FullscreenManager implements ActivityStateListener, WindowFocusChangedListener {

    // The amount of time to delay the control show request after returning to a once visible
    // activity.  This delay is meant to allow Android to run its Activity focusing animation and
    // have the controls scroll back in smoothly once that has finished.
    private static final long ACTIVITY_RETURN_SHOW_REQUEST_DELAY_MS = 100;

    private final Activity mActivity;
    private final Window mWindow;
    private final BrowserStateBrowserControlsVisibilityDelegate mBrowserVisibilityDelegate;
    private final boolean mIsBottomControls;

    private ControlContainer mControlContainer;
    private int mTopControlContainerHeight;
    private int mBottomControlContainerHeight;
    private TabModelSelector mTabModelSelector;
    private TabModelSelectorTabModelObserver mTabModelObserver;

    private float mRendererTopControlOffset = Float.NaN;
    private float mRendererBottomControlOffset = Float.NaN;
    private float mRendererTopContentOffset;
    private float mPreviousContentOffset = Float.NaN;
    private float mControlOffsetRatio;
    private float mPreviousControlOffset;
    private boolean mIsEnteringPersistentModeState;

    private boolean mInGesture;
    private boolean mContentViewScrolling;

    private boolean mBrowserControlsPermanentlyHidden;
    private boolean mBrowserControlsAndroidViewHidden;

    private final ArrayList<FullscreenListener> mListeners = new ArrayList<FullscreenListener>();

    /**
     * A listener that gets notified of changes to the fullscreen state.
     */
    public interface FullscreenListener {
        /**
         * Called whenever the content's offset changes.
         * @param offset The new offset of the content from the top of the screen.
         */
        public void onContentOffsetChanged(float offset);

        /**
         * Called whenever the content's visible offset changes.
         * @param offset The new offset of the visible content from the top of the screen.
         * @param needsAnimate Whether the caller is driving an animation with further updates.
         */
        public void onVisibleContentOffsetChanged(float offset, boolean needsAnimate);

        /**
         * Called when a ContentVideoView is created/destroyed.
         * @param enabled Whether to enter or leave overlay video mode.
         */
        public void onToggleOverlayVideoMode(boolean enabled);
    }

    private final Runnable mUpdateVisibilityRunnable = new Runnable() {
        @Override
        public void run() {
            int visibility = shouldShowAndroidControls() ? View.VISIBLE : View.INVISIBLE;
            if (mControlContainer.getView().getVisibility() == visibility) return;
            // requestLayout is required to trigger a new gatherTransparentRegion(), which
            // only occurs together with a layout and let's SurfaceFlinger trim overlays.
            // This may be almost equivalent to using View.GONE, but we still use View.INVISIBLE
            // since drawing caches etc. won't be destroyed, and the layout may be less expensive.
            mControlContainer.getView().setVisibility(visibility);
            mControlContainer.getView().requestLayout();
        }
    };

    /**
     * Creates an instance of the fullscreen mode manager.
     * @param activity The activity that supports fullscreen.
     * @param isBottomControls Whether or not the browser controls are at the bottom of the screen.
     */
    public ChromeFullscreenManager(Activity activity, boolean isBottomControls) {
        super(activity.getWindow());

        mActivity = activity;
        mWindow = activity.getWindow();
        mIsBottomControls = isBottomControls;
        mBrowserVisibilityDelegate = new BrowserStateBrowserControlsVisibilityDelegate();
    }

    /**
     * Initializes the fullscreen manager with the required dependencies.
     *
     * @param controlContainer Container holding the controls (Toolbar).
     * @param modelSelector The tab model selector that will be monitored for tab changes.
     * @param resControlContainerHeight The dimension resource ID for the control container height.
     */
    public void initialize(ControlContainer controlContainer, TabModelSelector modelSelector,
            int resControlContainerHeight) {
        ApplicationStatus.registerStateListenerForActivity(this, mActivity);
        ((BaseChromiumApplication) mActivity.getApplication())
                .registerWindowFocusChangedListener(this);

        mTabModelSelector = modelSelector;
        mTabModelObserver = new TabModelSelectorTabModelObserver(mTabModelSelector) {
            @Override
            public void tabClosureCommitted(Tab tab) {
                setTab(mTabModelSelector.getCurrentTab());
            }

            @Override
            public void allTabsClosureCommitted() {
                setTab(mTabModelSelector.getCurrentTab());
            }

            @Override
            public void tabRemoved(Tab tab) {
                setTab(mTabModelSelector.getCurrentTab());
            }

            @Override
            public void didSelectTab(Tab tab, TabSelectionType type, int lastId) {
                setTab(mTabModelSelector.getCurrentTab());
            }
        };

        assert controlContainer != null;
        mControlContainer = controlContainer;
        Resources resources = mWindow.getContext().getResources();

        int controlContainerHeight = resources.getDimensionPixelSize(resControlContainerHeight);
        if (mIsBottomControls) {
            mTopControlContainerHeight = 0;
            mBottomControlContainerHeight = controlContainerHeight;
        } else {
            mTopControlContainerHeight = controlContainerHeight;
            mBottomControlContainerHeight = 0;
        }

        mRendererTopContentOffset = mTopControlContainerHeight;
        updateControlOffset();
    }

    /**
     * @return Whether or not the browser controls are attached to the bottom of the screen.
     */
    public boolean areBrowserControlsAtBottom() {
        return mIsBottomControls;
    }

    /**
     * @return The visibility delegate that allows browser UI to control the browser control
     *         visibility.
     */
    public BrowserStateBrowserControlsVisibilityDelegate getBrowserVisibilityDelegate() {
        return mBrowserVisibilityDelegate;
    }

    @Override
    public void setTab(Tab tab) {
        Tab previousTab = getTab();
        super.setTab(tab);
        mBrowserVisibilityDelegate.setTab(getTab());
        if (tab != null && previousTab != getTab()) {
            mBrowserVisibilityDelegate.showControlsTransient();
        }
    }

    @Override
    public void onActivityStateChange(Activity activity, int newState) {
        if (newState == ActivityState.STOPPED) {
            // Exit fullscreen in onStop to ensure the system UI flags are set correctly when
            // showing again (on JB MR2+ builds, the omnibox would be covered by the
            // notification bar when this was done in onStart()).
            setPersistentFullscreenMode(false);
        } else if (newState == ActivityState.STARTED) {
            ThreadUtils.postOnUiThreadDelayed(new Runnable() {
                @Override
                public void run() {
                    mBrowserVisibilityDelegate.showControlsTransient();
                }
            }, ACTIVITY_RETURN_SHOW_REQUEST_DELAY_MS);
        } else if (newState == ActivityState.DESTROYED) {
            ApplicationStatus.unregisterActivityStateListener(this);
            ((BaseChromiumApplication) mWindow.getContext().getApplicationContext())
                    .unregisterWindowFocusChangedListener(this);

            mTabModelObserver.destroy();
        }
    }

    @Override
    public void onWindowFocusChanged(Activity activity, boolean hasFocus) {
        if (mActivity != activity) return;
        onWindowFocusChanged(hasFocus);
        // {@link ContentVideoView#getContentVideoView} requires native to have been initialized.
        if (!LibraryLoader.isInitialized()) return;
        ContentVideoView videoView = ContentVideoView.getContentVideoView();
        if (videoView != null) {
            videoView.onFullscreenWindowFocused();
        }
    }

    @Override
    protected FullscreenHtmlApiDelegate createApiDelegate() {
        return new FullscreenHtmlApiDelegate() {
            @Override
            public void onEnterFullscreen() {
                Tab tab = getTab();
                if (areBrowserControlsOffScreen()) {
                    // The browser controls are currently hidden.
                    getHtmlApiHandler().enterFullscreen(tab);
                } else {
                    // We should hide browser controls first.
                    mIsEnteringPersistentModeState = true;
                    tab.updateFullscreenEnabledState();
                }
            }

            @Override
            public boolean cancelPendingEnterFullscreen() {
                boolean wasPending = mIsEnteringPersistentModeState;
                mIsEnteringPersistentModeState = false;
                return wasPending;
            }

            @Override
            public void onFullscreenExited(Tab tab) {
                // At this point, browser controls are hidden. Show browser controls only if it's
                // permitted.
                tab.updateBrowserControlsState(BrowserControlsState.SHOWN, true);
            }

            @Override
            public boolean shouldShowNotificationToast() {
                return !isOverlayVideoMode();
            }
        };
    }

    /**
     * @return The ratio that the browser controls are off screen; this will be a number [0,1]
     *         where 1 is completely hidden and 0 is completely shown.
     */
    private float getBrowserControlHiddenRatio() {
        return mControlOffsetRatio;
    }

    /**
     * @return True if the browser controls are completely off screen.
     */
    public boolean areBrowserControlsOffScreen() {
        return getBrowserControlHiddenRatio() == 1.0f;
    }

    /**
     * @param remove Whether or not to forcefully remove the toolbar.
     */
    public void setBrowserControlsPermamentlyHidden(boolean remove) {
        if (remove == mBrowserControlsPermanentlyHidden) return;
        mBrowserControlsPermanentlyHidden = remove;
        updateVisuals();
    }

    /**
     * @return Whether or not the toolbar is forcefully being removed.
     */
    public boolean areBrowserControlsPermanentlyHidden() {
        return mBrowserControlsPermanentlyHidden;
    }

    /**
     * @return Whether the browser controls should be drawn as a texture.
     */
    public boolean drawControlsAsTexture() {
        return getBrowserControlHiddenRatio() > 0;
    }

    @Override
    public int getTopControlsHeight() {
        return mTopControlContainerHeight;
    }

    /**
     * @return The height of the bottom controls in pixels.
     */
    public int getBottomControlsHeight() {
        return mBottomControlContainerHeight;
    }

    @Override
    public float getContentOffset() {
        if (mBrowserControlsPermanentlyHidden) return 0;
        return mRendererTopContentOffset;
    }

    /**
     * @return The offset of the controls from the top of the screen.
     */
    public float getTopControlOffset() {
        if (mBrowserControlsPermanentlyHidden) return -getTopControlsHeight();
        // This is to avoid a problem with -0f in tests.
        if (mControlOffsetRatio == 0f) return 0f;
        return mControlOffsetRatio * -getTopControlsHeight();
    }

    /**
     * @return The offset of the controls from the bottom of the screen.
     */
    public float getBottomControlOffset() {
        if (mBrowserControlsPermanentlyHidden) return getBottomControlsHeight();
        if (mControlOffsetRatio == 0f) return 0f;
        return mControlOffsetRatio * getBottomControlsHeight();

    }

    /**
     * @return The toolbar control container.
     */
    public ControlContainer getControlContainer() {
        return mControlContainer;
    }

    private void updateControlOffset() {
        float topOffsetRatio = 0;

        float rendererControlOffset;
        if (mIsBottomControls) {
            rendererControlOffset =
                    Math.abs(mRendererBottomControlOffset / getBottomControlsHeight());
        } else {
            rendererControlOffset = Math.abs(mRendererTopControlOffset / getTopControlsHeight());
        }

        final boolean isNaNRendererControlOffset = Float.isNaN(rendererControlOffset);
        if (!isNaNRendererControlOffset) topOffsetRatio = rendererControlOffset;
        mControlOffsetRatio = topOffsetRatio;
    }

    @Override
    public void setOverlayVideoMode(boolean enabled) {
        super.setOverlayVideoMode(enabled);

        for (int i = 0; i < mListeners.size(); i++) {
            mListeners.get(i).onToggleOverlayVideoMode(enabled);
        }
    }

    /**
     * @return The visible offset of the content from the top of the screen.
     */
    public float getTopVisibleContentOffset() {
        return getTopControlsHeight() + getTopControlOffset();
    }

    /**
     * @param listener The {@link FullscreenListener} to be notified of fullscreen changes.
     */
    public void addListener(FullscreenListener listener) {
        if (!mListeners.contains(listener)) mListeners.add(listener);
    }

    /**
     * @param listener The {@link FullscreenListener} to no longer be notified of fullscreen
     *                 changes.
     */
    public void removeListener(FullscreenListener listener) {
        mListeners.remove(listener);
    }

    /**
     * Updates the content view's viewport size to have it render the content correctly.
     *
     * @param viewCore The ContentViewCore to update.
     */
    public void updateContentViewViewportSize(ContentViewCore viewCore) {
        if (viewCore == null) return;
        if (mInGesture || mContentViewScrolling) return;

        // Update content viewport size only when the browser controls are not animating.
        int contentOffset = (int) mRendererTopContentOffset;
        if (contentOffset != 0 && contentOffset != getTopControlsHeight()) return;
        viewCore.setTopControlsHeight(getTopControlsHeight(), contentOffset > 0);
    }

    @Override
    public void updateContentViewChildrenState() {
        ContentViewCore contentViewCore = getActiveContentViewCore();
        if (contentViewCore == null) return;
        ViewGroup view = contentViewCore.getContainerView();

        float topViewsTranslation = getTopVisibleContentOffset();
        applyTranslationToTopChildViews(view, topViewsTranslation);
        applyMarginToFullChildViews(view, topViewsTranslation);
        updateContentViewViewportSize(contentViewCore);
    }

    /**
     * Utility routine for ensuring visibility updates are synchronized with
     * animation, preventing message loop stalls due to untimely invalidation.
     */
    private void scheduleVisibilityUpdate() {
        final int desiredVisibility = shouldShowAndroidControls() ? View.VISIBLE : View.INVISIBLE;
        if (mControlContainer.getView().getVisibility() == desiredVisibility) return;
        mControlContainer.getView().removeCallbacks(mUpdateVisibilityRunnable);
        mControlContainer.getView().postOnAnimation(mUpdateVisibilityRunnable);
    }

    private void updateVisuals() {
        TraceEvent.begin("FullscreenManager:updateVisuals");

        // Use bottom controls height if top controls have no height.
        float offset = getTopControlOffset();
        if (mIsBottomControls) offset = getBottomControlOffset();

        if (Float.compare(mPreviousControlOffset, offset) != 0) {
            mPreviousControlOffset = offset;

            scheduleVisibilityUpdate();
            if (shouldShowAndroidControls()) {
                mControlContainer.getView().setTranslationY(offset);
            }

            // Whether we need the compositor to draw again to update our animation.
            // Should be |false| when the browser controls are only moved through the page
            // scrolling.
            boolean needsAnimate = shouldShowAndroidControls();
            for (int i = 0; i < mListeners.size(); i++) {
                // Since, in the case of bottom controls, the view is never translated, we don't
                // need to change the information passed into this method.
                // getTopVisibleContentOffset will return 0 which is the expected result.
                mListeners.get(i).onVisibleContentOffsetChanged(
                        getTopVisibleContentOffset(), needsAnimate);
            }
        }

        final Tab tab = getTab();
        if (tab != null && areBrowserControlsOffScreen() && mIsEnteringPersistentModeState) {
            getHtmlApiHandler().enterFullscreen(tab);
            mIsEnteringPersistentModeState = false;
        }

        updateContentViewChildrenState();

        float contentOffset = getContentOffset();
        if (Float.compare(mPreviousContentOffset, contentOffset) != 0) {
            for (int i = 0; i < mListeners.size(); i++) {
                mListeners.get(i).onContentOffsetChanged(contentOffset);
            }
            mPreviousContentOffset = contentOffset;
        }

        TraceEvent.end("FullscreenManager:updateVisuals");
    }

    /**
     * @param hide Whether or not to force the browser controls Android view to hide.  If this is
     *             {@code false} the browser controls Android view will show/hide based on position,
     *             if it is {@code true} the browser controls Android view will always be hidden.
     */
    public void setHideBrowserControlsAndroidView(boolean hide) {
        if (mBrowserControlsAndroidViewHidden == hide) return;
        mBrowserControlsAndroidViewHidden = hide;
        scheduleVisibilityUpdate();
    }

    private boolean shouldShowAndroidControls() {
        if (mBrowserControlsAndroidViewHidden) return false;

        boolean showControls = !drawControlsAsTexture();
        ContentViewCore contentViewCore = getActiveContentViewCore();
        if (contentViewCore == null) return showControls;
        ViewGroup contentView = contentViewCore.getContainerView();

        for (int i = 0; i < contentView.getChildCount(); i++) {
            View child = contentView.getChildAt(i);
            if (!(child.getLayoutParams() instanceof FrameLayout.LayoutParams)) continue;

            FrameLayout.LayoutParams layoutParams =
                    (FrameLayout.LayoutParams) child.getLayoutParams();
            if (Gravity.TOP == (layoutParams.gravity & Gravity.FILL_VERTICAL)) {
                showControls = true;
                break;
            }
        }

        return showControls;
    }

    private void applyMarginToFullChildViews(ViewGroup contentView, float margin) {
        for (int i = 0; i < contentView.getChildCount(); i++) {
            View child = contentView.getChildAt(i);
            if (!(child.getLayoutParams() instanceof FrameLayout.LayoutParams)) continue;
            FrameLayout.LayoutParams layoutParams =
                    (FrameLayout.LayoutParams) child.getLayoutParams();

            if (layoutParams.height == LayoutParams.MATCH_PARENT
                    && layoutParams.topMargin != (int) margin) {
                layoutParams.topMargin = (int) margin;
                child.requestLayout();
                TraceEvent.instant("FullscreenManager:child.requestLayout()");
            }
        }
    }

    private void applyTranslationToTopChildViews(ViewGroup contentView, float translation) {
        for (int i = 0; i < contentView.getChildCount(); i++) {
            View child = contentView.getChildAt(i);
            if (!(child.getLayoutParams() instanceof FrameLayout.LayoutParams)) continue;

            FrameLayout.LayoutParams layoutParams =
                    (FrameLayout.LayoutParams) child.getLayoutParams();
            if (Gravity.TOP == (layoutParams.gravity & Gravity.FILL_VERTICAL)) {
                child.setTranslationY(translation);
                TraceEvent.instant("FullscreenManager:child.setTranslationY()");
            }
        }
    }

    private ContentViewCore getActiveContentViewCore() {
        Tab tab = getTab();
        return tab != null ? tab.getContentViewCore() : null;
    }

    @Override
    public void setPositionsForTabToNonFullscreen() {
        Tab tab = getTab();
        if (tab == null || tab.isShowingBrowserControlsEnabled()) {
            setPositionsForTab(0, 0, getTopControlsHeight());
        } else {
            setPositionsForTab(-getTopControlsHeight(), getBottomControlsHeight(), 0);
        }
    }

    @Override
    public void setPositionsForTab(float topControlsOffset, float bottomControlsOffset,
            float topContentOffset) {
        float rendererTopControlOffset =
                Math.round(Math.max(topControlsOffset, -getTopControlsHeight()));
        float rendererBottomControlOffset =
                Math.round(Math.min(bottomControlsOffset, getBottomControlsHeight()));

        float rendererTopContentOffset = Math.min(
                Math.round(topContentOffset), rendererTopControlOffset + getTopControlsHeight());

        if (Float.compare(rendererTopControlOffset, mRendererTopControlOffset) == 0
                && Float.compare(rendererBottomControlOffset, mRendererBottomControlOffset) == 0
                && Float.compare(rendererTopContentOffset, mRendererTopContentOffset) == 0) {
            return;
        }

        mRendererTopControlOffset = rendererTopControlOffset;
        mRendererBottomControlOffset = rendererBottomControlOffset;

        mRendererTopContentOffset = rendererTopContentOffset;
        updateControlOffset();

        updateVisuals();
    }

    /**
     * @param e The dispatched motion event
     * @return Whether or not this motion event is in the top control container area and should be
     *         consumed.
     */
    public boolean onInterceptMotionEvent(MotionEvent e) {
        int bottomPosition;
        int topPosition = 0;
        float offset;

        if (mIsBottomControls) {
            int[] position = new int[2];
            ViewUtils.getRelativeLayoutPosition(mControlContainer.getView().getRootView(),
                    mControlContainer.getView(), position);

            topPosition = position[1];
            bottomPosition = topPosition + getBottomControlsHeight();
            offset = getBottomControlOffset();
        } else {
            bottomPosition = getTopControlsHeight();
            offset = getTopControlOffset();
        }

        return e.getY() < topPosition + offset && e.getY() > bottomPosition + offset
                && !mBrowserControlsAndroidViewHidden;
    }

    /**
     * Notifies the fullscreen manager that a motion event has occurred.
     * @param e The dispatched motion event.
     */
    public void onMotionEvent(MotionEvent e) {
        int eventAction = e.getActionMasked();
        if (eventAction == MotionEvent.ACTION_DOWN
                || eventAction == MotionEvent.ACTION_POINTER_DOWN) {
            mInGesture = true;
            // TODO(qinmin): Probably there is no need to hide the toast as it will go away
            // by itself.
            getHtmlApiHandler().hideNotificationToast();
        } else if (eventAction == MotionEvent.ACTION_CANCEL
                || eventAction == MotionEvent.ACTION_UP) {
            mInGesture = false;
            updateVisuals();
        }
    }

    @Override
    public void onContentViewScrollingStateChanged(boolean scrolling) {
        mContentViewScrolling = scrolling;
        if (!scrolling) updateVisuals();
    }
}


text:
namespace kaleidoscope {

class Lexer {
public:
  int GetToken();
  std::string GetIdentifier() const {
    return identifier_;
  }
  double GetNumber() const {
    return number_;
  }
private:
  std::string identifier_;
  double number_;
}; // class Lexer

} // namespace kaleidoscope

#endif // KALEIDOSCOPE_LEXER_H


text:
(function(){
	var nconf = require('nconf'),
		path = require('path'),
		async = require('async'),
		cluster = require('cluster');
	var client = require('./worker');

	global.env = process.env.NODE_ENV || 'production';

	nconf.argv().env();
	nconf.file('default', path.join('config', path.sep, global.env + '.json'));
	nconf.set('base_dir', __dirname);
	nconf.set('client_dir', path.join(nconf.get('base_dir'), path.sep, 'client'));
	nconf.defaults({
		'client': {
			'port': 3100,
			'siteName': 'NodeIB',
			'upload_url':  '/public/uploads',
			'date_format': 'ddd D MMM YYYY HH:mm:ss',
			'cluster': false
		}
	});

	global.nconf = nconf;

	// Count the machine's CPUs
	var cpuCount = require('os').cpus().length;

	if(cluster.isMaster && nconf.get('client:cluster')){
		// Create a worker for each CPU
		for(var i = 0; i <cpuCount; i += 1){
			cluster.fork();
		}

		// Restart dead workers
		cluster.on('exit', function(worker){
			console.log('Worker ' + worker.id + ' died :(');
			cluster.fork();
		});

		console.log('Master process started');
	}else{
		client(nconf.get('client:port'), nconf.get('client:siteName'));
	}
}());


text:
==============================
Passing Parameters to Register
==============================

When you :doc:`register components <registration>` you have the ability to provide a set of parameters that can be used during the :doc:`resolution of services <../resolve/index>` based on that component. (If you'd rather provide the parameters at resolution time, :doc:`you can do that instead <../resolve/parameters>`.)

Available Parameter Types
=========================

Autofac offers several different parameter matching strategies:

* ``NamedParameter`` - match target parameters by name
* ``TypedParameter`` - match target parameters by type (exact type match required)
* ``ResolvedParameter`` - flexible parameter matching

``NamedParameter`` and ``TypedParameter`` can supply constant values only.

``ResolvedParameter`` can be used as a way to supply values dynamically retrieved from the container, e.g. by resolving a service by name.

Parameters with Reflection Components
=====================================

When you register a reflection-based component, the constructor of the type may require a parameter that can't be resolved from the container. You can use a parameter on the registration to provide that value.

Say you have a configuration reader that needs a configuration section name passed in:

.. sourcecode:: csharp

    public class ConfigReader : IConfigReader
    {
      public ConfigReader(string configSectionName)
      {
        // Store config section name
      }

      // ...read configuration based on the section name.
    }

You could use a lambda expression component for that:

.. sourcecode:: csharp

    builder.Register(c => new ConfigReader("sectionName")).As<IConfigReader>();

Or you could pass a parameter to a reflection component registration:

.. sourcecode:: csharp

    // Using a NAMED parameter:
    builder.RegisterType<ConfigReader>()
           .As<IConfigReader>()
           .WithParameter("configSectionName", "sectionName");

    // Using a TYPED parameter:
    builder.RegisterType<ConfigReader>()
           .As<IConfigReader>()
           .WithParameter(new TypedParameter(typeof(string), "sectionName"));

    // Using a RESOLVED parameter:
    builder.RegisterType<ConfigReader>()
           .As<IConfigReader>()
           .WithParameter(
             new ResolvedParameter(
               (pi, ctx) => pi.ParameterType == typeof(string) && pi.Name == "configSectionName",
               (pi, ctx) => "sectionName"));

Parameters with Lambda Expression Components
============================================

With lambda expression component registrations, rather than passing the parameter value *at registration time* you enable the ability to pass the value *at service resolution time*. (:doc:`Read more about resolving with parameters. <../resolve/parameters>`)

In the component registration expression, you can make use of the incoming parameters by using the generic lambda ``Register`` methods:

.. sourcecode:: csharp

    builder.Register((MyConfig config) => new Worker(config));

If you need access to the full list of parameters, it's available by changing the delegate signature you use for registration.
Instead of specifying the parameter as an argument to the lambda, take in an ``IComponentContext`` and an ``IEnumerable<Parameter>``:

.. sourcecode:: csharp

    // Use TWO parameters to the registration delegate:
    // c = The current IComponentContext to dynamically resolve dependencies
    // p = An IEnumerable<Parameter> with the incoming parameter set
    builder.Register((c, p) =>
                     new Worker(p.Named<MyConfig>("config")));

When :doc:`resolving with parameters <../resolve/parameters>`, your lambda will use the parameters passed in:

.. sourcecode:: csharp

    var customConfig = new MyConfig
    {
      SomeValue = "../"
    };

    var worker = scope.Resolve<Worker>(new NamedParameter("config", customConfig));


text:
"""Description
Usage:
  dx_users.py (--user_name <name> [(--add --password <password> --email <email_address> [--jsonly]) |--delete])
                  [--engine <identifier> | --all]
                  [--debug] [--parallel <n>] [--poll <n>]
                  [--config <path_to_file>] [--logdir <path_to_file>]
  dx_users.py --update --user_name <name> [ --password <password> ] [--email <email_address> ] [ --delete ] [--jsonly]
                  [--engine <identifier> | --all]
                  [--debug] [--parallel <n>] [--poll <n>]
                  [--config <path_to_file>] [--logdir <path_to_file>]
  dx_users.py (--list)
                  [--engine <identifier> | --all]
                  [--debug] [--parallel <n>] [--poll <n>]
                  [--config <path_to_file>] [--logdir <path_to_file>]
  dx_users.py -h | --help | -v | --version
Description

Examples:
    dx_users.py --add --user_name dev --password delphix --email "test@something.com" --jsonly
    dx_users.py --debug --config delphixpy.v1_8_0-examples/dxtools_1.conf  --update --user_name dev --password not_delphix --email "test@somethingelse.com"
    dx_users.py --delete --user_name dev
    dx_users.py --list

Options:
  --user_name <name>        The name of the user
  --password <password>     The password of the user to be created/updated
  --email <email_address>   The email addres of the user to be created/updated
  --jsonly                  Designate the user as a Jet Stream Only User
  --add                     Add the identified user
  --update                  Update the identified user
  --delete                  Delete the identified user
  --engine <type>           Alt Identifier of Delphix engine in dxtools.conf.
  --all                     Run against all engines.
  --debug                   Enable debug logging
  --parallel <n>            Limit number of jobs to maxjob
  --poll <n>                The number of seconds to wait between job polls
                            [default: 10]
  --config <path_to_file>   The path to the dxtools.conf file
                            [default: ./dxtools.conf]
  --logdir <path_to_file>    The path to the logfile you want to use.
                            [default: ./dx_skel.log]
  -h --help                 Show this screen.
  -v --version              Show version.
"""
from __future__ import print_function

import sys
from os.path import basename
from time import sleep
from time import time

from docopt import docopt

from delphixpy.v1_8_0.exceptions import HttpError
from delphixpy.v1_8_0.exceptions import JobError
from delphixpy.v1_8_0.exceptions import RequestError
from delphixpy.v1_8_0.web import authorization
from delphixpy.v1_8_0.web import job
from delphixpy.v1_8_0.web import role
from delphixpy.v1_8_0.web import user
from delphixpy.v1_8_0.web.vo import Authorization
from delphixpy.v1_8_0.web.vo import CredentialUpdateParameters
from delphixpy.v1_8_0.web.vo import PasswordCredential
from delphixpy.v1_8_0.web.vo import User
from lib.DlpxException import DlpxException
from lib.DxLogging import logging_est
from lib.DxLogging import print_debug
from lib.DxLogging import print_exception
from lib.DxLogging import print_info
from lib.GetReferences import find_all_objects
from lib.GetReferences import find_obj_by_name
from lib.GetSession import GetSession

VERSION = "v.0.0.004"

def add_user(user_name, user_password, user_email, jsonly=None):
    """
    This function adds the user
    """
    user_obj = User()
    user_obj.name = user_name
    user_obj.email_address = user_email
    user_obj.credential = PasswordCredential()
    user_obj.credential.password = user_password

    try:
        user.create(dx_session_obj.server_session, user_obj)
        print("Attempting to create {}".format(user_name))
    except (DlpxException, RequestError) as e:
        print_exception(
            "\nERROR: Creating the user {} "
            "encountered an error:\n{}".format(user_name, e)
        )
        sys.exit(1)

    js_only(user_name, jsonly)

def js_only(user_name, jsonly=None):
    """
    Switch the user to/from a jsonly user
    """
    user_obj = find_obj_by_name(dx_session_obj.server_session, user, user_name)
    role_obj = find_obj_by_name(dx_session_obj.server_session, role, "Jet Stream User")

    if jsonly:
        authorization_obj = Authorization()
        authorization_obj.role = role_obj.reference
        authorization_obj.target = user_obj.reference
        authorization_obj.user = user_obj.reference

        authorization.create(dx_session_obj.server_session, authorization_obj)
    else:

        auth_name = (
            "("
            + user_obj.reference
            + ", "
            + role_obj.reference
            + ", "
            + user_obj.reference
            + ")"
        )
        authorization.delete(
            dx_session_obj.server_session,
            find_obj_by_name(
                dx_session_obj.server_session, authorization, auth_name
            ).reference,
        )

def update_user(user_name, user_password=None, user_email=None, jsonly=None):
    """
    This function updates the user
    """

    if user_email:
        updated_user_obj = User()
        updated_user_obj.email_address = user_email

        try:
            user.update(
                dx_session_obj.server_session,
                find_obj_by_name(
                    dx_session_obj.server_session, user, user_name
                ).reference,
                updated_user_obj,
            )
            print("Attempting to update {}".format(user_name))
        except (DlpxException, RequestError) as e:
            print_exception(
                "\nERROR: Updating the user {} "
                "encountered an error:\n{}".format(user_name, e)
            )
            sys.exit(1)

    if user_password:
        new_password_obj = CredentialUpdateParameters()
        new_password_obj.new_credential = PasswordCredential()
        new_password_obj.new_credential.password = user_password

        try:
            user.update_credential(
                dx_session_obj.server_session,
                find_obj_by_name(
                    dx_session_obj.server_session, user, user_name
                ).reference,
                new_password_obj,
            )
            print("Attempting to update {} password".format(user_name))
        except (DlpxException, RequestError) as e:
            print_exception(
                "\nERROR: Updating the user {} password "
                "encountered an error:\n{}".format(user_name, e)
            )
            sys.exit(1)

    js_only(user_name, jsonly)

def delete_user(user_name):
    """
    This function adds the user
    """
    user_obj = find_obj_by_name(dx_session_obj.server_session, user, user_name)

    try:
        user.delete(dx_session_obj.server_session, user_obj.reference)
        print("Attempting to delete {}".format(user_name))
    except (DlpxException, RequestError) as e:
        print_exception(
            "\nERROR: Deleting the user {} "
            "encountered an error:\n{}".format(user_name, e)
        )
        sys.exit(1)

def list_users():
    """
    This function lists all users
    """
    user_list = find_all_objects(dx_session_obj.server_session, user)

    for user_obj in user_list:
        print("User: {}".format(user_obj.name))

def run_async(func):
    """
    http://code.activestate.com/recipes/576684-simple-threading-decorator/
    run_async(func)
        function decorator, intended to make "func" run in a separate
        thread (asynchronously).
        Returns the created Thread object
        E.g.:
        @run_async
        def task1():
            do_something
        @run_async
        def task2():
            do_something_too
        t1 = task1()
        t2 = task2()
        ...
        t1.join()
        t2.join()
    """
    from threading import Thread
    from functools import wraps

    @wraps(func)
    def async_func(*args, **kwargs):
        func_hl = Thread(target=func, args=args, kwargs=kwargs)
        func_hl.start()
        return func_hl

    return async_func

@run_async
def main_workflow(engine):
    """
    This function actually runs the jobs.
    Use the @run_async decorator to run this function asynchronously.
    This allows us to run against multiple Delphix Engine simultaneously

    engine: Dictionary of engines
    """
    try:
        # Setup the connection to the Delphix Engine
        dx_session_obj.serversess(
            engine["ip_address"], engine["username"], engine["password"]
        )

    except DlpxException as e:
        print_exception(
            "\nERROR: Engine {} encountered an error while"
            "{}:\n{}\n".format(engine["hostname"], arguments["--target"], e)
        )
        sys.exit(1)

    thingstodo = ["thingtodo"]
    try:
        with dx_session_obj.job_mode(single_thread):
            while len(dx_session_obj.jobs) > 0 or len(thingstodo) > 0:
                if len(thingstodo) > 0:
                    if arguments["--add"]:
                        add_user(
                            arguments["--user_name"],
                            arguments["--password"],
                            arguments["--email"],
                            arguments["--jsonly"],
                        )
                    elif arguments["--update"]:
                        update_user(
                            arguments["--user_name"],
                            arguments["--password"],
                            arguments["--email"],
                            arguments["--jsonly"],
                        )
                    elif arguments["--delete"]:
                        delete_user(arguments["--user_name"])
                    elif arguments["--list"]:
                        list_users()
                    thingstodo.pop()
                # get all the jobs, then inspect them
                i = 0
                for j in dx_session_obj.jobs.keys():
                    job_obj = job.get(
                        dx_session_obj.server_session, dx_session_obj.jobs[j]
                    )
                    print_debug(job_obj)
                    print_info(
                        "{}: User: {}".format(engine["hostname"], job_obj.job_state)
                    )
                    if job_obj.job_state in ["CANCELED", "COMPLETED", "FAILED"]:
                        # If the job is in a non-running state, remove it
                        # from the
                        # running jobs list.
                        del dx_session_obj.jobs[j]
                    elif job_obj.job_state in "RUNNING":
                        # If the job is in a running state, increment the
                        # running job count.
                        i += 1
                    print_info("{}: {:d} jobs running.".format(engine["hostname"], i))
                    # If we have running jobs, pause before repeating the
                    # checks.
                    if len(dx_session_obj.jobs) > 0:
                        sleep(float(arguments["--poll"]))

    except (HttpError, RequestError, JobError, DlpxException) as e:
        print_exception("ERROR: Could not complete user " "operation: {}".format(e))

def run_job():
    """
    This function runs the main_workflow aynchronously against all the servers
    specified
    """
    # Create an empty list to store threads we create.
    threads = []
    engine = None

    # If the --all argument was given, run against every engine in dxtools.conf
    if arguments["--all"]:
        print_info("Executing against all Delphix Engines in the dxtools.conf")

        try:
            # For each server in the dxtools.conf...
            for delphix_engine in dx_session_obj.dlpx_engines:
                engine = dx_session_obj[delphix_engine]
                # Create a new thread and add it to the list.
                threads.append(main_workflow(engine))

        except DlpxException as e:
            print("Error encountered in run_job():\n{}".format(e))
            sys.exit(1)

    elif arguments["--all"] is False:
        # Else if the --engine argument was given, test to see if the engine
        # exists in dxtools.conf
        if arguments["--engine"]:
            try:
                engine = dx_session_obj.dlpx_engines[arguments["--engine"]]
                print_info(
                    "Executing against Delphix Engine: {}\n".format(
                        (arguments["--engine"])
                    )
                )

            except (DlpxException, RequestError, KeyError) as e:
                raise DlpxException(
                    "\nERROR: Delphix Engine {} cannot be "
                    "found in {}. Please check your value "
                    "and try again. Exiting.\n".format(
                        arguments["--engine"], config_file_path
                    )
                )

        else:
            # Else search for a default engine in the dxtools.conf
            for delphix_engine in dx_session_obj.dlpx_engines:
                if dx_session_obj.dlpx_engines[delphix_engine]["default"] == "true":

                    engine = dx_session_obj.dlpx_engines[delphix_engine]
                    print_info(
                        "Executing against the default Delphix Engine "
                        "in the dxtools.conf: {}".format(
                            dx_session_obj.dlpx_engines[delphix_engine]["hostname"]
                        )
                    )

                break

            if engine == None:
                raise DlpxException("\nERROR: No default engine found. Exiting")

    # run the job against the engine
    threads.append(main_workflow(engine))

    # For each thread in the list...
    for each in threads:
        # join them back together so that we wait for all threads to complete
        # before moving on
        each.join()

def time_elapsed():
    """
    This function calculates the time elapsed since the beginning of the script.
    Call this anywhere you want to note the progress in terms of time
    """
    # elapsed_minutes = round((time() - time_start)/60, +1)
    # return elapsed_minutes
    return round((time() - time_start) / 60, +1)

def main(arguments):
    # We want to be able to call on these variables anywhere in the script.
    global single_thread
    global usebackup
    global time_start
    global config_file_path
    global dx_session_obj
    global debug

    if arguments["--debug"]:
        debug = True

    try:
        dx_session_obj = GetSession()
        logging_est(arguments["--logdir"])
        print_debug(arguments)
        time_start = time()
        single_thread = False
        config_file_path = arguments["--config"]
        # Parse the dxtools.conf and put it into a dictionary
        dx_session_obj.get_config(config_file_path)

        # This is the function that will handle processing main_workflow for
        # all the servers.
        run_job()

        elapsed_minutes = time_elapsed()
        print_info(
            "script took {:.2f} minutes to get this far.".format(elapsed_minutes)
        )

    # Here we handle what we do when the unexpected happens
    except DlpxException as e:
        print_exception(
            "script encountered an error while processing the"
            "config file:\n{}".format(e)
        )

    except SystemExit as e:
        """
        This is what we use to handle our sys.exit(#)
        """
        sys.exit(e)

    except HttpError as e:
        """
        We use this exception handler when our connection to Delphix fails
        """
        print_exception(
            "Connection failed to the Delphix Engine"
            "Please check the ERROR message:\n{}".format(e)
        )
        sys.exit(1)

    except JobError as e:
        """
        We use this exception handler when a job fails in Delphix so that
        we have actionable data
        """
        elapsed_minutes = time_elapsed()
        print_exception("A job failed in the Delphix Engine")
        print_info(
            "{} took {:.2f} minutes to get this far\n{}".format(
                basename(__file__), elapsed_minutes, e
            )
        )
        sys.exit(3)

    except KeyboardInterrupt:
        """
        We use this exception handler to gracefully handle ctrl+c exits
        """
        print_debug("You sent a CTRL+C to interrupt the process")
        elapsed_minutes = time_elapsed()
        print_info(
            "{} took {:.2f} minutes to get this far\n".format(
                basename(__file__), elapsed_minutes
            )
        )

    except:
        """
        Everything else gets caught here
        """
        print_exception(sys.exc_info()[0])
        elapsed_minutes = time_elapsed()
        print_info(
            "{} took {:.2f} minutes to get this far\n".format(
                basename(__file__), elapsed_minutes
            )
        )
        sys.exit(1)

if __name__ == "__main__":
    # Grab our arguments from the doc at the top of the script
    arguments = docopt(__doc__, version=basename(__file__) + " " + VERSION)
    # Feed our arguments to the main function, and off we go!
    main(arguments)


text:
package com.viesis.gemstones.common.items;

import com.viesis.gemstones.ViesisGemstones;

import net.minecraft.item.Item;

public class ItemHelper extends Item {

	public ItemHelper(String itemName)
	{
		setItemName(this, itemName);
	}

	//Set the registry name of {@code block} to {@code blockName}
	//and the unlocalised name to the full registry name.
	public static void setItemName(Item item, String itemName)
	{
		item.setRegistryName(itemName);
		item.setUnlocalizedName(item.getRegistryName().toString());
		item.setCreativeTab(ViesisGemstones.tabVGItems);
	}
}


text:
// Code generated by applyconfiguration-gen. DO NOT EDIT.

package v2beta2

import (
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// HorizontalPodAutoscalerStatusApplyConfiguration represents an declarative configuration of the HorizontalPodAutoscalerStatus type for use
// with apply.
type HorizontalPodAutoscalerStatusApplyConfiguration struct {
	ObservedGeneration *int64                                               `json:"observedGeneration,omitempty"`
	LastScaleTime      *v1.Time                                             `json:"lastScaleTime,omitempty"`
	CurrentReplicas    *int32                                               `json:"currentReplicas,omitempty"`
	DesiredReplicas    *int32                                               `json:"desiredReplicas,omitempty"`
	CurrentMetrics     []MetricStatusApplyConfiguration                     `json:"currentMetrics,omitempty"`
	Conditions         []HorizontalPodAutoscalerConditionApplyConfiguration `json:"conditions,omitempty"`
}

// HorizontalPodAutoscalerStatusApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerStatus type for use with
// apply.
func HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration {
	return &HorizontalPodAutoscalerStatusApplyConfiguration{}
}

// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ObservedGeneration field is set to the value of the last call.
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration {
	b.ObservedGeneration = &value
	return b
}

// WithLastScaleTime sets the LastScaleTime field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the LastScaleTime field is set to the value of the last call.
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration {
	b.LastScaleTime = &value
	return b
}

// WithCurrentReplicas sets the CurrentReplicas field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the CurrentReplicas field is set to the value of the last call.
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {
	b.CurrentReplicas = &value
	return b
}

// WithDesiredReplicas sets the DesiredReplicas field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the DesiredReplicas field is set to the value of the last call.
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {
	b.DesiredReplicas = &value
	return b
}

// WithCurrentMetrics adds the given value to the CurrentMetrics field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the CurrentMetrics field.
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentMetrics(values ...*MetricStatusApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {
	for i := range values {
		if values[i] == nil {
			panic("nil value passed to WithCurrentMetrics")
		}
		b.CurrentMetrics = append(b.CurrentMetrics, *values[i])
	}
	return b
}

// WithConditions adds the given value to the Conditions field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Conditions field.
func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithConditions(values ...*HorizontalPodAutoscalerConditionApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {
	for i := range values {
		if values[i] == nil {
			panic("nil value passed to WithConditions")
		}
		b.Conditions = append(b.Conditions, *values[i])
	}
	return b
}