text:
namespace boost {

//Forward declare boost::rv
template <class T> class rv;

namespace move_detail {

//////////////////////////////////////
//              nat
//////////////////////////////////////
struct nat{};

//////////////////////////////////////
//            natify
//////////////////////////////////////
template <class T> struct natify{};

//////////////////////////////////////
//          remove_reference
//////////////////////////////////////
template<class T>
struct remove_reference
{
   typedef T type;
};

template<class T>
struct remove_reference<T&>
{
   typedef T type;
};

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

template<class T>
struct remove_reference<T&&>
{
   typedef T type;
};

#else

template<class T>
struct remove_reference< rv<T> >
{
   typedef T type;
};

template<class T>
struct remove_reference< rv<T> &>
{
   typedef T type;
};

template<class T>
struct remove_reference< const rv<T> &>
{
   typedef T type;
};

#endif

//////////////////////////////////////
//             add_const
//////////////////////////////////////
template<class T>
struct add_const
{
   typedef const T type;
};

template<class T>
struct add_const<T&>
{
   typedef const T& type;
};

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

template<class T>
struct add_const<T&&>
{
   typedef T&& type;
};

#endif

//////////////////////////////////////
//      add_lvalue_reference
//////////////////////////////////////
template<class T>
struct add_lvalue_reference
{  typedef T& type;  };

template<class T> struct add_lvalue_reference<T&>                 {  typedef T& type;  };
template<>        struct add_lvalue_reference<void>               {  typedef void type;   };
template<>        struct add_lvalue_reference<const void>         {  typedef const void type;  };
template<>        struct add_lvalue_reference<volatile void>      {  typedef volatile void type;   };
template<>        struct add_lvalue_reference<const volatile void>{  typedef const volatile void type;   };

template<class T>
struct add_const_lvalue_reference
{
   typedef typename remove_reference<T>::type         t_unreferenced;
   typedef typename add_const<t_unreferenced>::type   t_unreferenced_const;
   typedef typename add_lvalue_reference
      <t_unreferenced_const>::type                    type;
};

//////////////////////////////////////
//             is_lvalue_reference
//////////////////////////////////////
template<class T>
struct is_lvalue_reference
{
    static const bool value = false;
};

template<class T>
struct is_lvalue_reference<T&>
{
    static const bool value = true;
};

//////////////////////////////////////
//          is_class_or_union
//////////////////////////////////////
template<class T>
struct is_class_or_union
{
   struct twochar { char dummy[2]; };
   template <class U>
   static char is_class_or_union_tester(void(U::*)(void));
   template <class U>
   static twochar is_class_or_union_tester(...);
   static const bool value = sizeof(is_class_or_union_tester<T>(0)) == sizeof(char);
};

//////////////////////////////////////
//             addressof
//////////////////////////////////////
template<class T>
struct addr_impl_ref
{
   T & v_;
   inline addr_impl_ref( T & v ): v_( v ) {}
   inline operator T& () const { return v_; }

   private:
   addr_impl_ref & operator=(const addr_impl_ref &);
};

template<class T>
struct addressof_impl
{
   static inline T * f( T & v, long )
   {
      return reinterpret_cast<T*>(
         &const_cast<char&>(reinterpret_cast<const volatile char &>(v)));
   }

   static inline T * f( T * v, int )
   {  return v;  }
};

template<class T>
inline T * addressof( T & v )
{
   return ::boost::move_detail::addressof_impl<T>::f
      ( ::boost::move_detail::addr_impl_ref<T>( v ), 0 );
}

//////////////////////////////////////
//          has_pointer_type
//////////////////////////////////////
template <class T>
struct has_pointer_type
{
   struct two { char c[2]; };
   template <class U> static two test(...);
   template <class U> static char test(typename U::pointer* = 0);
   static const bool value = sizeof(test<T>(0)) == 1;
};

//////////////////////////////////////
//           is_convertible
//////////////////////////////////////
#if defined(_MSC_VER) && (_MSC_VER >= 1400)

//use intrinsic since in MSVC
//overaligned types can't go through ellipsis
template <class T, class U>
struct is_convertible
{
   static const bool value = __is_convertible_to(T, U);
};

#else

template <class T, class U>
class is_convertible
{
   typedef typename add_lvalue_reference<T>::type t_reference;
   typedef char true_t;
   class false_t { char dummy[2]; };
   static false_t dispatch(...);
   static true_t  dispatch(U);
   static t_reference       trigger();
   public:
   static const bool value = sizeof(dispatch(trigger())) == sizeof(true_t);
};

#endif

//////////////////////////////////////////////////////////////////////////////
//
//                               has_move_emulation_enabled_impl
//
//////////////////////////////////////////////////////////////////////////////
template<class T>
struct has_move_emulation_enabled_impl
   : is_convertible< T, ::boost::rv<T>& >
{};

template<class T>
struct has_move_emulation_enabled_impl<T&>
{  static const bool value = false;  };

template<class T>
struct has_move_emulation_enabled_impl< ::boost::rv<T> >
{  static const bool value = false;  };

//////////////////////////////////////////////////////////////////////////////
//
//                            is_rv_impl
//
//////////////////////////////////////////////////////////////////////////////

template <class T>
struct is_rv_impl
{  static const bool value = false;  };

template <class T>
struct is_rv_impl< rv<T> >
{  static const bool value = true;  };

template <class T>
struct is_rv_impl< const rv<T> >
{  static const bool value = true;  };

// Code from Jeffrey Lee Hellrung, many thanks

template< class T >
struct is_rvalue_reference
{  static const bool value = false;  };

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

template< class T >
struct is_rvalue_reference< T&& >
{  static const bool value = true;  };

#else // #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

template< class T >
struct is_rvalue_reference< boost::rv<T>& >
{  static const bool value = true;  };

template< class T >
struct is_rvalue_reference< const boost::rv<T>& >
{  static const bool value = true;  };

#endif // #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

template< class T >
struct add_rvalue_reference
{ typedef T&& type; };

#else // #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

namespace detail_add_rvalue_reference
{
   template< class T
            , bool emulation = has_move_emulation_enabled_impl<T>::value
            , bool rv        = is_rv_impl<T>::value  >
   struct add_rvalue_reference_impl { typedef T type; };

   template< class T, bool emulation>
   struct add_rvalue_reference_impl< T, emulation, true > { typedef T & type; };

   template< class T, bool rv >
   struct add_rvalue_reference_impl< T, true, rv > { typedef ::boost::rv<T>& type; };
} // namespace detail_add_rvalue_reference

template< class T >
struct add_rvalue_reference
   : detail_add_rvalue_reference::add_rvalue_reference_impl<T>
{ };

template< class T >
struct add_rvalue_reference<T &>
{  typedef T & type; };

#endif // #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

template< class T > struct remove_rvalue_reference { typedef T type; };

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   template< class T > struct remove_rvalue_reference< T&& >                  { typedef T type; };
#else // #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   template< class T > struct remove_rvalue_reference< rv<T> >                { typedef T type; };
   template< class T > struct remove_rvalue_reference< const rv<T> >          { typedef T type; };
   template< class T > struct remove_rvalue_reference< volatile rv<T> >       { typedef T type; };
   template< class T > struct remove_rvalue_reference< const volatile rv<T> > { typedef T type; };
   template< class T > struct remove_rvalue_reference< rv<T>& >               { typedef T type; };
   template< class T > struct remove_rvalue_reference< const rv<T>& >         { typedef T type; };
   template< class T > struct remove_rvalue_reference< volatile rv<T>& >      { typedef T type; };
   template< class T > struct remove_rvalue_reference< const volatile rv<T>& >{ typedef T type; };
#endif // #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES

// Ideas from Boost.Move review, Jeffrey Lee Hellrung:
//
//- TypeTraits metafunctions is_lvalue_reference, add_lvalue_reference, and remove_lvalue_reference ?
//  Perhaps add_reference and remove_reference can be modified so that they behave wrt emulated rvalue
//  references the same as wrt real rvalue references, i.e., add_reference< rv<T>& > -> T& rather than
//  rv<T>& (since T&& & -> T&).
//
//- Add'l TypeTraits has_[trivial_]move_{constructor,assign}...?
//
//- An as_lvalue(T& x) function, which amounts to an identity operation in C++0x, but strips emulated
//  rvalue references in C++03.  This may be necessary to prevent "accidental moves".

}  //namespace move_detail {
}  //namespace boost {

#endif //#ifndef BOOST_MOVE_DETAIL_META_UTILS_HPP


text: Empty directory, populated by docker-compose up setup-wiremock

redpajama_set_name: RedPajamaGithub


text:
package de.tum.in.www1.exerciseapp.repository;

import de.tum.in.www1.exerciseapp.domain.Exercise;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.security.Principal;

/**
 * Spring Data JPA repository for the Exercise entity.
 */
@SuppressWarnings("unused")
@Repository
public interface ExerciseRepository extends JpaRepository<Exercise, Long> {

    Page<Exercise> findByCourseId(@Param("courseId") Long courseId, Pageable pageable);

    /**
     * Select Exercise for Course ID
     * WHERE
     * there does not exist any LtiOutcomeUrl for this exercise (-> this is not an online exercise)
     * OR
     * there does exist an LtiOutcomeUrl for the current user (-> user has started exercise once using LTI)
     *
     */
    @Query("SELECT e FROM Exercise e WHERE e.course.id =  :#{#courseId} AND ((NOT EXISTS(SELECT l from LtiOutcomeUrl l WHERE e = l.exercise)) OR EXISTS (SELECT l2 from LtiOutcomeUrl l2 WHERE e = l2.exercise AND l2.user.login = :#{#principal.name})) ")
    Page<Exercise> findByCourseIdWhereLtiOutcomeUrlExists(@Param("courseId") Long courseId, @Param("principal") Principal principal, Pageable pageable);

}


text:
export const TgPropertyColumnBehavior = {

    properties: {
        property: String,
        tooltipProperty: String,
        type: String,
        width: Number,
        minWidth: Number,
        growFactor: Number,
        columnTitle: String,
        columnDesc: String,
        vertical: {
            type: Boolean,
            value: false
        }
    },

    hostAttributes: {
        hidden: true
    }
}


text:
#ifndef CONFIG_SPEEDTREE_H
#define CONFIG_SPEEDTREE_H

#include "pandabase.h"
#include "notifyCategoryProxy.h"
#include "configVariableBool.h"
#include "configVariableDouble.h"
#include "configVariableString.h"
#include "configVariableInt.h"
#include "configVariableFilename.h"
#include "configVariableColor.h"

NotifyCategoryDecl(speedtree, EXPCL_PANDASPEEDTREE, EXPTP_PANDASPEEDTREE);

extern ConfigVariableString speedtree_license;
extern ConfigVariableFilename speedtree_shaders_dir;
extern ConfigVariableFilename speedtree_textures_dir;
extern ConfigVariableDouble speedtree_max_anisotropy;
extern ConfigVariableBool speedtree_horizontal_billboards;
extern ConfigVariableDouble speedtree_alpha_test_scalar;
extern ConfigVariableBool speedtree_z_pre_pass;
extern ConfigVariableInt speedtree_max_billboard_images_by_base;

extern ConfigVariableDouble speedtree_visibility;
extern ConfigVariableDouble speedtree_global_light_scalar;
extern ConfigVariableBool speedtree_specular_lighting;
extern ConfigVariableBool speedtree_transmission_lighting;
extern ConfigVariableBool speedtree_detail_layer;
extern ConfigVariableBool speedtree_detail_normal_mapping;
extern ConfigVariableBool speedtree_ambient_contrast;
extern ConfigVariableDouble speedtree_transmission_scalar;
extern ConfigVariableDouble speedtree_fog_distance;
extern ConfigVariableColor speedtree_fog_color;
extern ConfigVariableColor speedtree_sky_color;
extern ConfigVariableDouble speedtree_sky_fog_min;
extern ConfigVariableDouble speedtree_sky_fog_max;
extern ConfigVariableColor speedtree_sun_color;
extern ConfigVariableDouble speedtree_sun_size;
extern ConfigVariableDouble speedtree_sun_spread_exponent;
extern ConfigVariableDouble speedtree_sun_fog_bloom;
extern ConfigVariableColor speedtree_specular_color;
extern ConfigVariableColor speedtree_emissive_color;
extern ConfigVariableInt speedtree_shadow_map_resolution;
extern ConfigVariableDouble speedtree_cascading_shadow_splits;
extern ConfigVariableBool speedtree_smooth_shadows;
extern ConfigVariableBool speedtree_show_shadow_splits_on_terrain;
extern ConfigVariableBool speedtree_wind_enabled;
extern ConfigVariableBool speedtree_frond_rippling;
extern ConfigVariableInt speedtree_terrain_num_lods;
extern ConfigVariableInt speedtree_terrain_resolution;
extern ConfigVariableInt speedtree_terrain_cell_size;

extern ConfigVariableDouble speedtree_shadow_fade;
extern ConfigVariableBool speedtree_show_overlays;

extern ConfigVariableInt speedtree_max_num_visible_cells;
extern ConfigVariableDouble speedtree_cull_cell_size;
extern ConfigVariableDouble speedtree_area_scale;
extern ConfigVariableBool speedtree_follow_terrain;
extern ConfigVariableInt speedtree_max_random_try_count;
extern ConfigVariableBool speedtree_5_2_stf;

extern EXPCL_PANDASPEEDTREE void init_libspeedtree();

#endif


text:
require "spec_helper"

describe CostsController do
  describe "routing" do

    it "routes to #index" do
      get("/costs").should route_to("costs#index")
    end

    it "routes to #new" do
      get("/costs/new").should route_to("costs#new")
    end

    it "routes to #show" do
      get("/costs/1").should route_to("costs#show", :id => "1")
    end

    it "routes to #edit" do
      get("/costs/1/edit").should route_to("costs#edit", :id => "1")
    end

    it "routes to #create" do
      post("/costs").should route_to("costs#create")
    end

    it "routes to #update" do
      put("/costs/1").should route_to("costs#update", :id => "1")
    end

    it "routes to #destroy" do
      delete("/costs/1").should route_to("costs#destroy", :id => "1")
    end

  end
end


text:
[![License](http://img.shields.io/:license-apache-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0.html)
[![Build Status](https://travis-ci.org/teampants/ansible-local-hosts.svg?branch=develop)](https://travis-ci.org/teampants/ansible-local-hosts)
# ansible-local-hosts
Adds hosts to local /etc/hosts file

## Adding hosts to /etc/hosts on your local workstastion
To add the created host(s) to your local /etc/hosts set ~add_to_local_etc_hosts~ to true.

**Warning: You must set serial=1 on the play that includes this role to use this feature, due to concurrency issues when
editing files. This requirement will go away in the future. See https://github.com/ansible/ansible-modules-core/pull/1902**

## Example Playbook

~~~
- hosts: local-vagrant
  serial: 1
  sudo: yes
  roles:
    - role: teampants.local-hosts
~~~


text:
package com.taobao.android.dx.dex.file;

import com.taobao.android.dx.rop.cst.CstFieldRef;

/**
 * Representation of a field reference inside a Dalvik file.
 */
public final class FieldIdItem extends MemberIdItem {
    /**
     * Constructs an instance.
     *
     * @param field {@code non-null;} the constant for the field
     */
    public FieldIdItem(CstFieldRef field) {
        super(field);
    }

    /** {@inheritDoc} */
    @Override
    public ItemType itemType() {
        return ItemType.TYPE_FIELD_ID_ITEM;
    }

    /** {@inheritDoc} */
    @Override
    public void addContents(DexFile file) {
        super.addContents(file);

        TypeIdsSection typeIds = file.getTypeIds();
        typeIds.intern(getFieldRef().getType());
    }

    /**
     * Gets the field constant.
     *
     * @return {@code non-null;} the constant
     */
    public CstFieldRef getFieldRef() {
        return (CstFieldRef) getRef();
    }

    /** {@inheritDoc} */
    @Override
    protected int getTypoidIdx(DexFile file) {
        TypeIdsSection typeIds = file.getTypeIds();
        return typeIds.indexOf(getFieldRef().getType());
    }

    /** {@inheritDoc} */
    @Override
    protected String getTypoidName() {
        return "type_idx";
    }
}


text:
require 'includes/config'
require 'includes/database'
require 'includes/helpers'

##############################################################################
### F I N D   F I L E S   I N   D A T A B A S E
##############################################################################

print "Fetching files from the database..."

hashed_files        = @mp3s.filter( :hashed => true        ).map( :path )
fingerprinted_files = @mp3s.filter( :fingerprinted => true ).map( :path )

log "done!"

log # blank line

log "Found #{@mp3s.count} files, of which:"
log "  * #{hashed_files.size} have been hashed, and"
log "  * #{fingerprinted_files.size} have been fingerprinted."

log # blank line

size = 0
DB[ "SELECT pg_size_pretty( sum( size ) ) FROM mp3s" ].each {|r| size = r[:pg_size_pretty] }

log "The files in the database take up a total of #{size}."


text:
package org.apache.phoenix.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Nonnull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Maps;

/**
 *
 * Read-only properties that avoids unnecessary synchronization in
 * java.util.Properties.
 *
 */
public class ReadOnlyProps implements Iterable<Entry<String, String>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadOnlyProps.class);
    public static final ReadOnlyProps EMPTY_PROPS = new ReadOnlyProps();
    @Nonnull
    private final Map<String, String> props;
    @Nonnull
    private final Map<String, String> overrideProps;

    public ReadOnlyProps(ReadOnlyProps defaultProps, Iterator<Entry<String, String>> iterator) {
        Map<String, String> map = new HashMap<String,String>(defaultProps.asMap());
        while (iterator.hasNext()) {
            Entry<String,String> entry = iterator.next();
            map.put(entry.getKey(), entry.getValue());
        }
        this.props = ImmutableMap.copyOf(map);
        this.overrideProps = ImmutableMap.of();
    }

    public ReadOnlyProps(Iterator<Entry<String, String>> iterator) {
        this(EMPTY_PROPS, iterator);
    }

    private ReadOnlyProps() {
        this.props = ImmutableMap.of();
        this.overrideProps = ImmutableMap.of();
    }

    public ReadOnlyProps(Map<String, String> props) {
        this.props = ImmutableMap.copyOf(props);
        this.overrideProps = ImmutableMap.of();
    }

    private ReadOnlyProps(ReadOnlyProps defaultProps, Properties overridesArg) {
        this.props = defaultProps.props;
        if (overridesArg == null || overridesArg.isEmpty()) {
            this.overrideProps = defaultProps.overrideProps;
        } else {
            Map<String, String> combinedOverrides =
                    Maps.newHashMapWithExpectedSize(defaultProps.overrideProps.size()
                            + overridesArg.size());
            if (!defaultProps.overrideProps.isEmpty()) {
                combinedOverrides.putAll(defaultProps.overrideProps);
            }
            for (Entry<Object, Object> entry : overridesArg.entrySet()) {
                combinedOverrides.put(entry.getKey().toString(), entry.getValue().toString());
            }
            this.overrideProps = ImmutableMap.copyOf(combinedOverrides);
        }
    }

    private static Pattern varPat = Pattern.compile("\\$\\{[^\\}\\$\u0020]+\\}");
    private static int MAX_SUBST = 20;

    private String substituteVars(String expr) {
        if (expr == null) {
          return null;
        }
        Matcher match = varPat.matcher("");
        String eval = expr;
        for(int s=0; s<MAX_SUBST; s++) {
          match.reset(eval);
          if (!match.find()) {
            return eval;
          }
          String var = match.group();
          var = var.substring(2, var.length()-1); // remove ${ .. }
          String val = null;
          try {
            val = System.getProperty(var);
          } catch(SecurityException se) {
          }
          if (val == null) {
            val = getRaw(var);
          }
          if (val == null) {
            return eval; // return literal ${var}: var is unbound
          }
          // substitute
          eval = eval.substring(0, match.start())+val+eval.substring(match.end());
        }
        throw new IllegalStateException("Variable substitution depth too large: "
                                        + MAX_SUBST + " " + expr);
      }

    /**
     * Get the value of the name property, without doing
     * variable expansion.
     *
     * @param name the property name.
     * @return the value of the name property,
     *         or null if no such property exists.
     */
    public String getRaw(String name) {
      String overridenValue = overrideProps.get(name);
      return overridenValue == null ? props.get(name) : overridenValue;
    }

    public String getRaw(String name, String defaultValue) {
        String value = getRaw(name);
        if (value == null) {
            return defaultValue;
        }
        return value;
      }

    /**
     * Get the value of the name property. If no such property
     * exists, then defaultValue is returned.
     *
     * @param name property name.
     * @param defaultValue default value.
     * @return property value, or defaultValue if the property
     *         doesn't exist.
     */
    public String get(String name, String defaultValue) {
      return substituteVars(getRaw(name, defaultValue));
    }

    /**
     * Get the value of the name property, null if
     * no such property exists.
     *
     * Values are processed for variable expansion
     * before being returned.
     *
     * @param name the property name.
     * @return the value of the name property,
     *         or null if no such property exists.
     */
    public String get(String name) {
      return substituteVars(getRaw(name));
    }

    private String getHexDigits(String value) {
        boolean negative = false;
        String str = value;
        String hexString = null;
        if (value.startsWith("-")) {
          negative = true;
          str = value.substring(1);
        }
        if (str.startsWith("0x") || str.startsWith("0X")) {
          hexString = str.substring(2);
          if (negative) {
            hexString = "-" + hexString;
          }
          return hexString;
        }
        return null;
      }

    /**
     * Get the value of the name property as a boolean.
     * If no such property is specified, or if the specified value is not a valid
     * boolean, then defaultValue is returned.
     *
     * @param name property name.
     * @param defaultValue default value.
     * @return property value as a boolean,
     *         or defaultValue.
     */
    public boolean getBoolean(String name, boolean defaultValue) {
      String valueString = get(name);
      if ("true".equals(valueString))
        return true;
      else if ("false".equals(valueString))
        return false;
      else return defaultValue;
    }

    /**
     * Get the value of the name property as an int.
     *
     * If no such property exists, or if the specified value is not a valid
     * int, then defaultValue is returned.
     *
     * @param name property name.
     * @param defaultValue default value.
     * @return property value as an int,
     *         or defaultValue.
     */
    public int getInt(String name, int defaultValue) {
      String valueString = get(name);
      if (valueString == null)
        return defaultValue;
      try {
        String hexString = getHexDigits(valueString);
        if (hexString != null) {
          return Integer.parseInt(hexString, 16);
        }
        return Integer.parseInt(valueString);
      } catch (NumberFormatException e) {
        return defaultValue;
      }
    }

    /**
     * Get the value of the name property as a long.
     * If no such property is specified, or if the specified value is not a valid
     * long, then defaultValue is returned.
     *
     * @param name property name.
     * @param defaultValue default value.
     * @return property value as a long,
     *         or defaultValue.
     */
    public long getLong(String name, long defaultValue) {
      String valueString = get(name);
      if (valueString == null)
        return defaultValue;
      try {
        String hexString = getHexDigits(valueString);
        if (hexString != null) {
          return Long.parseLong(hexString, 16);
        }
        return Long.parseLong(valueString);
      } catch (NumberFormatException e) {
        return defaultValue;
      }
    }

    /**
     * Get the value of the name property as a float.
     * If no such property is specified, or if the specified value is not a valid
     * float, then defaultValue is returned.
     *
     * @param name property name.
     * @param defaultValue default value.
     * @return property value as a float,
     *         or defaultValue.
     */
    public float getFloat(String name, float defaultValue) {
      String valueString = get(name);
      if (valueString == null)
        return defaultValue;
      try {
        return Float.parseFloat(valueString);
      } catch (NumberFormatException e) {
        return defaultValue;
      }
    }

    /**
     * Get the properties as a Map<String,String>
     *
     * @return Map<String,String>
     */
    public Map<String,String> asMap() {
        return props;
    }

    @Override
    public Iterator<Entry<String, String>> iterator() {
        return props.entrySet().iterator();
    }

    public boolean isEmpty() {
        return props.isEmpty();
    }

    /**
     * Constructs new map only if necessary for adding the override properties.
     * @param overrides Map of properties to override current properties.
     * @return new ReadOnlyProps if in applying the overrides there are
     * modifications to the current underlying Map, otherwise returns this.
     */
    public ReadOnlyProps addAll(Properties overrides) {
        for (Entry<Object, Object> entry : overrides.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            String oldValue = props.get(key);
            if (!Objects.equal(oldValue, value)) {
                if (LOGGER.isDebugEnabled()) LOGGER.debug("Creating new ReadOnlyProps due to " + key + " with " + oldValue + "!=" + value);
                return new ReadOnlyProps(this, overrides);
            }
        }
        return this;
    }
}


text:
#region License

#endregion
using System.Globalization;
using System.Abstract.Parts;
namespace System.Abstract
{
    /// <summary>
    /// ServiceLogExtensions
    /// </summary>
    public static class ServiceLogExtensions
    {
        // get
        /// <summary>
        /// Gets the specified service.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="service">The service.</param>
        /// <returns></returns>
        public static IServiceLog Get<T>(this IServiceLog service) { return service.Get(typeof(T)); }

        // log
        /// <summary>
        /// Fatals the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        public static void Fatal(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Fatal, null, s); }
        /// <summary>
        /// Fatals the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        public static void Fatal(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Fatal, ex, null); }
        /// <summary>
        /// Fatals the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void FatalFormat(this IServiceLog service, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Fatal, null, s);
        }
        /// <summary>
        /// Fatals the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void FatalFormat(this IServiceLog service, Exception ex, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Fatal, ex, s);
        }
        /// <summary>
        /// Errors the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        public static void Error(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Error, null, s); }
        /// <summary>
        /// Errors the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        public static void Error(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Error, ex, null); }
        /// <summary>
        /// Errors the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void ErrorFormat(this IServiceLog service, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Error, null, s);
        }
        /// <summary>
        /// Errors the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void ErrorFormat(this IServiceLog service, Exception ex, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Error, ex, s);
        }
        /// <summary>
        /// Warnings the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        public static void Warning(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Warning, null, s); }
        /// <summary>
        /// Warnings the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        public static void Warning(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Warning, ex, null); }
        /// <summary>
        /// Warnings the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void WarningFormat(this IServiceLog service, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Warning, null, s);
        }
        /// <summary>
        /// Warnings the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void WarningFormat(this IServiceLog service, Exception ex, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Warning, ex, s);
        }
        /// <summary>
        /// Informations the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        public static void Information(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Information, null, s); }
        /// <summary>
        /// Informations the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        public static void Information(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Information, ex, null); }
        /// <summary>
        /// Informations the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void InformationFormat(this IServiceLog service, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Information, null, s);
        }
        /// <summary>
        /// Informations the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void InformationFormat(this IServiceLog service, Exception ex, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Information, ex, s);
        }
        /// <summary>
        /// Debugs the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        public static void Debug(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Debug, null, s); }
        /// <summary>
        /// Debugs the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        public static void Debug(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Debug, ex, null); }
        /// <summary>
        /// Debugs the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void DebugFormat(this IServiceLog service, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Debug, null, s);
        }
        /// <summary>
        /// Debugs the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="ex">The ex.</param>
        /// <param name="s">The s.</param>
        /// <param name="args">The args.</param>
        public static void DebugFormat(this IServiceLog service, Exception ex, string s, params object[] args)
        {
            s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
            service.Write(ServiceLog.LogLevel.Debug, ex, s);
        }

        #region BehaveAs

        /// <summary>
        /// Behaves as.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="service">The service.</param>
        /// <returns></returns>
        public static T BehaveAs<T>(this IServiceLog service)
            where T : class, IServiceLog
        {
            IServiceWrapper<IServiceLog> serviceWrapper;
            do
            {
                serviceWrapper = (service as IServiceWrapper<IServiceLog>);
                if (serviceWrapper != null)
                    service = serviceWrapper.Parent;
            } while (serviceWrapper != null);
            return (service as T);
        }

        #endregion

        #region Lazy Setup

        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service)
            where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, ServiceLocatorManager.Lazy, null); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, string name)
            where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, ServiceLocatorManager.Lazy, name); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="locator">The locator.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, Lazy<IServiceLocator> locator)
            where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, null); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="locator">The locator.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, Lazy<IServiceLocator> locator, string name)
            where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, name); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, ServiceLocatorManager.Lazy, null); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, string name) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, ServiceLocatorManager.Lazy, name); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="locator">The locator.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, Lazy<IServiceLocator> locator) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, null); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="locator">The locator.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, Lazy<IServiceLocator> locator, string name) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, name); return service; }

        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="service">The service.</param>
        /// <param name="locator">The locator.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, IServiceLocator locator)
            where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, null); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="service">The service.</param>
        /// <param name="locator">The locator.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, IServiceLocator locator, string name)
            where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, name); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="locator">The locator.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, IServiceLocator locator) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, null); return service; }
        /// <summary>
        /// Registers the with service locator.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="locator">The locator.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, IServiceLocator locator, string name) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, name); return service; }

        #endregion
    }
}


text:
```js
var blake2 = require('blake2');
```

## Creating a hash
```js
var hash = blake2.createHash([algorithm[, out_length]]);
```

The `algorithm` can either be:
- blake2b _(default)_
- blake2bp
- blake2s
- blake2sp

The `out_length` parameter is the final hash length and is an integer between 1 and:
- 64 for blake2b and blake2bp _(default)_
- 32 for blake2s and blake2sp

## Updating the hash
```js
hash.update([data[, encoding]]);
```

## Creating the digest
```js
hash.digest([encoding]);
```

## Pseudo-class
```js
class blake2 {
	constructor(algorithm = 'blake2b', out_length = 64) {
		this.algorithm = algorithm;
		<blake2::blake2X_init(&this._state, out_length)>;
	}

	update(data, encoding) {
		if (typeof data !== Buffer)
			data = new Buffer(data, encoding);

		<blake2::blakeX_update(&this._state, data)>
	}

	digest() {
		return <blake2::blake2X_final(&this._state)>
	}
}
```


text:
<!DOCTYPE html>

		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
		<meta charset="utf-8" />
		<title>BdoIndonesia Login Page</title>

		<meta name="description" content="User login page" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />

		<link rel="stylesheet" href="../assets/css/bootstrap.css" />
		<link rel="stylesheet" href="../assets/css/font-awesome.css" />

		<link rel="stylesheet" href="../assets/css/ace-fonts.css" />

		<link rel="stylesheet" href="../assets/css/ace.css" />

		<link rel="stylesheet" href="../assets/css/ace-rtl.css" />

									BDO Portal

© BDO Indonesia

												Please Enter Your Information

											<form>
												<fieldset>

															<input type="text" class="form-control" placeholder="Username" />

															<input type="password" class="form-control" placeholder="Password" />

															<input type="checkbox" class="ace" />
															 Remember Me

														<button type="button" class="width-35 pull-right btn btn-md btn-primary">

															Login
														</button>

												</fieldset>
											</form>

													I forgot my password

												Retrieve Password

												Enter your email and to receive instructions

											<form>
												<fieldset>

															<input type="email" class="form-control" placeholder="Email" />

														<button type="button" class="width-35 pull-right btn btn-sm btn-danger">

															Send Me!
														</button>

												</fieldset>
											</form>

												Back to login

								Dark

								/

								Blur

								/

								Light


text:
'use strict';

const fs = require('fs');
const _ = require('lodash');
const Funnel = require('broccoli-funnel');
const MergeTrees = require('broccoli-merge-trees');
const SVGOptimizer = require('broccoli-svg-optimizer');
const broccoliReplace = require('broccoli-string-replace');
const Symbolizer = require('./symbolizer/symbolizer');
const InlinePacker = require('./inline-packer');
const ViewerAssetsBuilder = require('./viewer-assets-builder');
const ViewerBuilder = require('./viewer-builder');
const buildOptions = require('./build-options');
const { makeIDForPath } = require('./utils');
const prepareSymbolLoaderScript = require('./prepare-symbol-loader-script');

function mergeTreesIfNeeded(trees, options) {
  let mergedOptions = _.assign({ overwrite: true }, options);
  return trees.length === 1 ? trees[0] : new MergeTrees(trees, mergedOptions);
}

module.exports = {
  name: 'ember-svg-jar',

  isDevelopingAddon() {
    return false;
  },

  included(app) {
    this._super.included.apply(this, arguments);
    this.svgJarOptions = buildOptions(app);
  },

  treeForPublic() {
    let trees = [];

    if (this.svgJarOptions.viewer.enabled) {
      // Add `svg-jar-viewer.json` to public dir
      trees.push(this.getViewerTree());

      // Add viewer assets to public dir
      let svgJarPublicTree = this._super.treeForPublic.apply(this, arguments);

      svgJarPublicTree = broccoliReplace(svgJarPublicTree, {
        files: ['**/index.html'],
        pattern: {
          match: /\{\{ROOT_URL\}\}/g,
          replacement: this.svgJarOptions.rootURL,
        },
      });

      trees.push(svgJarPublicTree);
    }

    if (this.hasSymbolStrategy()) {
      trees.push(this.getSymbolStrategyTree());
    }

    return mergeTreesIfNeeded(trees);
  },

  treeForAddon(addonTree) {
    let trees = [addonTree];

    if (this.hasInlineStrategy()) {
      trees.push(this.getInlineStrategyTree());
    }

    return this._super.treeForAddon.call(this, mergeTreesIfNeeded(trees));
  },

  contentFor(type, app) {
    const includeLoader =
      this.hasSymbolStrategy() && this.optionFor('symbol', 'includeLoader');

    if (type === 'body' && includeLoader) {
      const rootURL = this.svgJarOptions.rootURL;
      const outputFile = this.optionFor('symbol', 'outputFile');
      const isTestEnv = app.environment === 'test';

      return prepareSymbolLoaderScript(rootURL, outputFile, isTestEnv);
    }

    return '';
  },

  optionFor(strategy, optionName) {
    // globalOptions can be both root or strategy specific.
    let globalOptions = ['sourceDirs', 'stripPath', 'optimizer'];

    return _.isUndefined(this.svgJarOptions[strategy][optionName])
      ? globalOptions.indexOf(optionName) !== -1 &&
          this.svgJarOptions[optionName]
      : this.svgJarOptions[strategy][optionName];
  },

  sourceDirsFor(strategy) {
    return this.optionFor(strategy, 'sourceDirs').filter(
      sourceDir => typeof sourceDir !== 'string' || fs.existsSync(sourceDir)
    );
  },

  originalSvgsFor(strategy) {
    let sourceDirs = this.sourceDirsFor(strategy);

    return new Funnel(mergeTreesIfNeeded(sourceDirs), {
      include: ['**/*.svg'],
    });
  },

  optimizedSvgsFor(strategy, originalSvgs) {
    let optimizerConfig = this.optionFor(strategy, 'optimizer');

    return new SVGOptimizer(originalSvgs, {
      svgoConfig: _.omit(optimizerConfig, 'svgoModule'),
      svgoModule: optimizerConfig.svgoModule,
      persist: this.svgJarOptions.persist,
    });
  },

  svgsFor(strategy) {
    let originalSvgs = this.originalSvgsFor(strategy);

    return this.hasOptimizerFor(strategy)
      ? this.optimizedSvgsFor(strategy, originalSvgs)
      : originalSvgs;
  },

  getViewerTree() {
    let viewerBuilderTrees = this.svgJarOptions.strategy.map(strategy => {
      let idGen = this.optionFor(strategy, 'idGen');
      let stripPath = this.optionFor(strategy, 'stripPath');
      let prefix = this.optionFor(strategy, 'prefix');

      return new ViewerAssetsBuilder(this.svgsFor(strategy), {
        strategy,
        validationConfig: this.svgJarOptions.validations,
        copypastaGen: this.optionFor(strategy, 'copypastaGen'),

        makeAssetID(relativePath) {
          return makeIDForPath(relativePath, { idGen, stripPath, prefix });
        },
      });
    });

    return new ViewerBuilder(mergeTreesIfNeeded(viewerBuilderTrees), {
      outputFile: 'svg-jar-viewer.json',
    });
  },

  getInlineStrategyTree() {
    let idGen = this.optionFor('inline', 'idGen');
    let stripPath = this.optionFor('inline', 'stripPath');

    return new InlinePacker(this.svgsFor('inline'), {
      makeAssetID(relativePath) {
        return makeIDForPath(relativePath, { idGen, stripPath });
      },
    });
  },

  getSymbolStrategyTree() {
    let idGen = this.optionFor('symbol', 'idGen');
    let stripPath = this.optionFor('symbol', 'stripPath');
    let prefix = this.optionFor('symbol', 'prefix');

    return new Symbolizer(this.svgsFor('symbol'), {
      outputFile: this.optionFor('symbol', 'outputFile'),
      svgAttrs: this.optionFor('symbol', 'containerAttrs'),
      persist: this.svgJarOptions.persist,

      makeAssetID(relativePath) {
        return makeIDForPath(relativePath, { idGen, stripPath, prefix });
      },
    });
  },

  hasOptimizerFor(strategy) {
    return this.optionFor(strategy, 'optimizer');
  },

  hasInlineStrategy() {
    return this.svgJarOptions.strategy.includes('inline');
  },

  hasSymbolStrategy() {
    return this.svgJarOptions.strategy.includes('symbol');
  },
};


text:
package com.evolveum.midpoint.model.impl.expr.triggerSetter;

import com.evolveum.midpoint.CacheInvalidationContext;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.repo.api.Cacheable;
import com.evolveum.midpoint.repo.api.DeleteObjectResult;
import com.evolveum.midpoint.repo.cache.CacheRegistry;
import com.evolveum.midpoint.repo.cache.RepositoryCache;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SingleCacheStateInformationType;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 *  Global state for optimizing trigger creators for the given midPoint node.
 */
@Component
public class TriggerCreatorGlobalState implements Cacheable {

    private static final Trace LOGGER = TraceManager.getTrace(TriggerCreatorGlobalState.class);

    private AtomicLong lastExpirationCleanup = new AtomicLong(0L);

    private static final long EXPIRATION_INTERVAL = 10000L;

    @Autowired private CacheRegistry cacheRegistry;
    @Autowired private PrismContext prismContext;

    private Map<TriggerHolderSpecification, CreatedTrigger> state = new ConcurrentHashMap<>();

    synchronized CreatedTrigger getLastCreatedTrigger(TriggerHolderSpecification key) {
        return state.get(key);
    }

    synchronized void recordCreatedTrigger(TriggerHolderSpecification key, CreatedTrigger trigger) {
        state.put(key, trigger);
    }

    @Override
    public synchronized void invalidate(Class<?> type, String oid, CacheInvalidationContext context) {
        if (context != null && (context.isTerminateSession() || context.isListUsersSession())) {   // fixme !!!
            return;
        }

        if (oid != null) {
            // We are interested in object deletion events; just to take care of situations when an object is deleted and
            // a new object (of the same name) is created immediately.
            boolean cleanupSpecificEntries = context != null &&
                    context.getDetails() instanceof RepositoryCache.RepositoryCacheInvalidationDetails &&
                    ((RepositoryCache.RepositoryCacheInvalidationDetails) context.getDetails()).getObject() instanceof DeleteObjectResult;

            // We want to remove expired entries in regular intervals. Invalidation event arrival is quite good approximation.
            // However, there's EXPIRATION_INTERVAL present to avoid going through the entries at each invalidation event.
            // (But if we scan the entries for another reason, we take care of expired ones regardless of expiration interval.)
            boolean cleanupExpiredEntries = System.currentTimeMillis() - lastExpirationCleanup.get() >= EXPIRATION_INTERVAL;

            if (cleanupSpecificEntries || cleanupExpiredEntries) {
                int removedMatching = 0;
                int removedExpired = 0;
                long now = System.currentTimeMillis();
                Iterator<Map.Entry<TriggerHolderSpecification, CreatedTrigger>> iterator = state.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<TriggerHolderSpecification, CreatedTrigger> entry = iterator.next();
                    String entryOid = entry.getValue().getHolderOid();
                    if (cleanupSpecificEntries && entryOid.equals(oid)) {
                        iterator.remove();
                        removedMatching++;
                    } else if (entry.getValue().getFireTime() < now) {
                        iterator.remove();
                        removedExpired++;
                    }
                }
                LOGGER.trace("Removed {} entries corresponding to OID={} and {} expired entries",
                        removedMatching, oid, removedExpired);
                lastExpirationCleanup.set(System.currentTimeMillis());
            }
        } else {
            // just an approximation
            int size = state.size();
            state.clear();
            LOGGER.trace("Removed the whole state ({} entries)", size);
            lastExpirationCleanup.set(System.currentTimeMillis());
        }
    }

    @NotNull
    @Override
    public Collection<SingleCacheStateInformationType> getStateInformation() {
        return Collections.singleton(
                new SingleCacheStateInformationType(prismContext)
                        .name(TriggerCreatorGlobalState.class.getName())
                        .size(state.size())
        );
    }

    @PostConstruct
    public void register() {
        cacheRegistry.registerCacheableService(this);
    }

    @PreDestroy
    public void unregister() {
        cacheRegistry.unregisterCacheableService(this);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using BookingApp.Models;
using BookingApp.Providers;
using BookingApp.Results;

namespace BookingApp.Controllers
{
    [Authorize]
    [RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
        private const string LocalLoginProvider = "Local";
        private ApplicationUserManager _userManager;

        private BAContext db = new BAContext();

        public AccountController()
        {
        }

        public AccountController(ApplicationUserManager userManager,
            ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
        {
            UserManager = userManager;
            AccessTokenFormat = accessTokenFormat;
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }

        // GET api/Account/UserInfo
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("UserInfo")]
        public UserInfoViewModel GetUserInfo()
        {
            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            return new UserInfoViewModel
            {
                Email = User.Identity.GetUserName(),
                HasRegistered = externalLogin == null,
                LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
            };
        }

        // POST api/Account/Logout
        [Route("Logout")]
        public IHttpActionResult Logout()
        {
            Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
            return Ok();
        }

        // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true
        [Route("ManageInfo")]
        public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false)
        {
            IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user == null)
            {
                return null;
            }

            List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>();

            foreach (IdentityUserLogin linkedAccount in user.Logins)
            {
                logins.Add(new UserLoginInfoViewModel
                {
                    LoginProvider = linkedAccount.LoginProvider,
                    ProviderKey = linkedAccount.ProviderKey
                });
            }

            if (user.PasswordHash != null)
            {
                logins.Add(new UserLoginInfoViewModel
                {
                    LoginProvider = LocalLoginProvider,
                    ProviderKey = user.UserName,
                });
            }

            return new ManageInfoViewModel
            {
                LocalLoginProvider = LocalLoginProvider,
                Email = user.UserName,
                Logins = logins,
                ExternalLoginProviders = GetExternalLogins(returnUrl, generateState)
            };
        }

        // POST api/Account/ChangePassword
        [Route("ChangePassword")]
        public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
                model.NewPassword);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // POST api/Account/SetPassword
        [Route("SetPassword")]
        public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // POST api/Account/AddExternalLogin
        [Route("AddExternalLogin")]
        public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);

            if (ticket == null || ticket.Identity == null || (ticket.Properties != null
                && ticket.Properties.ExpiresUtc.HasValue
                && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
            {
                return BadRequest("External login failure.");
            }

            ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);

            if (externalData == null)
            {
                return BadRequest("The external login is already associated with an account.");
            }

            IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
                new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // POST api/Account/RemoveLogin
        [Route("RemoveLogin")]
        public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result;

            if (model.LoginProvider == LocalLoginProvider)
            {
                result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
            }
            else
            {
                result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
                    new UserLoginInfo(model.LoginProvider, model.ProviderKey));
            }

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // GET api/Account/ExternalLogin
        [OverrideAuthentication]
        [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
        [AllowAnonymous]
        [Route("ExternalLogin", Name = "ExternalLogin")]
        public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return new ChallengeResult(provider, this);
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return InternalServerError();
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return new ChallengeResult(provider, this);
            }

            BAIdentityUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                 ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                    OAuthDefaults.AuthenticationType);
                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                    CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return Ok();
        }

        // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true
        [AllowAnonymous]
        [Route("ExternalLogins")]
        public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
        {
            IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
            List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();

            string state;

            if (generateState)
            {
                const int strengthInBits = 256;
                state = RandomOAuthStateGenerator.Generate(strengthInBits);
            }
            else
            {
                state = null;
            }

            foreach (AuthenticationDescription description in descriptions)
            {
                ExternalLoginViewModel login = new ExternalLoginViewModel
                {
                    Name = description.Caption,
                    Url = Url.Route("ExternalLogin", new
                    {
                        provider = description.AuthenticationType,
                        response_type = "token",
                        client_id = Startup.PublicClientId,
                        redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
                        state = state
                    }),
                    State = state
                };
                logins.Add(login);
            }

            return logins;
        }

        // POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}

            AppUser appUser = new AppUser() { Username = model.Username };
            db.AppUsers.Add(appUser);
            db.SaveChanges();

            var userStore = new UserStore<BAIdentityUser>(db);
            var userManager = new UserManager<BAIdentityUser>(userStore);

            var user = new BAIdentityUser()
            {
                UserName = model.Username,
                Email = model.Email,
                PasswordHash = BAIdentityUser.HashPassword(model.Password),
                Id = appUser.Id.ToString()
            };

            userManager.Create(user);
            userManager.AddToRole(user.Id, model.Role);

            return Ok();
        }

        // POST api/Account/Register
        //[AllowAnonymous]
        //[Route("Register")]
        //public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return BadRequest(ModelState);
        //    }

        //    var user = new BAIdentityUser() { UserName = model.Email, Email = model.Email };

        //    IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        //    if (!result.Succeeded)
        //    {
        //        return GetErrorResult(result);
        //    }

        //    return Ok();
        //}

        // POST api/Account/RegisterExternal
        [OverrideAuthentication]
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("RegisterExternal")]
        public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var info = await Authentication.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return InternalServerError();
            }

            var user = new BAIdentityUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user);
            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            result = await UserManager.AddLoginAsync(user.Id, info.Login);
            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }
            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && _userManager != null)
            {
                _userManager.Dispose();
                _userManager = null;
            }

            base.Dispose(disposing);
        }

        #region Helpers

        private IAuthenticationManager Authentication
        {
            get { return Request.GetOwinContext().Authentication; }
        }

        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }

                if (ModelState.IsValid)
                {
                    // No ModelState errors are available to send, so just return an empty BadRequest.
                    return BadRequest();
                }

                return BadRequest(ModelState);
            }

            return null;
        }

        private class ExternalLoginData
        {
            public string LoginProvider { get; set; }
            public string ProviderKey { get; set; }
            public string UserName { get; set; }

            public IList<Claim> GetClaims()
            {
                IList<Claim> claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider));

                if (UserName != null)
                {
                    claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider));
                }

                return claims;
            }

            public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
            {
                if (identity == null)
                {
                    return null;
                }

                Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);

                if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)
                    || String.IsNullOrEmpty(providerKeyClaim.Value))
                {
                    return null;
                }

                if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
                {
                    return null;
                }

                return new ExternalLoginData
                {
                    LoginProvider = providerKeyClaim.Issuer,
                    ProviderKey = providerKeyClaim.Value,
                    UserName = identity.FindFirstValue(ClaimTypes.Name)
                };
            }
        }

        private static class RandomOAuthStateGenerator
        {
            private static RandomNumberGenerator _random = new RNGCryptoServiceProvider();

            public static string Generate(int strengthInBits)
            {
                const int bitsPerByte = 8;

                if (strengthInBits % bitsPerByte != 0)
                {
                    throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits");
                }

                int strengthInBytes = strengthInBits / bitsPerByte;

                byte[] data = new byte[strengthInBytes];
                _random.GetBytes(data);
                return HttpServerUtility.UrlTokenEncode(data);
            }
        }

        #endregion
    }
}


text:
import math
import sys

# Make the whole code 3.x.x compatible too...
if sys.version[0]=="3": raw_input=input

# The only _varaibles_ required for this DEMO...
char="*"
x=20
y=19

# A Simple clear screen command for this DEMO...
for n in range(0, 64, 1): print("\r\n")

# This function is just basic for this DEMO but shows the power of the ANSI _Esc_ codes...
def locate(user_string="$VER: Locate_Demo.py_Version_0.00.10_(C)2007-2012_B.Walker_G0LCU.", x=0, y=0):
	# Don't allow any user errors. Python's own error detection will check for
	# syntax and concatination, etc, etc, errors.
	x=int(x)
	y=int(y)
	if x>=255: x=255
	if y>=255: y=255
	if x<=0: x=0
	if y<=0: y=0
	HORIZ=str(x)
	VERT=str(y)
	# Plot the user_string at the starting at position HORIZ, VERT...
	print("\033["+VERT+";"+HORIZ+"f"+user_string)

# Plot the upwards slope of the triangle...
while x<=35:
	locate(char, x, y)
	x=x+1
	y=y-1

# Plot the downwards slope of the triangle...
while x<=52:
	locate(char, x, y)
	x=x+1
	y=y+1

# Plot the base of the triangle...
char="***********************************"
locate(char, 19, 20)

# Write a string inside the triangle...
char="Drawing in text mode Python."
locate(char, 23, 18)

# Print this line BELOW the triangle...
print("\n\n\nCursor now set to the top.")
# NOW reset the cursor back to the top of the window using the default x and y values.
locate("")

# Hold drawing until user input for sine wave plot...
char=raw_input("Press <CR> to continue with a _sine_ wave:- ")

# A Simple clear screen command for this DEMO...
for n in range(0, 64, 1): print("\r\n")

char="*"
x=3
y=12

# Now plot a sinewave curve inside the Terminal.
for angle in range(0, 360, 5):
	# Generate a FLOATING point sine(angle) value...
	angle=float(angle)
	y=math.sin((angle*(math.pi))/180.0)
	# INVERT, AND, keep the y scan inside the standard Terminal window size.
	y=12-(int(y*10))
	locate(char, x, y)
	# Move along one, (1), x position.
	x=x+1

# Hold drawing until user input for a final clear screen...
char=raw_input("\n\n\n\n\n\n\n\n\n\nPress <CR> to clear the screen, display the default string, and stop:- ")

# A Simple clear screen command for this DEMO...
for n in range(0, 64, 1): print("\r\n")

# NOW reset the cursor back to the top of the window using the default x and y values
# and display the locate() function's default string...
locate()

# End of Locate_Demo.py Python code...
# Enjoy finding simple solutions to often very difficult problems...


text:
# golang-instagram

A [instagram](http://instagram.com) [API](http://instagram.com/developer) wrapper.

## Features

Implemented:

- All GET requests are implemented
- Both authenticated and unauthenticated requests can be made
- A nice iterator facility for paginated requests
- No `interface{}` data types! (1 exception, see Location.Id note below)

Todo:

- Authentication
- POST / DELETE requests (you need special permissions for these so no way to test.)

## Documentation

[Documentation on godoc.org](http://godoc.org/github.com/yanatan16/golang-instagram/instagram)

## Install

```
go get github.com/yanatan16/golang-instagram/instagram
```

## Creation

```go
import (
  "github.com/yanatan16/golang-instagram/instagram"
)

unauthenticatedApi := &instagram.Api{
  ClientId: "my-client-id",
}

authenticatedApi := &instagram.Api{
  AccessToken: "my-access-token",
}

- if enforceSigned false
anotherAuthenticatedApi := instagram.New("", "", "my-access-token", false)

- if enforceSigned true
anotherAuthenticatedApi := instagram.New("client_id", "client_secret", "my-access-token", false)

```

## Usage

See the [documentation](http://godoc.org/github.com/yanatan16/golang-instagram/instagram), [endpoint examples](https://github.com/yanatan16/golang-instagram/blob/master/instagram/example_test.go), and the [iteration tests](https://github.com/yanatan16/golang-instagram/blob/master/instagram/iterate_test.go) for a deeper dive than whats below.

```go
import (
  "fmt"
  "github.com/yanatan16/golang-instagram/instagram"
  "net/url"
)

func DoSomeInstagramApiStuff(accessToken string) {
  api := New("", accessToken)

  if ok, err := api.VerifyCredentials(); !ok {
    panic(err)
  }

  var myId string

  // Get yourself!
  if resp, err := api.GetSelf(); err != nil {
    panic(err)
  } else {
    // A response has two fields: Meta which you shouldn't really care about
    // And whatever your getting, in this case, a User
    me := resp.User
    fmt.Printf("My userid is %s and I have %d followers\n", me.Id, me.Counts.FollowedBy)
  }

  params := url.Values{}
  params.Set("count", "1")
  if resp, err := api.GetUserRecentMedia("self" /* this works :) */, params); err != nil {
    panic(err)
  } else {
    if len(resp.Medias) == 0 { // [sic]
      panic("I should have some sort of media posted on instagram!")
    }
    media := resp.Medias[0]
    fmt.Println("My last media was a %s with %d comments and %d likes. (url: %s)\n", media.Type, media.Comments.Count, media.Like.Count, media.Link)
  }
}
```

There's many more endpoints and a fancy iteration wrapper. Check it out in the code and documentation!

## Iteration

So pagination makes iterating through a list of users or media possible, but its not easy. So, because Go has nice iteration facilities (i.e. `range`), this package includes two useful methods for iterating over paginating: `api.IterateMedias` and `api.IterateUsers`. You can see [the tests](https://github.com/yanatan16/golang-instagram/blob/master/instagram/iterate_test.go) and [the docs](http://godoc.org/github.com/yanatan16/golang-instagram/instagram/#Api.IterateMedia) for more info.

```go
// First go and make the original request, passing in any additional parameters you need
res, err := api.GetUserRecentMedia("some-user", params)
if err != nil {
  panic(err)
}

// If you plan to break early, create a done channel. Pass in nil if you plan to exhaust the pagination
done := make(chan bool)
defer close(done)

// Here we get back two channels. Don't worry about the error channel for now
medias, errs := api.IterateMedia(res, done)

for media := range medias {
  processMedia(media)

  if doneWithMedia(media) {
    // This is how we signal to the iterator to quit early
    done <- true
  }
}

// If we exited early due to an error, we can check here
if err, ok := <- errs; ok && err != nil {
  panic(err)
}
```

## Tests

To run the tests, you'll need at least a `ClientId` (which you can get from [here](http://instagram.com/developer/clients/manage/)), and preferably an authenticated users' `AccessToken`, which you can get from making a request on the [API Console](http://instagram.com/developer/api-console/)

First, fill in `config_test.go.example` and save it as `config_test.go`. Then run `go test`

## Notes

- Certain methods require an access token so check the official documentation before using an unauthenticated `Api`. Also, there is a 5000 request per hour rate limit on any one ClientId or AccessToken, so it is advisable to use AccessTokens when available. This package will use it if it is given over a ClientId.
- Location.Id is sometimes returned as an integer (in media i think) and sometimes a string. Because of this, we have to call it an `interface{}`. But there is a facility to force it to a string, as follows:

```go
var loc Location
stringIdVersion := instagram.ParseLocationId(loc.Id)
```

If anyone can prove to me that they fixed this bug, just let me know and we can change it to a string (all other IDs are strings...)

- `created_time` fields come back as strings. So theres a handy type `StringUnixTimeStringUnixTime` which has a nice method `func (sut StringUnixTime) Time() (time.Time, error)` that you can use to cast it to a golang time.
- I apologize for using Medias [sic] everywhere, I needed a plural version that isn't spelled the same.

## License

MIT-style. See LICENSE file.


text:
package com.draagon.meta.loader.simple;

import com.draagon.meta.MetaDataException;
import com.draagon.meta.io.object.xml.XMLObjectReader;
import com.draagon.meta.loader.model.MetaModel;
import com.draagon.meta.loader.model.MetaModelLoader;
import com.draagon.meta.loader.model.MetaModelParser;
import com.draagon.meta.loader.types.TypesConfig;
import com.draagon.meta.loader.uri.URIHelper;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

public class SimpleModelParser extends MetaModelParser<TypesConfig,SimpleLoader,URI> {

    protected SimpleModelParser(MetaModelLoader modelLoader, ClassLoader classLoader, String sourceName) {
        super(modelLoader, classLoader, sourceName);
    }

    @Override
    public void loadAndMerge( SimpleLoader intoLoader, URI uri) {

        InputStream is = null;
        try {
            is = URIHelper.getInputStream( uri );
            //intoLoader.getResourceInputStream(resource);
            loadAndMergeFromStream( intoLoader, is );
        }
        catch( IOException e ) {
            throw new MetaDataException( "Unable to load URI ["+uri+"]: " + e.getMessage(), e );
        }
        finally {
            try {
                if ( is != null ) is.close();
            } catch( IOException e ) {
                throw new MetaDataException( "Unable to close URI ["+uri+"]: " + e.getMessage(), e );
            }
        }
    }

    /* Load MetaDataModel Stream */
    public void loadAndMergeFromStream( SimpleLoader intoLoader, InputStream in ) {

        IOException ioEx = null;

        MetaModel metadata = null;
        XMLObjectReader reader = null;

        try {
            reader = new XMLObjectReader( getLoader(), in );
            metadata = (MetaModel) reader.read( getLoader().getMetaObjectByName(MetaModel.OBJECT_NAME));
        } catch (IOException e) {
            ioEx = e;
        }

        try {
            reader.close();
        } catch (IOException ex) {
            if ( ioEx != null ) ioEx = ex;
        }
        if ( ioEx != null ) throw new MetaDataException( "Error loading MetaData from "+
                "["+getSourcename()+"]: "+ ioEx.toString(), ioEx );

        // Parse MetaData and Construct MetaData types
        mergeMetaDataModel( intoLoader, metadata );
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:background="@drawable/nav_header_background"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textColor="#FDFDFD"
        android:textSize="25sp" />

</LinearLayout>


text:
namespace GitVersionCore.Tests.VersionCalculation
{
    using System;
    using System.Collections.Generic;
    using GitTools;
    using GitTools.Testing;
    using GitVersion;
    using GitVersion.VersionCalculation;
    using LibGit2Sharp;
    using NUnit.Framework;
    using Shouldly;

    public class NextVersionCalculatorTests
    {
        [Test]
        public void ShouldIncrementVersionBasedOnConfig()
        {
            var baseCalculator = new TestBaseVersionCalculator(true, new SemanticVersion(1), new MockCommit());
            var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(1, "master", "b1a34e", DateTimeOffset.Now);
            var sut = new NextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData));
            var config = new Config();
            var context = new GitVersionContextBuilder().WithConfig(config).Build();

            var version = sut.FindVersion(context);

            version.ToString().ShouldBe("1.0.1");
        }

        [Test]
        public void DoesNotIncrementWhenBaseVersionSaysNotTo()
        {
            var baseCalculator = new TestBaseVersionCalculator(false, new SemanticVersion(1), new MockCommit());
            var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(1, "master", "b1a34e", DateTimeOffset.Now);
            var sut = new NextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData));
            var config = new Config();
            var context = new GitVersionContextBuilder().WithConfig(config).Build();

            var version = sut.FindVersion(context);

            version.ToString().ShouldBe("1.0.0");
        }

        [Test]
        public void AppliesBranchPreReleaseTag()
        {
            var baseCalculator = new TestBaseVersionCalculator(false, new SemanticVersion(1), new MockCommit());
            var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(2, "develop", "b1a34e", DateTimeOffset.Now);
            var sut = new NextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData));
            var context = new GitVersionContextBuilder()
                .WithDevelopBranch()
                .Build();

            var version = sut.FindVersion(context);

            version.ToString("f").ShouldBe("1.0.0-alpha.1+2");
        }

        [Test]
        public void PreReleaseTagCanUseBranchName()
        {
            var baseCalculator = new TestBaseVersionCalculator(false, new SemanticVersion(1), new MockCommit());
            var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(2, "develop", "b1a34e", DateTimeOffset.Now);
            var sut = new NextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData));
            var config = new Config();
            config.Branches.Add("custom", new BranchConfig
            {
                Regex = "custom/",
                Tag = "useBranchName"
            });
            var context = new GitVersionContextBuilder()
                .WithConfig(config)
                .WithDevelopBranch()
                .AddBranch("custom/foo")
                .Build();

            var version = sut.FindVersion(context);

            version.ToString("f").ShouldBe("1.0.0-foo.1+2");
        }

        [Test]
        public void PreReleaseTagCanUseBranchNameVariable()
        {
            var baseCalculator = new TestBaseVersionCalculator(false, new SemanticVersion(1), new MockCommit());
            var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(2, "develop", "b1a34e", DateTimeOffset.Now);
            var sut = new NextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData));
            var config = new Config();
            config.Branches.Add("custom", new BranchConfig
            {
                Regex = "custom/",
                Tag = "alpha.{BranchName}"
            });
            var context = new GitVersionContextBuilder()
                .WithConfig(config)
                .WithDevelopBranch()
                .AddBranch("custom/foo")
                .Build();

            var version = sut.FindVersion(context);

            version.ToString("f").ShouldBe("1.0.0-alpha.foo.1+2");
        }

        [Test]
        public void PreReleaseNumberShouldBeScopeToPreReleaseLabelInContinuousDelivery()
        {
            var config = new Config
            {
                VersioningMode = VersioningMode.ContinuousDelivery,
                Branches = new Dictionary<string, BranchConfig>
                {
                    {
                        "master", new BranchConfig()
                        {
                            Tag = "beta"
                        }
                    },
                }
            };

            using (var fixture = new EmptyRepositoryFixture())
            {
                fixture.Repository.MakeACommit();

                fixture.Repository.CreateBranch("feature/test");
                fixture.Repository.Checkout("feature/test");
                fixture.Repository.MakeATaggedCommit("0.1.0-test.1");
                fixture.Repository.MakeACommit();

                fixture.AssertFullSemver(config, "0.1.0-test.2+2");

                fixture.Repository.Checkout("master");
                fixture.Repository.Merge(fixture.Repository.FindBranch("feature/test"), Generate.SignatureNow());

                fixture.AssertFullSemver(config, "0.1.0-beta.1+2");
            }
        }
    }
}


text:
class TileLayer : public Layer {
	private:
	int m_iNbColumns;
	int m_iNbRows;
	int m_iLayerNbColumns;
	int m_iLayerNbRows;
	int m_iTileSize;
	Vector2D m_position;
	Vector2D m_velocity;
	const std::vector<Tileset> &m_vTilesets;
	std::vector<std::vector<int>> m_vTileIDs;

	Tileset _getTilesetByID(int tileID);
	int _getTileId(int x, int y);

	public:
	TileLayer(int tileSize, const std::vector<Tileset> &tilesets);
	virtual void update();
	virtual void render();
	void setTileIDs(const std::vector<std::vector<int>>& data, int width, int height);
	void setTileSize(int tileSize);
};

#endif


text:
<?xml version="1.0" encoding="utf-8"?>

<wicket:panel>

</wicket:panel>


text:
package jef.database.dialect.type;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Types;

import jef.database.jdbc.result.IResultSet;

final class ResultBigDecimalAccessor implements ResultSetAccessor{
	public Object jdbcGet(IResultSet rs,int n) throws SQLException {
		return rs.getBigDecimal(n);
	}

	public Class<?> getReturnType() {
		return BigDecimal.class;
	}

	public boolean applyFor(int type) {
		return Types.DECIMAL == type ||Types.NUMERIC==type;
	}
}


text:
<?xml-stylesheet type="text/xsl" href="/style/testcase.xsl"?>
<t:test xmlns:t="http://xproc.org/ns/testsuite"
      xmlns:p="http://www.w3.org/ns/xproc"
      xmlns:px="http://xproc.dev.java.net/ns/extensions"
      xmlns:c="http://www.w3.org/ns/xproc-step"
      xmlns:err="http://www.w3.org/ns/xproc-error"
      error="err:XC0027">
<t:title>Test for err:XC0027 - 002</t:title>

<t:description xmlns="http://www.w3.org/1999/xhtml">

Tests if dynamic error XC0027 is thrown if the document refers to a DTD that does not exist.

</t:description>

<t:input port="source">
  <doc/>
</t:input>

<t:pipeline>

</t:pipeline>

</t:test>


text:
package test.prefuse.data;

import junit.framework.TestCase;
import prefuse.data.CascadedTable;
import prefuse.data.Table;
import prefuse.data.Tuple;
import prefuse.data.expression.AbstractPredicate;
import prefuse.data.expression.AndPredicate;
import prefuse.data.expression.ArithmeticExpression;
import prefuse.data.expression.ColumnExpression;
import prefuse.data.expression.ComparisonPredicate;
import prefuse.data.expression.Expression;
import prefuse.data.expression.NumericLiteral;
import prefuse.data.expression.Predicate;
import prefuse.data.expression.RangePredicate;
import prefuse.data.io.DelimitedTextTableWriter;
import prefuse.data.util.TableIterator;
import test.prefuse.TestConfig;

public class CascadedTableTest extends TestCase implements TableTestData {

    Table t;

    /**
     * @see junit.framework.TestCase#setUp()
     */
    protected void setUp() throws Exception {
        super.setUp();
        t = TableTest.getTestCaseTable();
    }

    /**
     * @see junit.framework.TestCase#tearDown()
     */
    protected void tearDown() throws Exception {
        super.tearDown();
        t = null;
    }

    public void testCascadedTableRangeFilters() {
        double lo = 1;
        double hi = 20;

        // index the double column
        t.index(HEADERS[4]);

        // where id > 0 && dub > 1 && dub < 20
        ColumnExpression id = new ColumnExpression(HEADERS[0]);
        ColumnExpression dub = new ColumnExpression(HEADERS[4]);
        NumericLiteral x0 = new NumericLiteral(0);
        NumericLiteral xlo = new NumericLiteral(lo);
        NumericLiteral xhi1 = new NumericLiteral(hi-1.0);
        NumericLiteral xhi2 = new NumericLiteral(1.0f);
        Expression xhi = new ArithmeticExpression(
                ArithmeticExpression.ADD, xhi1, xhi2);

        ComparisonPredicate idCmp = new ComparisonPredicate(
                ComparisonPredicate.GTEQ, id, x0);
        RangePredicate dubRg = new RangePredicate(RangePredicate.IN_EX, dub,
                xlo, xhi);
        AndPredicate filter = new AndPredicate(idCmp, dubRg);

        if ( TestConfig.verbose() ) {
            System.out.println(filter.toString());
        }

        CascadedTable ft = new CascadedTable(t, filter);

        TableIterator iter = ft.iterator();
        while ( iter.hasNext() ) {
            int row = iter.nextInt();
            try {
                for (int c = 0; c < NCOLS; ++c) {
                    Object o1 = TABLE[c][ft.getColumnRow(row,c)];
                    Object o2 = ft.get(row,HEADERS[c]);
                    assertEquals(o1, o2);
                }
            } catch (Exception e) {
                fail("Caught exception: " + e);
            }
        }

        // add an extra column to the cascaded table
        String name = "test";
        ft.addColumn(name, double.class, new Double(Math.PI));
        iter = ft.iterator();
        while (iter.hasNext()) {
            int row = iter.nextInt();
            iter.setDouble(name, Math.E);
            assertTrue(Math.E == ft.getDouble(row, name));
        }

        int nr = t.addRow();
        t.setInt(nr, HEADERS[0], nr+1);
        t.setDouble(nr, HEADERS[4], 2.5);

        if ( TestConfig.verbose() ) {
            try {
                new DelimitedTextTableWriter().writeTable(ft, System.out);
            } catch ( Exception e ) { e.printStackTrace(); }
        }
    }

    /*
     * Test method for
     * 'prefuse.data.CascadedTable.CascadedTable(Table,RowFilter)'
     */
    public void testCascadedTableTableRowFilter() {
        final float thresh = 5.0f;

        Predicate p = new AbstractPredicate() {
            public boolean getBoolean(Tuple t) {
                return t.getFloat(HEADERS[3]) < thresh;
            }
        };

        CascadedTable ft = new CascadedTable(t, p);

        for ( int i=0, r=0; i<NROWS; ++i ) {
            float val = ((Float)TABLE[3][i]).floatValue();
            if ( val < thresh ) {
                try {
                    for ( int c=0; c<NCOLS; ++c ) {
                        Object o1 = TABLE[c][i];
                        Object o2 = ft.get(r, HEADERS[c]);
                        assertEquals(o1, o2);
                    }
                    ++r;
                } catch ( Exception e ) {
                    fail("Caught exception: "+e);
                }
            }
        }

        // add an extra column to the cascaded table
        String name = "test";
        ft.addColumn(name, double.class, new Double(Math.PI));
        TableIterator iter = ft.iterator();
        while ( iter.hasNext() ) {
            int row = iter.nextInt();
            iter.setDouble(name, Math.E);
            assertTrue(Math.E == ft.getDouble(row, name));
        }

        int nr = t.addRow();
        t.setFloat(nr, HEADERS[3], 0.5f);
        t.setInt(nr, HEADERS[0], 77);
        nr = t.addRow();
        t.setFloat(nr, HEADERS[3], 0.5f);
        t.setInt(nr, HEADERS[0], 99);

        if ( TestConfig.verbose() ) {
            try {
                new DelimitedTextTableWriter().writeTable(ft, System.out);
            } catch ( Exception e ) { e.printStackTrace(); }
        }
    }

}