text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: android.net.wifi.WifiConfiguration
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ANDROID_NET_WIFI_WIFICONFIGURATION_HPP_DECL
#define J2CPP_ANDROID_NET_WIFI_WIFICONFIGURATION_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace util { class BitSet; } } }
namespace j2cpp { namespace android { namespace os { class Parcel; } } }
namespace j2cpp { namespace android { namespace os { class Parcelable; } } }

#include <android/os/Parcel.hpp>
#include <android/os/Parcelable.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/util/BitSet.hpp>

namespace j2cpp {

namespace android { namespace net { namespace wifi {

	class WifiConfiguration;
	namespace WifiConfiguration_ {

		class Protocol;
		class Protocol
			: public object<Protocol>
		{
		public:

			J2CPP_DECLARE_CLASS

			J2CPP_DECLARE_METHOD(0)
			J2CPP_DECLARE_METHOD(1)
			J2CPP_DECLARE_FIELD(0)
			J2CPP_DECLARE_FIELD(1)
			J2CPP_DECLARE_FIELD(2)
			J2CPP_DECLARE_FIELD(3)

			explicit Protocol(jobject jobj)
			: object<Protocol>(jobj)
			{
			}

			operator local_ref<java::lang::Object>() const;

			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > WPA;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > RSN;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), local_ref< java::lang::String > > varName;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), local_ref< array< local_ref< java::lang::String >, 1> > > strings;
		}; //class Protocol

		class GroupCipher;
		class GroupCipher
			: public object<GroupCipher>
		{
		public:

			J2CPP_DECLARE_CLASS

			J2CPP_DECLARE_METHOD(0)
			J2CPP_DECLARE_METHOD(1)
			J2CPP_DECLARE_FIELD(0)
			J2CPP_DECLARE_FIELD(1)
			J2CPP_DECLARE_FIELD(2)
			J2CPP_DECLARE_FIELD(3)
			J2CPP_DECLARE_FIELD(4)
			J2CPP_DECLARE_FIELD(5)

			explicit GroupCipher(jobject jobj)
			: object<GroupCipher>(jobj)
			{
			}

			operator local_ref<java::lang::Object>() const;

			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > WEP40;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > WEP104;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > TKIP;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jint > CCMP;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), local_ref< java::lang::String > > varName;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), local_ref< array< local_ref< java::lang::String >, 1> > > strings;
		}; //class GroupCipher

		class PairwiseCipher;
		class PairwiseCipher
			: public object<PairwiseCipher>
		{
		public:

			J2CPP_DECLARE_CLASS

			J2CPP_DECLARE_METHOD(0)
			J2CPP_DECLARE_METHOD(1)
			J2CPP_DECLARE_FIELD(0)
			J2CPP_DECLARE_FIELD(1)
			J2CPP_DECLARE_FIELD(2)
			J2CPP_DECLARE_FIELD(3)
			J2CPP_DECLARE_FIELD(4)

			explicit PairwiseCipher(jobject jobj)
			: object<PairwiseCipher>(jobj)
			{
			}

			operator local_ref<java::lang::Object>() const;

			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > NONE;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > TKIP;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > CCMP;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), local_ref< java::lang::String > > varName;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), local_ref< array< local_ref< java::lang::String >, 1> > > strings;
		}; //class PairwiseCipher

		class KeyMgmt;
		class KeyMgmt
			: public object<KeyMgmt>
		{
		public:

			J2CPP_DECLARE_CLASS

			J2CPP_DECLARE_METHOD(0)
			J2CPP_DECLARE_METHOD(1)
			J2CPP_DECLARE_FIELD(0)
			J2CPP_DECLARE_FIELD(1)
			J2CPP_DECLARE_FIELD(2)
			J2CPP_DECLARE_FIELD(3)
			J2CPP_DECLARE_FIELD(4)
			J2CPP_DECLARE_FIELD(5)

			explicit KeyMgmt(jobject jobj)
			: object<KeyMgmt>(jobj)
			{
			}

			operator local_ref<java::lang::Object>() const;

			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > NONE;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > WPA_PSK;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > WPA_EAP;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jint > IEEE8021X;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), local_ref< java::lang::String > > varName;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), local_ref< array< local_ref< java::lang::String >, 1> > > strings;
		}; //class KeyMgmt

		class Status;
		class Status
			: public object<Status>
		{
		public:

			J2CPP_DECLARE_CLASS

			J2CPP_DECLARE_METHOD(0)
			J2CPP_DECLARE_METHOD(1)
			J2CPP_DECLARE_FIELD(0)
			J2CPP_DECLARE_FIELD(1)
			J2CPP_DECLARE_FIELD(2)
			J2CPP_DECLARE_FIELD(3)

			explicit Status(jobject jobj)
			: object<Status>(jobj)
			{
			}

			operator local_ref<java::lang::Object>() const;

			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > CURRENT;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > DISABLED;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > ENABLED;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), local_ref< array< local_ref< java::lang::String >, 1> > > strings;
		}; //class Status

		class AuthAlgorithm;
		class AuthAlgorithm
			: public object<AuthAlgorithm>
		{
		public:

			J2CPP_DECLARE_CLASS

			J2CPP_DECLARE_METHOD(0)
			J2CPP_DECLARE_METHOD(1)
			J2CPP_DECLARE_FIELD(0)
			J2CPP_DECLARE_FIELD(1)
			J2CPP_DECLARE_FIELD(2)
			J2CPP_DECLARE_FIELD(3)
			J2CPP_DECLARE_FIELD(4)

			explicit AuthAlgorithm(jobject jobj)
			: object<AuthAlgorithm>(jobj)
			{
			}

			operator local_ref<java::lang::Object>() const;

			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > OPEN;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > SHARED;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > LEAP;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), local_ref< java::lang::String > > varName;
			static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), local_ref< array< local_ref< java::lang::String >, 1> > > strings;
		}; //class AuthAlgorithm

	} //namespace WifiConfiguration_

	class WifiConfiguration
		: public object<WifiConfiguration>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_FIELD(0)
		J2CPP_DECLARE_FIELD(1)
		J2CPP_DECLARE_FIELD(2)
		J2CPP_DECLARE_FIELD(3)
		J2CPP_DECLARE_FIELD(4)
		J2CPP_DECLARE_FIELD(5)
		J2CPP_DECLARE_FIELD(6)
		J2CPP_DECLARE_FIELD(7)
		J2CPP_DECLARE_FIELD(8)
		J2CPP_DECLARE_FIELD(9)
		J2CPP_DECLARE_FIELD(10)
		J2CPP_DECLARE_FIELD(11)
		J2CPP_DECLARE_FIELD(12)
		J2CPP_DECLARE_FIELD(13)

		typedef WifiConfiguration_::Protocol Protocol;
		typedef WifiConfiguration_::GroupCipher GroupCipher;
		typedef WifiConfiguration_::PairwiseCipher PairwiseCipher;
		typedef WifiConfiguration_::KeyMgmt KeyMgmt;
		typedef WifiConfiguration_::Status Status;
		typedef WifiConfiguration_::AuthAlgorithm AuthAlgorithm;

		explicit WifiConfiguration(jobject jobj)
		: object<WifiConfiguration>(jobj)
		, networkId(jobj)
		, status(jobj)
		, SSID(jobj)
		, BSSID(jobj)
		, preSharedKey(jobj)
		, wepKeys(jobj)
		, wepTxKeyIndex(jobj)
		, priority(jobj)
		, hiddenSSID(jobj)
		, allowedKeyManagement(jobj)
		, allowedProtocols(jobj)
		, allowedAuthAlgorithms(jobj)
		, allowedPairwiseCiphers(jobj)
		, allowedGroupCiphers(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;
		operator local_ref<android::os::Parcelable>() const;

		WifiConfiguration();
		local_ref< java::lang::String > toString();
		jint describeContents();
		void writeToParcel(local_ref< android::os::Parcel >  const&, jint);

		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > networkId;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > status;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), local_ref< java::lang::String > > SSID;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), local_ref< java::lang::String > > BSSID;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), local_ref< java::lang::String > > preSharedKey;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), local_ref< array< local_ref< java::lang::String >, 1> > > wepKeys;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(6), J2CPP_FIELD_SIGNATURE(6), jint > wepTxKeyIndex;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(7), J2CPP_FIELD_SIGNATURE(7), jint > priority;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(8), J2CPP_FIELD_SIGNATURE(8), jboolean > hiddenSSID;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(9), J2CPP_FIELD_SIGNATURE(9), local_ref< java::util::BitSet > > allowedKeyManagement;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(10), J2CPP_FIELD_SIGNATURE(10), local_ref< java::util::BitSet > > allowedProtocols;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(11), J2CPP_FIELD_SIGNATURE(11), local_ref< java::util::BitSet > > allowedAuthAlgorithms;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(12), J2CPP_FIELD_SIGNATURE(12), local_ref< java::util::BitSet > > allowedPairwiseCiphers;
		field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(13), J2CPP_FIELD_SIGNATURE(13), local_ref< java::util::BitSet > > allowedGroupCiphers;
	}; //class WifiConfiguration

} //namespace wifi
} //namespace net
} //namespace android

} //namespace j2cpp

#endif //J2CPP_ANDROID_NET_WIFI_WIFICONFIGURATION_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ANDROID_NET_WIFI_WIFICONFIGURATION_HPP_IMPL
#define J2CPP_ANDROID_NET_WIFI_WIFICONFIGURATION_HPP_IMPL

namespace j2cpp {

android::net::wifi::WifiConfiguration_::Protocol::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

static_field<
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_FIELD_NAME(0),
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_FIELD_SIGNATURE(0),
	jint
> android::net::wifi::WifiConfiguration_::Protocol::WPA;

static_field<
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_FIELD_NAME(1),
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_FIELD_SIGNATURE(1),
	jint
> android::net::wifi::WifiConfiguration_::Protocol::RSN;

static_field<
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_FIELD_NAME(2),
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_FIELD_SIGNATURE(2),
	local_ref< java::lang::String >
> android::net::wifi::WifiConfiguration_::Protocol::varName;

static_field<
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_FIELD_NAME(3),
	android::net::wifi::WifiConfiguration_::Protocol::J2CPP_FIELD_SIGNATURE(3),
	local_ref< array< local_ref< java::lang::String >, 1> >
> android::net::wifi::WifiConfiguration_::Protocol::strings;

J2CPP_DEFINE_CLASS(android::net::wifi::WifiConfiguration_::Protocol,"android/net/wifi/WifiConfiguration$Protocol")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::Protocol,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::Protocol,1,"<clinit>","()V")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::Protocol,0,"WPA","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::Protocol,1,"RSN","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::Protocol,2,"varName","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::Protocol,3,"strings","[java.lang.String")

android::net::wifi::WifiConfiguration_::GroupCipher::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

static_field<
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_NAME(0),
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_SIGNATURE(0),
	jint
> android::net::wifi::WifiConfiguration_::GroupCipher::WEP40;

static_field<
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_NAME(1),
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_SIGNATURE(1),
	jint
> android::net::wifi::WifiConfiguration_::GroupCipher::WEP104;

static_field<
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_NAME(2),
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_SIGNATURE(2),
	jint
> android::net::wifi::WifiConfiguration_::GroupCipher::TKIP;

static_field<
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_NAME(3),
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_SIGNATURE(3),
	jint
> android::net::wifi::WifiConfiguration_::GroupCipher::CCMP;

static_field<
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_NAME(4),
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_SIGNATURE(4),
	local_ref< java::lang::String >
> android::net::wifi::WifiConfiguration_::GroupCipher::varName;

static_field<
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_NAME(5),
	android::net::wifi::WifiConfiguration_::GroupCipher::J2CPP_FIELD_SIGNATURE(5),
	local_ref< array< local_ref< java::lang::String >, 1> >
> android::net::wifi::WifiConfiguration_::GroupCipher::strings;

J2CPP_DEFINE_CLASS(android::net::wifi::WifiConfiguration_::GroupCipher,"android/net/wifi/WifiConfiguration$GroupCipher")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::GroupCipher,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::GroupCipher,1,"<clinit>","()V")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::GroupCipher,0,"WEP40","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::GroupCipher,1,"WEP104","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::GroupCipher,2,"TKIP","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::GroupCipher,3,"CCMP","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::GroupCipher,4,"varName","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::GroupCipher,5,"strings","[java.lang.String")

android::net::wifi::WifiConfiguration_::PairwiseCipher::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

static_field<
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_NAME(0),
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_SIGNATURE(0),
	jint
> android::net::wifi::WifiConfiguration_::PairwiseCipher::NONE;

static_field<
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_NAME(1),
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_SIGNATURE(1),
	jint
> android::net::wifi::WifiConfiguration_::PairwiseCipher::TKIP;

static_field<
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_NAME(2),
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_SIGNATURE(2),
	jint
> android::net::wifi::WifiConfiguration_::PairwiseCipher::CCMP;

static_field<
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_NAME(3),
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_SIGNATURE(3),
	local_ref< java::lang::String >
> android::net::wifi::WifiConfiguration_::PairwiseCipher::varName;

static_field<
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_NAME(4),
	android::net::wifi::WifiConfiguration_::PairwiseCipher::J2CPP_FIELD_SIGNATURE(4),
	local_ref< array< local_ref< java::lang::String >, 1> >
> android::net::wifi::WifiConfiguration_::PairwiseCipher::strings;

J2CPP_DEFINE_CLASS(android::net::wifi::WifiConfiguration_::PairwiseCipher,"android/net/wifi/WifiConfiguration$PairwiseCipher")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::PairwiseCipher,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::PairwiseCipher,1,"<clinit>","()V")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::PairwiseCipher,0,"NONE","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::PairwiseCipher,1,"TKIP","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::PairwiseCipher,2,"CCMP","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::PairwiseCipher,3,"varName","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::PairwiseCipher,4,"strings","[java.lang.String")

android::net::wifi::WifiConfiguration_::KeyMgmt::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

static_field<
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_NAME(0),
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_SIGNATURE(0),
	jint
> android::net::wifi::WifiConfiguration_::KeyMgmt::NONE;

static_field<
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_NAME(1),
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_SIGNATURE(1),
	jint
> android::net::wifi::WifiConfiguration_::KeyMgmt::WPA_PSK;

static_field<
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_NAME(2),
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_SIGNATURE(2),
	jint
> android::net::wifi::WifiConfiguration_::KeyMgmt::WPA_EAP;

static_field<
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_NAME(3),
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_SIGNATURE(3),
	jint
> android::net::wifi::WifiConfiguration_::KeyMgmt::IEEE8021X;

static_field<
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_NAME(4),
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_SIGNATURE(4),
	local_ref< java::lang::String >
> android::net::wifi::WifiConfiguration_::KeyMgmt::varName;

static_field<
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_NAME(5),
	android::net::wifi::WifiConfiguration_::KeyMgmt::J2CPP_FIELD_SIGNATURE(5),
	local_ref< array< local_ref< java::lang::String >, 1> >
> android::net::wifi::WifiConfiguration_::KeyMgmt::strings;

J2CPP_DEFINE_CLASS(android::net::wifi::WifiConfiguration_::KeyMgmt,"android/net/wifi/WifiConfiguration$KeyMgmt")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::KeyMgmt,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::KeyMgmt,1,"<clinit>","()V")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::KeyMgmt,0,"NONE","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::KeyMgmt,1,"WPA_PSK","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::KeyMgmt,2,"WPA_EAP","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::KeyMgmt,3,"IEEE8021X","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::KeyMgmt,4,"varName","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::KeyMgmt,5,"strings","[java.lang.String")

android::net::wifi::WifiConfiguration_::Status::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

static_field<
	android::net::wifi::WifiConfiguration_::Status::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::Status::J2CPP_FIELD_NAME(0),
	android::net::wifi::WifiConfiguration_::Status::J2CPP_FIELD_SIGNATURE(0),
	jint
> android::net::wifi::WifiConfiguration_::Status::CURRENT;

static_field<
	android::net::wifi::WifiConfiguration_::Status::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::Status::J2CPP_FIELD_NAME(1),
	android::net::wifi::WifiConfiguration_::Status::J2CPP_FIELD_SIGNATURE(1),
	jint
> android::net::wifi::WifiConfiguration_::Status::DISABLED;

static_field<
	android::net::wifi::WifiConfiguration_::Status::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::Status::J2CPP_FIELD_NAME(2),
	android::net::wifi::WifiConfiguration_::Status::J2CPP_FIELD_SIGNATURE(2),
	jint
> android::net::wifi::WifiConfiguration_::Status::ENABLED;

static_field<
	android::net::wifi::WifiConfiguration_::Status::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::Status::J2CPP_FIELD_NAME(3),
	android::net::wifi::WifiConfiguration_::Status::J2CPP_FIELD_SIGNATURE(3),
	local_ref< array< local_ref< java::lang::String >, 1> >
> android::net::wifi::WifiConfiguration_::Status::strings;

J2CPP_DEFINE_CLASS(android::net::wifi::WifiConfiguration_::Status,"android/net/wifi/WifiConfiguration$Status")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::Status,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::Status,1,"<clinit>","()V")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::Status,0,"CURRENT","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::Status,1,"DISABLED","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::Status,2,"ENABLED","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::Status,3,"strings","[java.lang.String")

android::net::wifi::WifiConfiguration_::AuthAlgorithm::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

static_field<
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_NAME(0),
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_SIGNATURE(0),
	jint
> android::net::wifi::WifiConfiguration_::AuthAlgorithm::OPEN;

static_field<
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_NAME(1),
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_SIGNATURE(1),
	jint
> android::net::wifi::WifiConfiguration_::AuthAlgorithm::SHARED;

static_field<
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_NAME(2),
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_SIGNATURE(2),
	jint
> android::net::wifi::WifiConfiguration_::AuthAlgorithm::LEAP;

static_field<
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_NAME(3),
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_SIGNATURE(3),
	local_ref< java::lang::String >
> android::net::wifi::WifiConfiguration_::AuthAlgorithm::varName;

static_field<
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_CLASS_NAME,
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_NAME(4),
	android::net::wifi::WifiConfiguration_::AuthAlgorithm::J2CPP_FIELD_SIGNATURE(4),
	local_ref< array< local_ref< java::lang::String >, 1> >
> android::net::wifi::WifiConfiguration_::AuthAlgorithm::strings;

J2CPP_DEFINE_CLASS(android::net::wifi::WifiConfiguration_::AuthAlgorithm,"android/net/wifi/WifiConfiguration$AuthAlgorithm")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::AuthAlgorithm,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration_::AuthAlgorithm,1,"<clinit>","()V")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::AuthAlgorithm,0,"OPEN","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::AuthAlgorithm,1,"SHARED","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::AuthAlgorithm,2,"LEAP","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::AuthAlgorithm,3,"varName","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration_::AuthAlgorithm,4,"strings","[java.lang.String")

android::net::wifi::WifiConfiguration::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

android::net::wifi::WifiConfiguration::operator local_ref<android::os::Parcelable>() const
{
	return local_ref<android::os::Parcelable>(get_jobject());
}

android::net::wifi::WifiConfiguration::WifiConfiguration()
: object<android::net::wifi::WifiConfiguration>(
	call_new_object<
		android::net::wifi::WifiConfiguration::J2CPP_CLASS_NAME,
		android::net::wifi::WifiConfiguration::J2CPP_METHOD_NAME(0),
		android::net::wifi::WifiConfiguration::J2CPP_METHOD_SIGNATURE(0)
	>()
)
, networkId(get_jobject())
, status(get_jobject())
, SSID(get_jobject())
, BSSID(get_jobject())
, preSharedKey(get_jobject())
, wepKeys(get_jobject())
, wepTxKeyIndex(get_jobject())
, priority(get_jobject())
, hiddenSSID(get_jobject())
, allowedKeyManagement(get_jobject())
, allowedProtocols(get_jobject())
, allowedAuthAlgorithms(get_jobject())
, allowedPairwiseCiphers(get_jobject())
, allowedGroupCiphers(get_jobject())
{
}

local_ref< java::lang::String > android::net::wifi::WifiConfiguration::toString()
{
	return call_method<
		android::net::wifi::WifiConfiguration::J2CPP_CLASS_NAME,
		android::net::wifi::WifiConfiguration::J2CPP_METHOD_NAME(1),
		android::net::wifi::WifiConfiguration::J2CPP_METHOD_SIGNATURE(1),
		local_ref< java::lang::String >
	>(get_jobject());
}

jint android::net::wifi::WifiConfiguration::describeContents()
{
	return call_method<
		android::net::wifi::WifiConfiguration::J2CPP_CLASS_NAME,
		android::net::wifi::WifiConfiguration::J2CPP_METHOD_NAME(2),
		android::net::wifi::WifiConfiguration::J2CPP_METHOD_SIGNATURE(2),
		jint
	>(get_jobject());
}

void android::net::wifi::WifiConfiguration::writeToParcel(local_ref< android::os::Parcel > const &a0, jint a1)
{
	return call_method<
		android::net::wifi::WifiConfiguration::J2CPP_CLASS_NAME,
		android::net::wifi::WifiConfiguration::J2CPP_METHOD_NAME(3),
		android::net::wifi::WifiConfiguration::J2CPP_METHOD_SIGNATURE(3),
		void
	>(get_jobject(), a0, a1);
}

J2CPP_DEFINE_CLASS(android::net::wifi::WifiConfiguration,"android/net/wifi/WifiConfiguration")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration,1,"toString","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration,2,"describeContents","()I")
J2CPP_DEFINE_METHOD(android::net::wifi::WifiConfiguration,3,"writeToParcel","(Landroid/os/Parcel;I)V")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,0,"networkId","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,1,"status","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,2,"SSID","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,3,"BSSID","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,4,"preSharedKey","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,5,"wepKeys","[java.lang.String")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,6,"wepTxKeyIndex","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,7,"priority","I")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,8,"hiddenSSID","Z")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,9,"allowedKeyManagement","Ljava/util/BitSet;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,10,"allowedProtocols","Ljava/util/BitSet;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,11,"allowedAuthAlgorithms","Ljava/util/BitSet;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,12,"allowedPairwiseCiphers","Ljava/util/BitSet;")
J2CPP_DEFINE_FIELD(android::net::wifi::WifiConfiguration,13,"allowedGroupCiphers","Ljava/util/BitSet;")

} //namespace j2cpp

#endif //J2CPP_ANDROID_NET_WIFI_WIFICONFIGURATION_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
using NUnit.Framework;
using osu.Game.Tests.Visual;

namespace osu.Game.Rulesets.Catch.Tests.Editor
{
    [TestFixture]
    public class TestSceneEditor : EditorTestScene
    {
        protected override Ruleset CreateEditorRuleset() => new CatchRuleset();
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'coveralls'
Coveralls.wear!

require 'faststrap'


text:
<?php

namespace ChargeBee\ChargeBee\Models;

use ChargeBee\ChargeBee\Model;

class CustomerChildAccountAccess extends Model
{
  protected $allowed = [
    'portalEditSubscriptions',
    'portalDownloadInvoices',
    'sendSubscriptionEmails',
    'sendInvoiceEmails',
    'sendPaymentEmails',
  ];

}

?>


text:
from __future__ import absolute_import

import os
from datetime import datetime
from itertools import product

import mock
import pytest
from alembic.command import upgrade
from alembic.config import Config
from flask_migrate import Migrate
from sqlalchemy import inspect

from app import create_app
from app.models import (
    db, Framework, SupplierFramework, Supplier, User, ContactInformation, DraftService, Lot, Service, FrameworkLot
)
from app.main.views.frameworks import FRAMEWORK_UPDATE_WHITELISTED_ATTRIBUTES_MAP

@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
    print("Doing db setup")
    app_env_var_mock = mock.patch.dict('gds_metrics.os.environ', {'PROMETHEUS_METRICS_PATH': '/_metrics'})
    app_env_var_mock.start()
    app = create_app('test')
    Migrate(app, db)
    ALEMBIC_CONFIG = os.path.join(os.path.dirname(__file__), '../migrations/alembic.ini')
    config = Config(ALEMBIC_CONFIG)
    config.set_main_option("script_location", "migrations")

    with app.app_context():
        upgrade(config, 'head')

    print("Done db setup")

    def teardown():
        app = create_app('test')
        with app.app_context():
            db.session.remove()
            db.engine.execute("drop sequence suppliers_supplier_id_seq cascade")
            db.drop_all()
            db.engine.execute("drop table alembic_version")
            insp = inspect(db.engine)
            for enum in insp.get_enums():
                db.Enum(name=enum['name']).drop(db.engine)
            db.get_engine(app).dispose()
            app_env_var_mock.stop()
    request.addfinalizer(teardown)

@pytest.fixture(scope='session')
def app(request):
    return create_app('test')

@pytest.fixture(params=[{}])
def draft_service(request, app, supplier_framework):
    with app.app_context():
        supplier_id = Supplier.query.filter(Supplier.supplier_id == supplier_framework['supplierId']).first()
        framework = Framework.query.filter(Framework.slug == supplier_framework['frameworkSlug']).first()
        lot = Lot.query.filter(Lot.slug == 'digital-specialists').first()
        fl_query = {
            'framework_id': framework.id,
            'lot_id': lot.id
        }
        fl = FrameworkLot(**fl_query)

        ds = DraftService(
            framework=framework,
            lot=lot,
            service_id="1234567890",
            supplier=supplier_id,
            data={},
            status='submitted',
            updated_at=datetime.now(),
            created_at=datetime.now(),
            lot_one_service_limit=lot.one_service_limit,
        )
        db.session.add(fl)
        db.session.add(ds)
        db.session.commit()

        def teardown():
            with app.app_context():
                FrameworkLot.query.filter(
                    *[getattr(FrameworkLot, k) == v for k, v in fl_query.items()]
                ).delete(synchronize_session=False)
                Service.query.filter(Service.service_id == ds.service_id).delete(synchronize_session=False)
                DraftService.query.filter(DraftService.service_id == ds.service_id).delete(synchronize_session=False)
                db.session.commit()

        request.addfinalizer(teardown)

        with mock.patch('app.models.main.url_for', autospec=lambda i, **values: 'test.url/test'):
            Service.create_from_draft(ds, 'enabled')
            return ds.serialize()

@pytest.fixture(params=[{'supplier_id': None}])
def supplier(request, app):
    with app.app_context():
        s = Supplier(
            supplier_id=request.param['supplier_id'],
            name=u"Supplier name",
            description=""
        )
        db.session.add(s)
        db.session.commit()

        return {'id': s.supplier_id}

@pytest.fixture(params=[{'on_framework': True}])
def supplier_framework(request, app, supplier, live_example_framework):
    with app.app_context():
        sf = SupplierFramework(
            supplier_id=supplier['id'],
            framework_id=live_example_framework['id'],
            **request.param
        )
        db.session.add(sf)
        db.session.commit()

        return sf.serialize()

_framework_kwargs_whitelist = set(FRAMEWORK_UPDATE_WHITELISTED_ATTRIBUTES_MAP.values()).union({'framework'})

def _update_framework(request, app, slug, **kwargs):
    if not kwargs:
        # request doesn't really care about any more specific properties of the Framework. nothing for us
        # to do.
        return

    # first whitelist the kwargs to limit what we have to worry about
    kwargs = {k: v for k, v in kwargs.items() if k in _framework_kwargs_whitelist}

    framework = Framework.query.filter(
        Framework.slug == slug
    ).first()
    original_values = {k: getattr(framework, k) for k in kwargs.keys()}
    for k, v in kwargs.items():
        setattr(framework, k, v)

    db.session.add(framework)
    db.session.commit()

    def teardown():
        with app.app_context():
            framework = Framework.query.filter(
                Framework.slug == slug
            ).first()
            for k, v in original_values.items():
                setattr(framework, k, v)

            db.session.add(framework)
            db.session.commit()

    request.addfinalizer(teardown)
    return framework.serialize()

def _add_framework(request, app, slug, **kwargs):
    # first whitelist the kwargs to limit what we have to worry about
    kwargs = {k: v for k, v in kwargs.items() if k in _framework_kwargs_whitelist}
    if "status" in kwargs and "clarification_questions_open" not in kwargs:
        kwargs["clarification_questions_open"] = (kwargs["status"] == "open")

    framework = Framework(slug=slug, name=slug, **kwargs)
    db.session.add(framework)
    db.session.commit()

    def teardown():
        with app.app_context():
            FrameworkLot.query.filter(FrameworkLot.framework_id == framework.id).delete()
            Framework.query.filter(Framework.id == framework.id).delete()
            db.session.commit()

    request.addfinalizer(teardown)
    return framework.serialize()

def _add_lots_for_framework(request, app, framework_slug, lot_slugs):
    for lot_slug in lot_slugs:
        _add_lot_for_framework(request, app, framework_slug, lot_slug)

def _add_lot_for_framework(request, app, framework_slug, lot_slug):
    with app.app_context():
        framework = Framework.query.filter(Framework.slug == framework_slug).first()
        lot = Lot.query.filter(Lot.slug == lot_slug).first()
        existing_framework_lot = FrameworkLot.query.filter(
            FrameworkLot.framework_id == framework.id, FrameworkLot.lot_id == lot.id
        ).first()
        if not existing_framework_lot:
            framework_lot = FrameworkLot(framework_id=framework.id, lot_id=lot.id)
            db.session.add(framework_lot)
            db.session.commit()
            return framework_lot

def _framework_fixture_inner(request, app, slug, **kwargs):
    with app.app_context():
        # we have to do a switch between two implementations here as in some cases a matching Framework
        # may already be in the database (e.g. Frameworks that were inserted by migrations)
        inner_func = (
            _update_framework if Framework.query.filter(Framework.slug == slug).first() else _add_framework
        )
        return inner_func(request, app, slug, **kwargs)

_generic_framework_agreement_details = {"frameworkAgreementVersion": "v1.0"}

_g8_framework_defaults = {
    "slug": "g-cloud-8",
    "framework": "g-cloud",
    "framework_agreement_details": _generic_framework_agreement_details,
    "applications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "intention_to_award_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_publish_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_live_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_expires_at_utc": "2000-01-01T00:00:00.000000Z",
    "has_direct_award": True,
    "has_further_competition": False,
}
_g7_framework_defaults = {
    "slug": "g-cloud-7",
    "framework": "g-cloud",
    "framework_agreement_details": None,
    "applications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "intention_to_award_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_publish_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_live_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_expires_at_utc": "2000-01-01T00:00:00.000000Z",
    "has_direct_award": True,
    "has_further_competition": False,
}
_g6_framework_defaults = {
    "slug": "g-cloud-6",
    "framework": "g-cloud",
    "framework_agreement_details": None,
    "applications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "intention_to_award_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_publish_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_live_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_expires_at_utc": "2000-01-01T00:00:00.000000Z",
    "has_direct_award": True,
    "has_further_competition": False,
}
_dos_framework_defaults = {
    "slug": "digital-outcomes-and-specialists",
    "framework": "digital-outcomes-and-specialists",
    "framework_agreement_details": None,
    "applications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "intention_to_award_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_publish_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_live_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_expires_at_utc": "2000-01-01T00:00:00.000000Z",
    "has_direct_award": False,
    "has_further_competition": True,
}
_dos2_framework_defaults = {
    "slug": "digital-outcomes-and-specialists-2",
    "framework": "digital-outcomes-and-specialists",
    "framework_agreement_details": None,
    "applications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "intention_to_award_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_publish_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_live_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_expires_at_utc": "2000-01-01T00:00:00.000000Z",
    "has_direct_award": False,
    "has_further_competition": True,
}
_example_framework_details = {
    "slug": "example-framework",
    "framework": "g-cloud",
    "framework_agreement_details": None,
    "applications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "intention_to_award_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_close_at_utc": "2000-01-01T00:00:00.000000Z",
    "clarifications_publish_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_live_at_utc": "2000-01-01T00:00:00.000000Z",
    "framework_expires_at_utc": "2000-01-01T00:00:00.000000Z",
    "has_direct_award": True,
    "has_further_competition": False,
}
_dos_framework_lots = ["digital-specialists", "digital-outcomes", "user-research-participants", "user-research-studios"]

def _supplierframework_fixture_inner(request, app, sf_kwargs=None):
    """
        if @sf_kwargs is a callable, it will be called with each supplier, framework combination as arguments to
        generate the kwargs for each SupplierFramework. a returned value of None will prevent that SupplierFramework
        being created.
    """
    sf_kwargs = sf_kwargs or {}
    supplier_framework_id_pairs = set()
    with app.app_context():
        for supplier, framework in product(Supplier.query.all(), Framework.query.all()):
            kwargs = sf_kwargs(supplier, framework) if callable(sf_kwargs) else sf_kwargs
            if kwargs is not None:
                supplier_framework = SupplierFramework(
                    supplier=supplier,
                    framework=framework,
                    **kwargs
                )
                supplier_framework_id_pairs.add((supplier.supplier_id, framework.id,))
                db.session.add(supplier_framework)

        db.session.commit()

    def teardown():
        with app.app_context():
            for supplier_id, framework_id in supplier_framework_id_pairs:
                SupplierFramework.query.filter(
                    SupplierFramework.supplier_id == supplier_id,
                    SupplierFramework.framework_id == framework_id,
                ).delete()
            db.session.commit()

    request.addfinalizer(teardown)

def _supplier_fixture_inner(request, app, supplier_kwargs=None, ci_kwargs=None):
    supplier_kwargs = supplier_kwargs or {}
    supplier_kwargs = dict({
        "name": "Supplier {}".format(supplier_kwargs.get("supplier_id", "")),
        "description": "some description",
    }, **supplier_kwargs)

    with app.app_context():
        supplier = Supplier(**supplier_kwargs)
        db.session.add(supplier)
        db.session.flush()

        ci_kwargs = ci_kwargs or {}
        ci_kwargs = dict({
            "contact_name": "Contact for supplier {}".format(supplier.supplier_id),
            "email": "{}@contact.com".format(supplier.supplier_id),
            "postcode": "SW1A 1AA",
            "supplier_id": supplier.supplier_id,
        }, **ci_kwargs)

        contact_information = ContactInformation(**ci_kwargs)
        db.session.add(contact_information)

        db.session.commit()

        supplier_id = supplier.supplier_id
        contact_information_id = contact_information.id

    def teardown():
        with app.app_context():
            ContactInformation.query.filter(ContactInformation.id == contact_information_id).delete()
            Supplier.query.filter(Supplier.supplier_id == supplier_id).delete()
            db.session.commit()

    request.addfinalizer(teardown)
    return supplier_id

def _user_fixture_inner(request, app, user_kwargs=None):
    user_kwargs = user_kwargs or {}
    user_kwargs = dict({
        "email_address": "test+{}@digital.gov.uk".format(user_kwargs.get("id", "replaceme")),
        "active": True,
        "password": "fake password",
        "password_changed_at": datetime.now(),
        "name": "my name",
    }, **user_kwargs)

    with app.app_context():
        user = User(**user_kwargs)
        db.session.add(user)
        db.session.commit()

        # if we didn't know the user id at insert time and didn't have an email we should replace it now
        # so we don't end up with collisions
        if user.email_address == "test+replaceme@digital.gov.uk":
            user.email_address = "test+{}@digital.gov.uk".format(user.id)
            db.session.add(user)
            db.session.commit()

        user_id = user.id

    def teardown():
        with app.app_context():
            User.query.filter(User.id == user_id).delete()
            db.session.commit()

    request.addfinalizer(teardown)
    return user_id

# Frameworks

@pytest.fixture()
def open_example_framework(request, app):
    return _framework_fixture_inner(request, app, **dict(_example_framework_details, status="open"))

@pytest.fixture(params=[{}])
def live_example_framework(request, app):
    return _framework_fixture_inner(request, app, **dict(_example_framework_details, status="live", **request.param))

@pytest.fixture()
def open_g8_framework(request, app):
    return _framework_fixture_inner(request, app, **dict(_g8_framework_defaults, status="open"))

@pytest.fixture()
def live_g8_framework(request, app):
    return _framework_fixture_inner(request, app, **dict(_g8_framework_defaults, status="live"))

@pytest.fixture()
def live_g8_framework_2_variations(request, app):
    _framework_fixture_inner(request, app, **dict(
        _g8_framework_defaults,
        status="live",
        framework_agreement_details=dict(_generic_framework_agreement_details, variations={
            "banana": {
                "createdAt": "2016-06-06T20:01:34.000000Z",
            },
            "toblerone": {
                "createdAt": "2016-07-06T21:09:09.000000Z",
            },
        }),
    ))

@pytest.fixture()
def open_g6_framework(request, app):
    return _framework_fixture_inner(request, app, **dict(_g6_framework_defaults, status="open"))

@pytest.fixture()
def expired_g6_framework(request, app):
    return _framework_fixture_inner(request, app, **dict(_g6_framework_defaults, status="expired"))

@pytest.fixture()
def open_dos_framework(request, app):
    fw = _framework_fixture_inner(request, app, **dict(_dos_framework_defaults, status="open"))
    _add_lots_for_framework(request, app, _dos_framework_defaults["slug"], _dos_framework_lots)
    return fw

@pytest.fixture()
def live_dos_framework(request, app):
    fw = _framework_fixture_inner(request, app, **dict(_dos_framework_defaults, status="live"))
    _add_lots_for_framework(request, app, _dos_framework_defaults["slug"], _dos_framework_lots)
    return fw

@pytest.fixture()
def live_reusable_dos_framework(request, app):
    fw = _framework_fixture_inner(request, app, **dict(
        _dos_framework_defaults,
        status="live",
        allow_declaration_reuse=True,
    ))
    _add_lots_for_framework(request, app, _dos_framework_defaults["slug"], _dos_framework_lots)
    return fw

@pytest.fixture()
def expired_dos_framework(request, app):
    fw = _framework_fixture_inner(request, app, **dict(_dos_framework_defaults, status="expired"))
    _add_lots_for_framework(request, app, _dos_framework_defaults["slug"], _dos_framework_lots)
    return fw

@pytest.fixture()
def live_dos2_framework(request, app):
    fw = _framework_fixture_inner(request, app, **dict(_dos2_framework_defaults, status="live"))
    _add_lots_for_framework(request, app, _dos2_framework_defaults["slug"], _dos_framework_lots)
    return fw

# Suppliers

@pytest.fixture()
def supplier_basic(request, app):
    return _supplier_fixture_inner(request, app, supplier_kwargs={"supplier_id": 1})

@pytest.fixture()
def supplier_basic_alt(request, app):
    return _supplier_fixture_inner(request, app, supplier_kwargs={"supplier_id": 2})

# Users

@pytest.fixture()
def user_role_supplier(request, app, supplier_basic):
    return _user_fixture_inner(request, app, user_kwargs={
        "id": 1,
        "role": "supplier",
        "supplier_id": supplier_basic,
    })

@pytest.fixture()
def user_role_supplier_alt(request, app, supplier_basic_alt):
    return _user_fixture_inner(request, app, user_kwargs={
        "id": 2,
        "role": "supplier",
        "supplier_id": supplier_basic_alt,
    })

# Frameworks & Suppliers with some SupplierFrameworks setup

@pytest.fixture()
def live_g8_framework_2_variations_suppliers_not_on_framework(
        request,
        app,
        live_g8_framework_2_variations,
        user_role_supplier,
):
    _supplierframework_fixture_inner(request, app)

@pytest.fixture()
def live_g8_framework_2_variations_suppliers_on_framework(
        request,
        app,
        live_g8_framework_2_variations,
        user_role_supplier,
):
    _supplierframework_fixture_inner(request, app, sf_kwargs={"on_framework": True})

@pytest.fixture()
def live_g8_framework_2_variations_suppliers_on_framework_with_alt(
        request,
        app,
        live_g8_framework_2_variations,
        user_role_supplier,
        user_role_supplier_alt,
):
    _supplierframework_fixture_inner(request, app, sf_kwargs={"on_framework": True})

@pytest.fixture()
def live_g8_framework_suppliers_on_framework(
        request,
        app,
        live_g8_framework,
        user_role_supplier,
):
    _supplierframework_fixture_inner(request, app, sf_kwargs={"on_framework": True})

@pytest.fixture()
def open_g8_framework_live_reusable_dos_framework_suppliers_on_live_framework(
        request,
        app,
        open_g8_framework,
        live_reusable_dos_framework,
        user_role_supplier,
):
    _supplierframework_fixture_inner(request, app, sf_kwargs=lambda supplier, framework: {
        "on_framework": framework.status == "live",
    })

@pytest.fixture()
def open_g8_framework_live_reusable_dos_framework_suppliers_g8_sf(
        request,
        app,
        open_g8_framework,
        live_reusable_dos_framework,
        user_role_supplier,
):
    _supplierframework_fixture_inner(request, app, sf_kwargs=(
        lambda supplier, framework: None if framework.slug == "digital-outcomes-and-specialists" else {}
    ))


text:
var initDrawer = function initDrawer() {
  var data = {
    color: 'aliceBlue',
    shapes: {},
    currentShape: null,
    newShapes: [],
    modifiedShape: null,
    remoteShapes: []
  };

  var ShapeTypes = {line: 'line', path: 'path', rect: 'rect', circle: 'circle'};
  var LineTypes = {round: 'round'};
  var Colors = {black: 'black', red: 'red', blue: 'blue', green: 'green', purple: 'purple', yellow: 'yellow', white: 'white', aliceblue: 'aliceblue'};

  //returns 4 digit guid string
  var getGuid = function getGuid() {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    var codes = [0, 0, 0, 0];

    codes = codes.map(function (code) {
      return chars[Math.floor(Math.random() * chars.length)];
    });

    return codes.join('');
  };

  class Point {
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }
  }

  class Shape {
    constructor(type, points, strokeColor, fillColor) {
      this.type = type;
      this.points = points;
      this.radius = 0;
      this.lineWidth = 2;
      this.lineJoin = LineTypes.round;
      this.lineCap = LineTypes.round;
      this.strokeColor = strokeColor;
      this.fillColor = fillColor;
      this.guid = getGuid();
    }
  }

  class Drawer {

    constructor(canvas, data) {
      this.canvas = canvas;
      // this.shapes = shapes;
      this.data = data;
      data = this.data;
      this.isDrawing = false;
      this.currentShapeType = ShapeTypes.path;
      this.isSelecting = false;
      this.ShapeTypes = ShapeTypes;
      this.LineTypes = LineTypes;
      this.Colors = Colors;
      this.fillColor = null;
      this.strokeColor = Colors.red;
      this.colorStroke = 'stroke';
      // keep this last so state is setup to hanlde drawing
      this.addListeners();
    }

    changeShapeType(type) {
      if (this.isSelecting) {
        this.toggleIsSelecting();
      }

      this.currentShapeType = type;
    }

    toggleStrokeFill(type) {
      this.colorStroke = type;
      this.changeColor(this.strokeColor || this.fillColor);
    }

    changeColor(color) {
      if (this.colorStroke === 'stroke') {
        this.strokeColor = color;
        this.fillColor = null;
      } else {
        this.fillColor = color;
        this.strokeColor = null;
      }
    }

    enableIsSelecting() {
      this.isSelecting = true;
      this.canvas.style.cursor = 'pointer';
    }

    disableIsSelecting() {
      this.isSelecting = false;
      this.canvas.style.cursor = 'default';
    }

    toggleIsSelecting() {
      if (this.isSelecting) {
        this.disableIsSelecting();
      } else {
        this.enableIsSelecting();
      }
    }

    getSelectedShape(mousePoint) {
      var selectedShape = null;

      for (var key in this.data.shapes) {
        var shape = this.data.shapes[key];
        var test = false;

        if (shape.type === ShapeTypes.rect && shape.points.length > 1) {
          var p1 = shape.points[0];
          var p2 = shape.points[1];

          if (mousePoint.x > p1.x && mousePoint.x < p2.x || mousePoint.x < p1.x && mousePoint.x > p2.x) {
            if (mousePoint.y > p1.y && mousePoint.y < p2.y || mousePoint.y < p1.y && mousePoint.y > p2.y) {
              test = true;
            }
          }

        } else if (shape.type === ShapeTypes.circle) {
          // pythagorean theorem
          var center = shape.points[0];
          var a = mousePoint.x - center.x;
          var b = mousePoint.y - center.y;
          var hyp = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
          test = hyp < shape.radius;
        }

        if (test) {
          selectedShape = shape;

          if (selectedShape.type === ShapeTypes.circle) {
            selectedShape.offsetX = a;
            selectedShape.offsetY = b;
          }
          if (selectedShape.type === ShapeTypes.rect) {
            selectedShape.offsetX = mousePoint.x - p1.x;
            selectedShape.offsetY = mousePoint.y - p1.y;
          }

          break;
        }
      }

      this.data.modifiedShape = selectedShape;
    }

    moveSelectedShape(mousePoint) {
      var shape = this.data.modifiedShape;

      if (!shape) {
        return;
      }

      if (shape.type === ShapeTypes.rect) {
        var p1 = shape.points[0];
        var p2 = shape.points[1];
        var width = p2.x - p1.x;
        var height = p2.y - p1.y;

        p1.x = mousePoint.x - shape.offsetX;
        p1.y = mousePoint.y - shape.offsetY;
        p2.x = p1.x + width;
        p2.y = p1.y + height;
      } else if (shape.type === ShapeTypes.circle) {
        shape.points[0].x = mousePoint.x - shape.offsetX;
        shape.points[0].y = mousePoint.y - shape.offsetY;
      }
    }

    // mouse events & helpers ###########

    getMousePoint(e) {
      var rect = this.canvas.getBoundingClientRect();
      // get the mouse point and remove offset of canvas in window
      var x = (e.clientX - rect.left) / (rect.right - rect.left) * this.canvas.width;
      var y = (e.clientY - rect.top) / (rect.bottom - rect.top) * this.canvas.height;
      return new Point(x, y);
    }

    handleMouseUp(e) {
      this.isDrawing = false;

      if (this.isSelecting) {
        if (this.data.modifiedShape) {
          this.data.modifiedShape.done = true;
        }
        return;
      }

      var shape = this.data.currentShape;

      if (!shape) {
        return;
      }

      if (shape && (shape.mode === ShapeTypes.rect || shape.mode === ShapeTypes.line)) {
        if (shape.points.length > 1) {
          shape.points.pop();
        }
        var point = this.getMousePoint(e);
        shape.points.push(point);
      }

      shape.done = true;
      this.data.newShapes.push(shape);
      // this.data.currentShape = null;

      console.log('SHAPE COUNT: ', this.data.newShapes.length);
    }

    handleMouseDown(e) {
      this.isDrawing = true;
      var mousePoint = this.getMousePoint(e);

      // if we are selecting
      if (this.isSelecting) {
        this.getSelectedShape(mousePoint);
        return;
      }

      var points = [mousePoint];
      this.data.currentShape = new Shape(this.currentShapeType, points,
        this.strokeColor, this.fillColor);

      // this.shapes.push(this.currentShape);
    }

    handleMouseMove(e) {

      if (!this.isDrawing) { return; }
      var mousePoint = this.getMousePoint(e);
      var shape = this.data.currentShape;

      if (this.isSelecting) {
        this.moveSelectedShape(mousePoint);
        return;
      }

      if (shape.type === ShapeTypes.path) {
        // paths get every point of move
        shape.points.push(mousePoint);
      } else if (shape.type === ShapeTypes.rect) {
        // rect's only have 2 points max
        if (shape.points.length > 1) {
          shape.points.pop();
        }

        shape.points.push(mousePoint);
      } else if (shape.type === ShapeTypes.circle) {
        // circles have one center point and a radius
        var center = shape.points[0];
        var distX = mousePoint.x - center.x;
        var distY = mousePoint.y - center.y;
        shape.radius = Math.abs(distX > distY ? distX : distY);
      } else if (shape.type === ShapeTypes.line) {
        // lines have 2 points max
        if (shape.points.length > 1) {
          shape.points.pop();
        }

        shape.points.push(mousePoint);
      }
    }

    addListeners() {
      this.canvas.addEventListener('mousedown',
        this.handleMouseDown.bind(this));
      this.canvas.addEventListener('mouseup',
        this.handleMouseUp.bind(this));
      this.canvas.addEventListener('mouseout',
        this.handleMouseUp.bind(this));
      this.canvas.addEventListener('mousemove',
        this.handleMouseMove.bind(this));
    }
  }

  var canvas = document.getElementById('draw-canvas');

  return new Drawer(canvas, data);
};

export default initDrawer;


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Hay dos servidores involucrados en el envío de un mensaje: tu servidor y un servidor de mensajería de terceros. Tú llevas registro de los destinatarios de tus mensajes. El servidor de terceros controla las rutas.

{# wf_updated_on: 2017-07-12 #}
{# wf_published_on: 2016-06-30 #}

# Enviar mensajes {: .page-title }

{% include "web/_shared/contributors/josephmedley.html" %}

Realmente hay dos servidores involucrados en el envío de un mensaje: tu servidor
y un servidor de mensajería de terceros. Tú llevas registro de dos cosas:
destinatarios y puntos finales específicos del destinatario en el servidor de mensajería. El
servidor de mensajería controla las rutas.

## El contexto más amplio {: #the-broader-context }

Hemos visto cómo suscribirte a los mensajes de notificaciones push dentro de una app web. Ese proceso
incluyó pasar una clave pública, llamada la `applicationServerKey`, a la
API de suscripción.

En el siguiente diagrama, se muestra el orden de las operaciones.

![Enviando un mensaje](images/push-flow.gif)

1. Un dispositivo descarga tu app web que contiene una publicKey ya creada,
   a la cual se hace referencia en secuencias de comandos como la `applicationServerKey`. Tu app web instala
   un proceso de trabajo.
1. Durante el flujo de suscripción, el navegador contacta el servidor de mensajería para
   crear una suscripción nueva y devolvérsela a la app.

    Nota: No tienes que conocer la URL del servidor de mensajería. Cada proveedor de navegador administra su propio servidor de mensajería para su navegador.

1. Después del flujo de suscripción, tu app vuelve a pasar un objeto de suscripción al
   servidor de tu app.
1. Posteriormente, el servidor de tu app envía un mensaje al servidor
   de mensajería, que lo reenvía al destinatario.

## Generar la applicationServerKey {: #generating-the-key }

Hay muchas cosas que tienes que conocer sobre la `applicationServerKey`:

* Es la parte de la clave pública de un par de claves públicas o privadas generado en el servidor
  de tu app.
* EL par de claves se tienen que poder usar con una firma digital de curva elíptica
  (ECDSA) en la curva P-256.
* Tu app tiene que pasar la clave pública al servidor de mensajería como un conjunto de
  de valores enteros de ocho bits sin firmar.
* Se define en una especificación llamada Voluntary Application Server Identification
  for Web Push (VAPID), la cual discutiremos en la sección [enviar mensajes](sending-messages).

Puedes encontrar un ejemplo para generar esto en la
[biblioteca de nodo web-push](https://github.com/web-push-libs/web-push/). Puede
lucir así:

    function generateVAPIDKeys() {
      var curve = crypto.createECDH('prime256v1');
      curve.generateKeys();

      return {
        publicKey: curve.getPublicKey(),
        privateKey: curve.getPrivateKey(),
      };
    }

## Anatomía de un objeto de suscripción {: #subscription-anatomy }

Anteriormente, dijimos que un objeto de suscripción se tiene convertir en string y pasar al
servidor, pero no te dijimos que había en el objeto de suscripción. Eso es
porque el cliente no hace nada con esto. El servidor sí.

El objeto de suscripción tiene la siguiente apariencia:

    {
      "endpoint": "https://example.com/push-service/send/dbDqU8xX10w:APA91b...",
      "keys": {
        "auth": "qLAYRzG9TnUwbprns6H2Ew==",
        "p256dh": "BILXd-c1-zuEQYXH\\_tc3qmLq52cggfqqTr\\_ZclwqYl6A7-RX2J0NG3icsw..."
      }
    }

¿Cuál es el contenido?

**endpoint**: contiene dos partes, la URL del servicio de mensajería que usa el
navegador que suscribe seguido del identificador único para el usuario.

**keys**: las claves de encriptación que se usan para encriptar datos se pasan a los mensajes del proceso
de trabajo. Contiene lo siguiente:

* **auth**: un secreto de autenticación de 16 bytes generado por el navegador.
* **p256dh**: 65 bytes contienen una clave pública del navegador que los
  desarrolladores tienen que usar cuando se encriptan mensajes que quieren enviar a ese
  servicio push.

Note: En muchos de los bytes de especificaciones relevantes se llaman octetos. El término se usa debido a lo heredado y a los sistemas de comunicación en que los bytes no siempre tienen 8 bits.

## Crear el mensaje {: #creating-the-message }

Aquí es donde las cosas comienzan a volverse disparatadas. En esta sección, ya no estamos
en tu app cliente. Estamos en el servidor de la app donde vamos a crear
y a enviar un mensaje al cliente. Hay muchas cosas para controlar.

Antes de continuar, revisemos qué tenemos y de dónde proviene.

* **Objeto de subscripción**: esto proviene del cliente. Contiene el punto final
  del servidor de mensajería, una copia de la clave pública y un secreto de autenticación
  generado por el cliente. De aquí en más, dejaremos de hablar
  sobre el objeto de subscripción y solo haremos referencia al **elemento final**, la **clave
  pública** y el **secreto de autenticación**.
* **clave privada**: la clave privada VAPID corresponde a la clave privada VAPID.
  Esta es una clave privada para tu servidor de la app.

Vamos a mirar la creación de un mensaje en tres partes. Primero crearemos algunos encabezados
HTTP, luego crearemos una carga para el mensaje y finalmente los combinaremos
y los enviaremos al servidor de mensajería.

### Una nota sobre ejemplos de códigos {: #a-note-about-samples }

Los ejemplos de códigos que se proporcionan en esta sección, se toman de la [biblioteca de
nodo web-push](https://github.com/web-push-libs/web-push).

### El producto {: #the-product }

Miremos con qué vamos a terminar, luego hablaremos de cómo
crearlo.

POST /push-service/send/dbDqU8xX10w:APA91b... HTTP/1.1
Host: push.example.net
Push-Receipt: https://push.example.net/r/3ZtI4YVNBnUUZhuoChl6omU
TTL: 43200
Content-Type: text/plain;charset=utf8
Content-Length: 36
Authorization: WebPush
eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJhdWQiOiJodHRwczovL3B1c2guZXhhbXBsZS5uZXQiLCJleHAiOjE0NTM1MjM3NjgsInN1YiI6Im1haWx0bzpwdXNoQGV4YW1wbGUuY29tIn0.i3CYb7t4xfxCDquptFOepC9GAu\_HLGkMlMuCGSK2rpiUfnK9ojFwDXb1JrErtmysazNjjvW2L9OkSSHzvoD1oA
Crypto-Key:
p256ecdsa=BA1Hxzyi1RUM1b5wjxsn7nGxAszw2u61m164i3MrAIxHF6YK5h4SDYic-dRuU\_RCPCfA5aq9ojSwk5Y2EmClBPsiChYuI3jMzt3ir20P8r\_jgRR-dSuN182x7iB

Ten en cuenta que esta solicitud se envía al punto final contenido en el objeto
de suscripción. Los encabezados de Authorization, Crypto-Key y TTL requieren de alguna
de explicación. Comencemos con lo más simple.

## Encabezados HTTP {: #http-headers }

### TTL {: #ttl }

Puede llevar un poco de tiempo hasta que el servidor de mensaje pueda entregar un mensaje enviado por tu
servidor de la app. Los servicios de mensajes no están obligados a mantener un mensaje por siempre.
Francamente, para ser oportunos, un servidor de la app nunca tiene que enviar un mensaje que pueda permanecer
por siempre. Es por ello que se solicita incluir un encabezado llamado TTL, literalmente
"tiempo de permanencia".

EL encabezado TTL es un valor en segundos proporcionado como una sugerencia al servidor
de mensajes sobre cuánto tiempo el servidor tiene que mantener el mensaje e intentar
entregarlo. Si elige, el servidor de mensaje puede acortar el tiempo que desea mantener
el mensaje. Si lo hace, debe mostrar que se acortó el tiempo en un encabezado TTL a través de una
respuesta a la solicitud de mensaje. Si el TTL tiene un valor de 0, el servidor de mensaje
tiene que entregarlo de inmediato si el usuario-agente está disponible. Si el usuario-agente
no está disponible, el mensaje caduca de inmediato y nunca se entrega.

### Encabezado de la Crypto-Key {: #crypto-key-header }

Para validar un mensaje enviado por el servidor de tu app, el servidor de mensaje necesita la
clave pública. Envías la clave pública en el encabezado de la Crypto-Key. El encabezado de la Crypto-Key
tiene varias partes.

dh=publicKey,p256ecdsa=applicationServerKey

Por ejemplo:

dh=BGEw2wsHgLwzerjvnMTkbKrFRxdmwJ5S\_k7zi7A1coR\_sVjHmGrlvzYpAT1n4NPbioFlQkIrT
NL8EH4V3ZZ4vJE,p256ecdsa=BDd3\_hVL9fZi9Ybo2UUzA284WG5FZR30\_95YeZJsiApwXKpNcF1rRPF3foIiBHXRdJI2Qhumhf6\_LFTeZaN

La primera parte (`dh=publicKey`) es la clave pública, la que creamos
en Solicitar permiso y suscribir usuarios. La segunda parte
(`p256ecdsa=applicationServerKey`) es la clave pública creada por el servidor de tu app.
Ambas se deben codificar como dirección url base64. Observa la coma que separa las dos partes de la Crypto-Key.

Note: Un error en Chrome 52 requiere que se use un punto y coma para separar las partes de la Crypto-Key, en lugar de una coma.

### Encabezado de Authorization {: #authorization-header }

Para enviar mensajes, necesitas un encabezado de Authorization. Contiene cuatro partes:

WebPush <JWTHeader>.<Payload>.<Signature>

La palabra WebPush es un literal que debe estar seguido de un espacio. Las partes
restantes, que son encriptadas y concatenadas mediante un punto, forman un JSON
web token (JWT) firmado. Un JWT es un modo de compartir un objeto JSON con una segunda parte de
modo que la parte emisora pueda firmarlo y la parte receptora puede verificar
que la firma sea del emisor esperado.

Veamos cada parte del token en detalle.

#### Encabezado JWT {: #jwt-header }

El encabezado JWT contiene dos extractos estándar de información: una propiedad `typ` para
indicar el tipo de mensaje, en este caso, un mensaje JWT y una propiedad `alg`
para indicar el algoritmo usado para firmar el mensaje.
Estos detalles se deben codificar como dirección url base64.

    {
      "typ": "JWT",
      "alg": "ES256"
    }

#### Carga de JWT {: #jwt-payload }

El JWT llama a esta sección la carga. Aquí no se almacena la carga
del mensaje. Llegaremos a eso en breve. La carga es otro objeto JSON con los
siguientes miembros:
**aud**
Esto contiene el origen del punto final del servicio push, que tienes que extraer
desde el objeto de suscripción. Este no es el origen de tu sitio.
**exp**
Especifica el momento en que la solicitud JWT vence en milisegundos (no el vencimiento
del mensaje en sí). Debe estar dentro de las veinticuatro horas. Esto se puede
calcular convirtiendo la fecha actual en milisegundos y agregando la duración.
Por ejemplo, en Node.js puedes hacer esto:

    Math.floor((Date.now() / 1000) + 12 * 60 * 60)

**sub**
Especifica un sujeto, que la especificación VAPID define como un modo para el servicio push
para contactar a un emisor de mensaje. Esto puede ser una URL o una dirección mailto (consulta el siguiente
ejemplo).

Una carga completa de JWT tiene la siguiente apariencia:

    {
      "aud": "http://push.example.net",
      "exp": "1469618703",
      "sub": "mailto: my-email@some-url.com"
    }

#### Firma {: #signature }

La firma es la última sección del JWT.

WebPush <JWTHeader>.<Payload>.<Signature>

Crear la firma primero concatenando el encabezado JWT y la carga con
un punto. Por ejemplo:

<JWTHeader>.<Payload>

Encripta esto usando la clave privada que creaste en
[Generar la applicationServerKey](#generating-the-key).

Ahora tenemos las tres piezas que forman el JWT que unes
con un punto.

<JWTHeader>.<Payload>.<Signature>

Te mostraremos cómo hacer la encriptación de la firma, pero hay
un número de bibliotecas disponibles. Un buen lugar para mirar es la sección de bibliotecas de
[jwt.io](https://jwt.io/){: .external }.

Finalmente, antepone la palabra 'WebPush' seguida de un espacio. El resultado
se verán más o menos de la siguiente manera:

WebPush eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJhdWQiOiJodHRwczovL2ZjbS5nb29nbGVhcGlzLmNvbSIsImV4cCI6MTQ2NjY2ODU5NCwic3ViIjoibWFpbHRvOnNpbXBsZS1wdXNoLWRlbW9AZ2F1bnRmYWNlLmNvLnVrIn0.Ec0VR8dtf5qb8Fb5Wk91br-evfho9sZT6jBRuQwxVMFyK5S8bhOjk8kuxvilLqTBmDXJM5l3uVrVOQirSsjq0A

### Carga de mensaje {: #message-payload }

Cuando se implementa código del servidor, existen dos métodos para enviar mensajes que deben
considerarse:

* mensajes con carga de datos;
* mensajes sin carga de datos, a menudo citados como "señales".

En el caso de la señal, el service worker usa el mensaje como una señal para
obtener datos desde un terminal. La sección Administrar mensajes contiene un ejemplo de código
para mostrar cómo lo hace un proceso de trabajo.

¿Qué motivos te impulsarían a enviar un mensaje sin carga? Existen dos:

* Si debes enviar algo cuyo tamaño supera el límite de carga de 4 k establecido por la especificación
* Si los clientes necesitan datos más actualizados que los que se ofrecerían en el mensaje de aplicación.

Técnicamente, la otra razón es que las capacidades del navegador pueden variar
por un tiempo, pero probablemente las dos razones principales se aplicarán siempre. Si el
navegador no es compatible con las cargas, el objeto de suscripción no contendrá claves.

La carga, sin importar cómo se la diste al cliente, tiene que ser encriptada.
La encriptación es una especialidad que resulta tan suficiente, incluso dentro de un desarrollo de software, que
no te recomendamos escribir tu propio sistema de encriptación. Afortunadamente, hay
varias bibliotecas push disponibles.

Para cargas que se envían a través del servidor de mensaje, tienes que encriptarlas usando la
publicKey y el secreto de autenticación. También se debe usar sal con 16 bytes aleatorios
que son únicos para el mensaje. Finalmente, se agrega al cuerpo de la
solicitud enviada al servidor de mensaje.

### Envío en camino {: #sending-it-on-its-way }

En la biblioteca de nodo web-push, esto se logra con una instancia del objeto
de solicitud desde la biblioteca https incorporada.

    const https = require('https');

En algún punto, se envía la solicitud al servidor de mensaje. La biblioteca de nodo web-push
encapsula este código dentro de una promesa (con llamadas apropiadas para resolver y
rechazar) de modo que pueda suceder de manera asincrónica. El siguiente ejemplo de código, tomado de
la [biblioteca de nodo web-push](https://github.com/web-push-libs/web-push)
ilustra esto.

Ten en cuenta que el servidor de mensaje responde a la solicitud de la red de inmediato,
lo cual significa que es asincrónico con el envío del mensaje a la app del cliente.

    const pushRequest = https.request(options, function(pushResponse) {
      let body = '';
      // Allow the payload to be sent out in chunks.
      pushResponse.on('data', function(chunk) {
        body += chunk;
      });
      // Check to see if the push is successful.
      pushResponse.on('end', function() {
        if (pushResponse.statusCode !== 201) {
          reject(new WebPushError('Received unexpected response code',
            pushResponse.statusCode, pushResponse.headers, body));
        } else {
          // Do something with the response body.
        }
     });
    });

    if (requestPayload) {
      pushRequest.write(requestPayload);
    }

    pushRequest.end();

    pushRequest.on('error', function(e) {
      console.error(e);
    });

{# wf_devsite_translation #}


text:
FROM alpine

ENV LLVM_VERSION 3.9

RUN apk add --update \
  alpine-sdk \
  libressl-dev \
  binutils-gold \
  llvm${LLVM_VERSION} \
  llvm${LLVM_VERSION}-dev \
  pcre2-dev \
  libexecinfo-dev \
  coreutils \
  linux-headers

# add user pony in order to not run tests as root
RUN adduser -D -s /bin/sh -h /home/pony -g root pony
USER pony
WORKDIR /home/pony


text:
package util

import (
	"encoding/json"
	"fmt"
)

type etcdHealth struct {
	// Note this has to be public so the json library can modify it.
	Health string `json:"health"`
}

func EtcdHealthCheck(data []byte) error {
	obj := etcdHealth{}
	if err := json.Unmarshal(data, &obj); err != nil {
		return err
	}
	if obj.Health != "true" {
		return fmt.Errorf("Unhealthy status: %s", obj.Health)
	}
	return nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MsTestToXunitConverter.xUnit
{
    class TestClass
    {
        [TestMethod, Ignore("Reason")]
        public void IgnoreA()
        {

        }
    }
}


text:
transcription conversion tool for Sanskrit (supports only lower cases)

supported transcription formats:
- deva: Devanāgarī
- iast: (customized) International Alphabet of Sanskrit Transliteration
- kami: (customized) kamimura encoding
- kh: Harvard-Kyoto

See `encs` defined in index.js for details.

## Install

```sh
npm install https://github.com/mkunten/encoding-lang-sa.git --save
```

## Usage

### nodejs

#### convert
```javascript
var EncodingLangSa = require('encoding-lang-sa');

// IAST to Devanāgarī
var kh2iast = EncodingLangSa.converter('kh', 'iast');
console.log(kh2iast('AsId rAjA nalo nAma vIrasenasuto balI/'));
// -> āsīd rājā nalo nāma vīrasenasuto balī/

// IAST to Devanāgarī
var iast2deva = EncodingLangSa.converter('iast', 'deva', { removeSpace: true });
console.log(iast2deva('^āsīd rājā nalo nāma vīrasenasuto balī/'));
// -> आसीद्राजा नलो नाम वीरसेनसुतो बली ।
// * independent vowels like आ are romanized with the prefix '^'.
```

#### sort

```javascript
// IAST
var iastSorter = EncodingLangSa.sorter('iast');
console.log([ 'aśva', 'aiśvarya', 'āśva', 'aśvin', 'iśvara' ].sort(iastSorter));
// -> [ 'aśva', 'aśvin', 'āśva', 'iśvara', 'aiśvarya' ]
```

### browser

```html
<script type="application/javascript" src="/path/to/static/js/encoding-lang-sa.js"></script>
```

#### convert

```javascript
// IAST to Devanāgarī
var kh2iast = EncodingLangSa.converter('kh', 'iast');
console.log(kh2iast('AsId rAjA nalo nAma vIrasenasuto balI/'));
// -> āsīd rājā nalo nāma vīrasenasuto balī/

// IAST to Devanāgarī
var iast2deva = EncodingLangSa.converter('iast', 'deva', { removeSpace: true });
console.log(iast2deva('^āsīd rājā nalo nāma vīrasenasuto balī/'));
// -> आसीद्राजा नलो नाम वीरसेनसुतो बली ।
</script>
```

#### sort

```javascript
// IAST
var iastSorter = EncodingLangSa.sorter('iast');
console.log([ 'aśva', 'aiśvarya', 'āśva', 'aśvin', 'iśvara' ].sort(iastSorter));
// -> [ 'aśva', 'aśvin', 'āśva', 'iśvara', 'aiśvarya' ]
```

## Version
0.0.2

## License
MIT


text:
package de.iew.stagediver.fx.eventbus.event;

import de.iew.framework.utils.Assert;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Implements a simple extension of {@link java.util.HashMap} to provide a fluent interface to build parameter maps
 * for OSGis event system.
 *
 * @author Manuel Schulze
 * @since 16.04.14 - 21:14
 */
public class EventParameterMap<T> extends HashMap<String, T> implements Serializable {

    private static final long serialVersionUID = -4260520632450829459L;

    /**
     * Adds the specified property and value into this parameter map.
     *
     * @param property Not NULL property name
     * @param value    The value to add (Can be NULL)
     * @return This parameter map for fluent interface
     */
    public EventParameterMap<T> add(final String property, final T value) {
        Assert.assertMethodParameterIsNotNull(property);

        put(property, value);
        return this;
    }

    /**
     * Adds all properties of the specified map into this parameter map.
     *
     * @param properties The properties to add
     * @return This parameter map for fluent interface
     */
    public EventParameterMap<T> putProperties(final Map<String, T> properties) {
        if (properties != null) {
            putAll(properties);
        }
        return this;
    }

    /**
     * Many use cases just put a few values into a parameter map. This method shortens the creation of such maps because
     * you can provide the first property / value pair at construction time.
     *
     * @param property Not NULL property name
     * @param value    The value to add (Can be NULL)
     * @return The created parameter map
     */
    public static EventParameterMap<Object> create(final String property, final Object value) {
        return create().add(property, value);
    }

    /**
     * Many use cases just put a few values into a parameter map. This method creates an empty parameter map.
     *
     * @return The created parameter map
     */
    public static EventParameterMap<Object> create() {
        return new EventParameterMap<>();
    }

    /**
     * Many use cases just put a few values into a parameter map. This method shortens the creation of such maps because
     * you can put a map of properties at construction time.
     *
     * @param properties the map of properties
     * @return The created parameter map
     */
    public static EventParameterMap<Object> create(final Map<String, Object> properties) {
        return create().putProperties(properties);
    }
}


text:
{{ header | safe }}

{{ subcopy | safe }}

                      {{ call_to_action }}

              {{ offer_details }}


text:
"""
General class for a recurrent language model
"""
__docformat__ = 'restructedtext en'
__authors__ = ("Alessandro Sordoni")
__contact__ = "Alessandro Sordoni <sordonia@iro.umontreal>"

import theano
import theano.tensor as T
import numpy as np
import cPickle
import logging
import operator

logger = logging.getLogger(__name__)

from theano.sandbox.rng_mrg import MRG_RandomStreams
from theano.tensor.shared_randomstreams import RandomStreams
from collections import OrderedDict

from model import *
from utils import *

# Theano speed-up
theano.config.scan.allow_gc = False
#

def add_to_params(params, new_param):
    params.append(new_param)
    return new_param

class ComponentBase():
    def __init__(self, state, rng, parent):
        patience = state['patience']
        self.rng = rng
        self.trng = MRG_RandomStreams(max(self.rng.randint(2 ** 15), 1))

        self.parent = parent
        self.state = state
        self.__dict__.update(state)

        self.rec_activation = eval(self.rec_activation)
        self.params = []

class LanguageModel(ComponentBase):
    TRAINING = 0
    EVALUATION = 1
    SAMPLING = 2
    BEAM_SEARCH = 3

    def init_params(self):
        ###################
        # RECURRENT WEIGHTS
        ###################
        self.W_emb = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.idim, self.rankdim), name='W_emb'))
        self.W_in = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.rankdim, self.qdim), name='W_in'))
        self.W_hh = add_to_params(self.params, theano.shared(value=OrthogonalInit(self.rng, self.qdim, self.qdim), name='W_hh'))
        self.b_hh = add_to_params(self.params, theano.shared(value=np.zeros((self.qdim,), dtype='float32'), name='b_hh'))

        if self.step_type == "gated":
            self.b_r = add_to_params(self.params, theano.shared(value=np.zeros((self.qdim,), dtype='float32'), name='b_r'))
            self.b_z = add_to_params(self.params, theano.shared(value=np.zeros((self.qdim,), dtype='float32'), name='b_z'))

            self.W_in_r = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.rankdim, self.qdim), name='W_in_r'))
            self.W_in_z = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.rankdim, self.qdim), name='W_in_z'))
            self.W_hh_r = add_to_params(self.params, theano.shared(value=OrthogonalInit(self.rng, self.qdim, self.qdim), name='W_hh_r'))
            self.W_hh_z = add_to_params(self.params, theano.shared(value=OrthogonalInit(self.rng, self.qdim, self.qdim), name='W_hh_z'))

        self.bd_out = add_to_params(self.params, theano.shared(value=np.zeros((self.idim,), dtype='float32'), name='bd_out'))
        self.Wd_emb = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.idim, self.rankdim), name='Wd_emb'))

        ######################
        # Output layer weights
        ######################
        out_target_dim = self.qdim
        if not self.maxout_out:
            out_target_dim = self.rankdim

        self.Wd_out = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.qdim, out_target_dim), name='Wd_out'))

        # Set up deep output
        if self.deep_out:
            self.Wd_e_out = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.rankdim, out_target_dim), name='Wd_e_out'))
            self.bd_e_out = add_to_params(self.params, theano.shared(value=np.zeros((out_target_dim,), dtype='float32'), name='bd_e_out'))

    def plain_step(self, x_t, h_tm1):
        #### Handle the bias from the document
        h_t = T.dot(x_t, self.W_in) + T.dot(h_tm1, self.W_hh) + self.b_hh
        h_t = self.rec_activation(h_t)
        return h_t

    def gated_step(self, x_t, h_tm1):
        r_t = T.nnet.sigmoid(T.dot(x_t, self.W_in_r) + T.dot(h_tm1, self.W_hh_r) + self.b_r)
        z_t = T.nnet.sigmoid(T.dot(x_t, self.W_in_z) + T.dot(h_tm1, self.W_hh_z) + self.b_z)

        h_tilde = T.dot(x_t, self.W_in) + T.dot(r_t * h_tm1, self.W_hh) + self.b_hh
        h_tilde = self.rec_activation(h_tilde)
        h_t = (np.float32(1.0) - z_t) * h_tm1 + z_t * h_tilde
        return h_t, r_t, z_t, h_tilde

    def approx_embedder(self, x):
        return self.W_emb[x]

    def build_lm(self, x, y=None, mode=TRAINING, prev_h=None, step_num=None):
        """
        x is the input sequence
        y are the targets
        mode is the evaluation or sampling mode
        prev_h is used in the sampling mode
        step_num is the step number of decoding
        """
        one_step = False

        # Check parameter consistency
        if mode == LanguageModel.EVALUATION or mode == LanguageModel.TRAINING:
            assert y
        else:
            assert not y
            assert prev_h
            one_step = True

        # if x.ndim == 2 then
        # x = (n_steps, batch_size)
        if x.ndim == 2:
            batch_size = x.shape[1]
        # else x = (word_1, word_2, word_3, ...)
        # or x = (last_word_1, last_word_2, last_word_3, ..)
        # in this case batch_size is
        else:
            batch_size = 1

        if not prev_h:
            prev_h = T.alloc(np.float32(0.), batch_size, self.qdim)

        xe = self.approx_embedder(x)
        # Gated Encoder
        if self.step_type == "gated":
            f_enc = self.gated_step
            o_enc_info = [prev_h, None, None, None]
        else:
            f_enc = self.plain_step
            o_enc_info = [prev_h]

        # Run through all the sentence (encode everything)
        if not one_step:
            _res, _ = theano.scan(f_enc,
                              sequences=[xe],\
                              outputs_info=o_enc_info)
        # Make just one step further
        else:
            _res = f_enc(xe, prev_h)

        h = _res[0]
        # Store last h for further use
        pre_activ = self.output_layer(h, xe)

        # EVALUATION  : Return target_probs
        # target_probs.ndim == 3
        outputs = self.output_softmax(pre_activ)

        if mode == LanguageModel.EVALUATION:
            target_probs = GrabProbs(outputs, y)
            return target_probs, h
        # BEAM_SEARCH : Return output (the softmax layer) + the new hidden states
        elif mode == LanguageModel.BEAM_SEARCH:
            return outputs, h
        # SAMPLING    : Return a vector of n_sample from the output layer
        #                 + log probabilities + the new hidden states
        elif mode == LanguageModel.SAMPLING:
            if outputs.ndim == 1:
                outputs = outputs.dimshuffle('x', 0)

            sample = self.trng.multinomial(pvals=outputs, dtype='int64').argmax(axis=-1)
            if outputs.ndim == 1:
                sample = sample[0]

            log_prob = -T.log(T.diag(outputs.T[sample]))
            return sample, log_prob, h

    def output_layer(self, h, x):
        pre_activ = T.dot(h, self.Wd_out)

        if self.deep_out:
            pre_activ += T.dot(x, self.Wd_e_out) + self.bd_e_out

        if self.maxout_out:
            pre_activ = Maxout(2)(pre_activ)

        return pre_activ

    def output_softmax(self, pre_activ):
        # returns a (timestep, bs, idim) matrix (huge)
        return SoftMax(T.dot(pre_activ, self.Wd_emb.T) + self.bd_out)

    def build_next_probs_predictor(self, x, prev_h, d=None):
        return self.build_lm(x, d, mode=LanguageModel.BEAM_SEARCH, prev_h=prev_h)

    def sampling_step(self, *args):
        args = iter(args)

        # Arguments that correspond to scan's "sequences" parameteter:
        step_num = next(args)
        assert step_num.ndim == 0

        # Arguments that correspond to scan's "outputs" parameteter:
        prev_word = next(args)
        assert prev_word.ndim == 1

        # skip the previous word log probability
        log_prob = next(args)
        assert log_prob.ndim == 1

        prev_h = next(args)
        assert prev_h.ndim == 2

        # When we sample we shall recompute the lm for one step...
        sample, log_prob, h = self.build_lm(prev_word, prev_h=prev_h, step_num=step_num, mode=LanguageModel.SAMPLING)

        assert sample.ndim == 1
        assert log_prob.ndim == 1
        assert h.ndim == 2

        return [sample, log_prob, h]

    def build_sampler(self, n_samples, n_steps):
        # For the naive sampler, the states are:
        # 1) a vector [<s>] * n_samples to seed the sampling
        # 2) a vector of [ 0. ] * n_samples for the log_probs
        # 3) prev_h hidden layers
        # TODO: This does not support the document bias
        states = [T.alloc(np.int64(self.sos_sym), n_samples),
                  T.alloc(np.float32(0.), n_samples),
                  T.alloc(np.float32(0.), n_samples, self.qdim)]
        outputs, updates = theano.scan(self.sampling_step,
                    outputs_info=states,
                    sequences=[T.arange(n_steps, dtype='int64')],
                    n_steps=n_steps,
                    name="sampler_scan")
        # Return sample, log_probs and updates (for tnrg multinomial)
        return (outputs[0], outputs[1]), updates
    ####

    def __init__(self, state, rng, parent):
        ComponentBase.__init__(self, state, rng, parent)
        self.init_params()

class RecurrentLM(Model):
    def indices_to_words(self, seq):
        sen = []
        for k in range(len(seq)):
            sen.append(self.idx_to_str[seq[k]])
            if seq[k] == self.eos_sym:
                break
        return ' '.join(sen)

    def words_to_indices(self, seq):
        sen = []
        for k in range(len(seq)):
            sen.append(self.str_to_idx.get(seq[k], self.unk_sym))
        return sen

    def compute_updates(self, training_cost, params):
        updates = {}

        grads = T.grad(training_cost, params)
        grads = OrderedDict(zip(params, grads))

        # Clip stuff
        c = numpy.float32(self.cutoff)
        clip_grads = []

        norm_gs = T.sqrt(sum(T.sum(g ** 2) for p, g in grads.items()))
        normalization = T.switch(T.ge(norm_gs, c), c / norm_gs, np.float32(1.))
        notfinite = T.or_(T.isnan(norm_gs), T.isinf(norm_gs))

        for p, g in grads.items():
            clip_grads.append((p, T.switch(notfinite, numpy.float32(.1) * p, g * normalization)))
        grads = OrderedDict(clip_grads)

        if self.updater == 'adagrad':
            updates = Adagrad(grads, self.lr)
        elif self.updater == 'sgd':
            raise Exception("Sgd not implemented!")
        elif self.updater == 'adadelta':
            updates = Adadelta(grads)
        elif self.updater == 'rmsprop':
            updates = RMSProp(grads, self.lr)
        elif self.updater == 'adam':
            updates = Adam(grads)
        else:
            raise Exception("Updater not understood!")
        return updates

    def build_train_function(self):
        if not hasattr(self, 'train_fn'):
            # Compile functions
            logger.debug("Building train function")
            model_updates = self.compute_updates(self.prediction_cost / self.x_data.shape[1], self.params)
            self.train_fn = theano.function(inputs=[self.x_data, self.x_max_length, self.x_cost_mask],
                                            outputs=self.prediction_cost, updates=model_updates, name="train_fn")
        return self.train_fn

    def build_eval_function(self):
        if not hasattr(self, 'eval_fn'):
            # Compile functions
            logger.debug("Building evaluation function")
            self.eval_fn = theano.function(inputs=[self.x_data, self.x_max_length, self.x_cost_mask],
                                            outputs=self.prediction_cost, name="eval_fn")
        return self.eval_fn

    def build_sampling_function(self):
        if not hasattr(self, 'sample_fn'):
            logger.debug("Building sampling function")
            self.sample_fn = theano.function(inputs=[self.n_samples, self.n_steps], outputs=[self.sample, self.sample_log_prob], \
                                       updates=self.sampling_updates, name="sample_fn")
        return self.sample_fn

    def build_next_probs_function(self):
        if not hasattr(self, 'next_probs_fn'):
            outputs, h = self.language_model.build_next_probs_predictor(self.beam_source, prev_h=self.beam_h)
            self.next_probs_fn = theano.function(inputs=[self.beam_h, self.beam_source],
                                                 outputs=[outputs, h],
                                                 name="next_probs_fn")
        return self.next_probs_fn

    def __init__(self, rng, state):
        Model.__init__(self)
        self.state = state

        # Compatibility towards older models
        self.__dict__.update(state)
        self.rng = rng

        # Load dictionary
        raw_dict = cPickle.load(open(self.dictionary, 'r'))

        # Probabilities for each term in the corpus
        self.str_to_idx = dict([(tok, tok_id) for tok, tok_id, _ in raw_dict])
        self.idx_to_str = dict([(tok_id, tok) for tok, tok_id, freq in raw_dict])

        # if '<s>' not in self.str_to_idx \
        #   or '</s>' not in self.str_to_idx:
        #        raise Exception("Error, malformed dictionary!")

        # Number of words in the dictionary
        self.idim = len(self.str_to_idx)
        self.state['idim'] = self.idim

        logger.debug("Initializing language model")
        self.language_model = LanguageModel(self.state, self.rng, self)

        # Init params
        self.params = self.language_model.params

        self.x_data = T.imatrix('x_data')
        self.x_cost_mask = T.matrix('cost_mask')
        self.x_max_length = T.iscalar('x_max_length')

        # The training is done with a trick. We append a special </q> at the beginning of the session
        # so that we can predict also the first query in the session starting from the session beginning token (</q>).
        self.aug_x_data = T.concatenate([T.alloc(np.int32(self.eos_sym), 1, self.x_data.shape[1]), self.x_data])
        self.training_x = self.aug_x_data[:self.x_max_length]
        self.training_y = self.aug_x_data[1:self.x_max_length+1]
        self.training_x_cost_mask = self.x_cost_mask[:self.x_max_length].flatten()

        target_probs, self.eval_h = self.language_model.build_lm(self.training_x,
                                                    y=self.training_y,
                                                    mode=LanguageModel.EVALUATION)

        # Prediction cost
        self.prediction_cost = T.sum(-T.log(target_probs) * self.training_x_cost_mask)

        # Sampling variables
        self.n_samples = T.iscalar("n_samples")
        self.n_steps = T.iscalar("n_steps")
        (self.sample, self.sample_log_prob), self.sampling_updates \
                = self.language_model.build_sampler(self.n_samples, self.n_steps)

        # Beam-search variables
        self.beam_source = T.lvector("beam_source")
        self.beam_h = T.matrix("beam_h")
        self.beam_step_num = T.lscalar("beam_step_num")


text:
(function(){
    'use strict';

    angular.module('gantt').factory('GanttHierarchy', [function() {
        var Hierarchy = function () {
            var self = this;

            var nameToRow = {};

            var idToRow = {};

            var nameToChildren = {};
            var idToChildren = {};

            var nameToParent = {};
            var idToParent = {};

            var registerChildRow = function(row, childRow) {
                if (childRow !== undefined) {
                    var nameChildren = nameToChildren[row.model.name];
                    if (nameChildren === undefined) {
                        nameChildren = [];
                        nameToChildren[row.model.name] = nameChildren;
                    }
                    nameChildren.push(childRow);

                    var idChildren = idToChildren[row.model.id];
                    if (idChildren === undefined) {
                        idChildren = [];
                        idToChildren[row.model.id] = idChildren;
                    }
                    idChildren.push(childRow);

                    nameToParent[childRow.model.name] = row;
                    idToParent[childRow.model.id] = row;
                }
            };

            this.refresh = function(rows) {
                nameToRow = {};
                idToRow = {};

                nameToChildren = {};
                idToChildren = {};

                nameToParent = {};
                idToParent = {};

                angular.forEach(rows, function(row) {
                    nameToRow[row.model.name] = row;
                    idToRow[row.model.id] = row;
                });

                angular.forEach(rows, function(row) {
                    if (row.model.parent !== undefined) {
                        var parentRow = nameToRow[row.model.parent];
                        if (parentRow === undefined) {
                            parentRow = idToRow[row.model.parent];
                        }

                        if (parentRow !== undefined) {
                            registerChildRow(parentRow, row);
                        }
                    }

                    if (row.model.children !== undefined) {
                        angular.forEach(row.model.children, function(childRowNameOrId) {
                            var childRow = nameToRow[childRowNameOrId];
                            if (childRow === undefined) {
                                childRow = idToRow[childRowNameOrId];
                            }

                            if (childRow !== undefined) {
                                registerChildRow(row, childRow);
                            }
                        });
                    }
                });

                var rootRows = [];
                angular.forEach(rows, function(row) {
                    if (self.parent(row) === undefined) {
                        rootRows.push(row);
                    }
                });

                return rootRows;
            };

            this.children = function(row) {
                var children = idToChildren[row.model.id];
                return children;
            };

            this.descendants = function(row) {
                var descendants = [];

                var children = self.children(row);
                descendants.push.apply(descendants, children);
                if (children !== undefined) {
                    angular.forEach(children, function(child) {
                        var childDescendants = self.descendants(child);
                        descendants.push.apply(descendants, childDescendants);
                    });
                }

                return descendants;
            };

            this.parent = function(row) {
                var parent = idToParent[row.model.id];
                return parent;
            };

            this.ancestors = function(row) {
                var ancestors = [];

                var parent = self.parent(row);
                while (parent !== undefined) {
                    ancestors.push(parent);
                    parent = self.parent(parent);
                }

                return ancestors;
            };
        };

        return Hierarchy;
    }]);
}());