text:
using System;
using System.Xml;
using System.Xml.Serialization;
using Systembolagskollen.Helpers;

namespace Systembolaget.DataObjects
{
    [Serializable]
    public class Beverage
    {
        [XmlElement("nr")]
        public string ArticleNumber { get; set; }

        [XmlElement("Artikelid")]
        public string ArticleId { get; set; }

        [XmlElement("Varnummer")]
        public string PartNumber { get; set; }

        [XmlElement("Namn")]
        public string Name { get; set; }

        [XmlElement("Prisinklmoms")]
        public decimal PriceIncludingVat { get; set; }

        [XmlElement("Pant")]
        public string Pawn { get; set; }

        [XmlElement("Volymiml")]
        public decimal VolumeInMl { get; set; }

        [XmlElement("PrisPerLiter")]
        public decimal PricePerLiter { get; set; }

        [XmlElement("Saljstart")]
        public string StartOfSales { get; set; }

        [XmlElement("Varugrupp")]
        public string Department { get; set; }

        [XmlElement("Forpackning")]
        public string Packaging { get; set; }

        [XmlElement("Ursprunglandnamn")]
        public string CountryOfOrigin { get; set; }

        [XmlElement("Producent")]
        public string Producer { get; set; }

        [XmlElement("Leverantor")]
        public string Supplier { get; set; }

        [XmlElement("Alkoholhalt")]
        public string Alcohol { get; set; }

        [XmlElement("Sortiment")]
        public string Assortment { get; set; }

        [XmlElement("Ekologiskt")]
        public string Ecologic { get; set; }

        [XmlElement("Etiskt")]
        public string Ethical { get; set; }

        [XmlElement("Koscher")]
        public string Koscher { get; set; }

        [XmlElement("RavarorBeskrivning")]
        public string RawMaterialSynopsis { get; set; }

        public string EcologicSynopsis
        {
            get
            {
                if (EcologicAsBool)
                    return "Ja";
                return "Nej";
            }
        }

        public string EthicalSynopsis
        {
            get
            {
                if (EthicalAsBool)
                    return "Ja";
                return "Nej";
            }
        }

        public string KoscherSynopsis
        {
            get
            {
                if (KoscherAsBool)
                    return "Ja";
                return "Nej";
            }
        }

        private bool EcologicAsBool
        {
            get
            {
                return Ecologic == "1";
            }
        }

        private bool EthicalAsBool
        {
            get
            {
                return Ethical == "1";
            }
        }

        private bool KoscherAsBool
        {
            get
            {
                return Koscher == "1";
            }
        }

        public decimal PriceIncludingPawn
        {
            get
            {
                if (Pawn == null)
                    return PriceIncludingVat;
                return (PriceIncludingVat + Convert.ToDecimal(Pawn.Replace(".", ",")));
            }
        }

        public override string ToString()
        {
            var stringLiteral = "";

            stringLiteral += String.Format("{0, -50}", Name);
            stringLiteral += String.Format("{0, 10}", ArticleId);
            stringLiteral += String.Format("{0, 20}", ArticleNumber);
            stringLiteral += String.Format("{0, 100}", PriceIncludingVat);
            stringLiteral += String.Format("{0, 20}", PartNumber);

            return stringLiteral;
        }

        public decimal APK
        {
            get
            {
                var volume = VolumeInMl;
                var percentage = this.AlcoholToDecimal().PreventZero().ToPercentage();
                var price = PriceIncludingVat.PreventZero();

                var täljare = VolumeInMl * percentage;
                var nämnare = price;

                var apk = täljare / nämnare;

                return Math.Round(apk, 2);
            }
        }
    }
}


text:
export fixed_field, subfields

add_verbose_scope(:Subfields)

# Compute basis for the subfield of K that is generated by the elements of as.
function _subfield_basis(K::S, as::Vector{T}) where {
    S <: Union{AnticNumberField, Hecke.NfRel},
    T <: Union{nf_elem, Hecke.NfRelElem}
   }
  if isempty(as)
    return elem_type(K)[gen(K)]
  end

  # Notation: k base field, K the ambient field, F the field generated by as

  k = base_field(K)

  d = degree(K)
  Kvs = VectorSpace(k, d)
  # We transition the coefficients of a in reverse order, so that the
  # first vector in the row reduced echelon form yields the highest
  # degree among all elements of Fas.
  (Fvs,phivs) = sub(Kvs, [Kvs([coeff(a,n) for n in d-1:-1:0])
                          for a in as])
  dF = length(Fvs.gens) # dim(Fvs)
  bs = as
  while !isempty(bs)
    nbs = elem_type(K)[]
    for b in bs
      abs = elem_type(K)[a*b for a in as]
      abvs,_ = sub(Kvs, [Kvs([coeff(ab,n) for n in d-1:-1:0])
                         for ab in abs])
      (Fvs,phivs) = sub(Kvs, typeof(Fvs)[Fvs, abvs])
      if dF != length(Fvs.gens) # dim(Fvs)
        dF = length(Fvs.gens) # dim(Fvs)
        append!(nbs, abs)
      end
    end
    bs = nbs
  end

  kx = parent(K.pol)
  return elem_type(K)[let Kv = phivs(v)
            K(kx([Kv[n] for n in d:-1:1]))
          end
          for v in gens(Fvs)]::Vector{elem_type(K)}
end

function _improve_subfield_basis(K, bas)
  # First compute the maximal order of <bas> by intersecting and saturating
  # Then B_Ok = N * B_LLL_OK
  # Then B' defined as lllN * B_LLL_OK will hopefully be small
  OK = maximal_order(K)
  OKbmatinv = basis_mat_inv(OK, copy = false)
  basinOK = bas * fmpq_mat(OKbmatinv.num) * fmpq(1, OKbmatinv.den)
  deno = fmpz(1)
  for i in 1:nrows(basinOK)
    for j in 1:ncols(basinOK)
      deno = lcm(deno, denominator(basinOK[i, j]))
    end
  end
   S = saturate(map_entries(FlintZZ, basinOK * deno))
  SS = S * basis_matrix(OK, copy = false)
  lllOK = lll(OK)
  N = (SS * basis_mat_inv(lllOK)).num
  lllN = lll(N)
  maybesmaller = lllN * basis_matrix(lllOK)
  return maybesmaller
end

function _improve_subfield_basis_no_lll(K, bas)
  OK = maximal_order(K)
  OKbmatinv = basis_mat_inv(OK, copy = false)
  basinOK = bas * fmpq_mat(OKbmatinv.num) * fmpq(1, OKbmatinv.den)
  deno = fmpz(1)
  for i in 1:nrows(basinOK)
    for j in 1:ncols(basinOK)
      deno = lcm(deno, denominator(basinOK[i, j]))
    end
  end
  S = saturate(map_entries(FlintZZ, basinOK * deno))
  SS = S * basis_matrix(OK, copy = false)
  return SS
end

# Compute a primitive element given a basis of a subfield
function _subfield_primitive_element_from_basis(K::S, as::Vector{T}) where {
    S <: Union{AnticNumberField, Hecke.NfRel},
    T <: Union{nf_elem, Hecke.NfRelElem}
   }
  if isempty(as)
    return gen(K)
  end

  d = length(as)

  # First check basis elements
  i = findfirst(a -> degree(minpoly(a)) == d, as)
  if i <= d
    return as[i]
  end

  k = base_field(K)

  # Notation: cs the coefficients in a linear combination of the as, ca the dot
  # product of these vectors.
  cs = fmpz[zero(ZZ) for n in 1:d]
  cs[1] = one(ZZ)
  while true
    ca = sum(c*a for (c,a) in zip(cs,as))
    if degree(minpoly(ca)) == d
      return ca
    end

    # increment the components of cs
    cs[1] += 1
    let i = 2
      while i <= d && cs[i-1] > cs[i]+1
        cs[i-1] = zero(ZZ)
        cs[i] += 1
        i += 1
      end
    end
  end
end

#As above, but for AnticNumberField type
#In this case, we can use block system to find if an element is primitive.
function _subfield_primitive_element_from_basis(K::AnticNumberField, as::Vector{nf_elem})
  if isempty(as) || degree(K) == 1
    return gen(K)
  end

  dsubfield = length(as)

  @vprint :Subfields 1 "Sieving for primitive elements\n"
  # First check basis elements
  @vprint :Subfields 1 "Sieving for primitive elements\n"
  # First check basis elements
  Zx = PolynomialRing(FlintZZ, "x", cached = false)[1]
  f = Zx(K.pol*denominator(K.pol))
  p, d = _find_prime(fmpz_poly[f])
  #First, we search for elements that are primitive using block systems
  F = FlintFiniteField(p, d, "w", cached = false)[1]
  Ft = PolynomialRing(F, "t", cached = false)[1]
  ap = zero(Ft)
  fit!(ap, degree(K)+1)
  rt = roots(f, F)
  indices = Int[]
  for i = 1:length(as)
    b = _block(as[i], rt, ap)
    if length(b) == dsubfield
      push!(indices, i)
    end
  end

  @vprint :Subfields 1 "Found $(length(indices)) primitive elements in the basis\n"
  #Now, we select the one of smallest T2 norm
  if !isempty(indices)
    a = as[indices[1]]
    I = t2(a)
    for i = 2:length(indices)
      t2n = t2(as[indices[i]])
      if t2n < I
        a = as[indices[i]]
        I = t2n
      end
    end
    @vprint :Subfields 1 "Primitive element found\n"
    return a
  end

  @vprint :Subfields 1 "Trying combinations of elements in the basis\n"
  # Notation: cs the coefficients in a linear combination of the as, ca the dot
  # product of these vectors.
  cs = fmpz[rand(FlintZZ, -2:2) for n in 1:dsubfield]
  k = 0
  s = 1
  first = true
  a = one(K)
  I = t2(a)
  while true
    s += 1
    ca = sum(c*a for (c,a) in zip(cs,as))
    b = _block(ca, rt, ap)
    if length(b) == dsubfield
      t2n = t2(ca)
      if first
        a = ca
        I = t2n
        first = false
      elseif t2n < I
        a = ca
        I = t2n
      end
      k += 1
      if k == 5
      	@vprint :Subfields 1 "Primitive element found\n"
        return a
      end
    end

    # increment the components of cs
    bb = div(s, 10)+1
    for n = 1:dsubfield
      cs[n] = rand(FlintZZ, -bb:bb)
    end
  end
end

################################################################################
#
#  Subfield
#
################################################################################

@doc Markdown.doc"""
    subfield(L::NumField, elt::Vector{<: NumFieldelem};
                          isbasis::Bool = false) -> NumField, Map

The simple number field $k$ generated by the elements of `elt` over the base
field $K$ of $L$ together with the embedding $k \to L$.

If `isbasis` is `true`, it is assumed that `elt` holds a $K$-basis of $k$.
"""
function subfield(K::NumField, elt::Vector{<:NumFieldElem}; isbasis::Bool = false)
  if length(elt) == 1
    return _subfield_from_primitive_element(K, elt[1])
  end

  if isbasis
    s = _subfield_primitive_element_from_basis(K, elt)
  else
    bas = _subfield_basis(K, elt)
    s = _subfield_primitive_element_from_basis(K, bas)
  end

  return _subfield_from_primitive_element(K, s)
end

function _subfield_from_primitive_element(K::AnticNumberField, s::nf_elem)
  Qx = QQ["x"][1]
  if is_maximal_order_known(K) && s in maximal_order(K)
    OK = maximal_order(K)
    @vtime :Subfields 1 f = Qx(minpoly(representation_matrix(OK(s, false))))
  else
    # Don't return a defining polynomial with denominators
    s = denominator(s) * s
    @vtime :Subfields 1 f = minpoly(Qx, s)
  end
  L, _ = NumberField(f, cached = false)
  return L, hom(L, K, s, check = false)
end

function _subfield_from_primitive_element(K, s)
  @vtime :Subfields 1 f = minpoly(s)
  L, _ = NumberField(f, cached = false)
  return L, hom(L, K, s, check = false)
end

################################################################################
#
#  Fixed field
#
################################################################################

@doc Markdown.doc"""
    fixed_field(K::SimpleNumField,
                sigma::Map;
                simplify::Bool = true) -> NumberField, NfToNfMor

Given a number field $K$ and an automorphism $\sigma$ of $K$, this function
returns the fixed field of $\sigma$ as a pair $(L, i)$ consisting of a number
field $L$ and an embedding of $L$ into $K$.

By default, the function tries to find a small defining polynomial of $L$. This
can be disabled by setting `simplify = false`.
"""
function fixed_field(K::SimpleNumField, sigma::T; simplify::Bool = true) where {T <: NumFieldMor}
  return fixed_field(K, T[sigma], simplify = simplify)
end

#@doc Markdown.doc"""
#    fixed_field(K::SimpleNumField, A::Vector{NfToNfMor}) -> NumberField, NfToNfMor
#
#Given a number field $K$ and a set $A$ of automorphisms of $K$, this function
#returns the fixed field of $A$ as a pair $(L, i)$ consisting of a number field
#$L$ and an embedding of $L$ into $K$.
#
#By default, the function tries to find a small defining polynomial of $L$. This
#can be disabled by setting `simplify = false`.
#"""
function fixed_field(K::AnticNumberField, A::Vector{NfToNfMor}; simplify::Bool = true)

  autos = small_generating_set(A)
  if length(autos) == 0
    return K, id_hom(K)
  end

  if is_maximal_order_known(K)
    OK = maximal_order(K)
    if isdefined(OK, :lllO)
      k, mk = fixed_field1(K, A)
      return k, mk
    end
  end

  a = gen(K)
  n = degree(K)
  ar_mat = Vector{fmpq_mat}()
  v = Vector{nf_elem}(undef, n)
  for i in 1:length(autos)
    domain(autos[i]) !== codomain(autos[i]) && throw(error("Maps must be automorphisms"))
    domain(autos[i]) !== K && throw(error("Maps must be automorphisms of K"))
    o = one(K)
    # Compute the image of the basis 1,a,...,a^(n - 1) under autos[i] and write
    # the coordinates in a matrix. This is the matrix of autos[i] with respect
    # to 1,a,...a^(n - 1).
    as = autos[i](a)
    if a == as
      continue
    end
    v[1] = o
    for j in 2:n
      o = o * as
      v[j] = o
    end
    bm = basis_matrix(v, FakeFmpqMat)
    # We have to be a bit careful (clever) since in the absolute case the
    # basis matrix is a FakeFmpqMat

    m = fmpq_mat(bm.num)
    for j in 1:n
      m[j, j] = m[j, j] - bm.den # This is autos[i] - identity
    end

    push!(ar_mat, m)
  end

  if length(ar_mat) == 0
    return K, id_hom(K)
  else
    bigmatrix = hcat(ar_mat)
    k, Ker = kernel(bigmatrix, side = :left)
    bas = Vector{elem_type(K)}(undef, k)
    if simplify
      KasFMat = _improve_subfield_basis(K, Ker)
      for i in 1:k
        bas[i] = elem_from_mat_row(K, KasFMat.num, i, KasFMat.den)
      end
    else
    #KasFMat = _improve_subfield_basis_no_lll(K, Ker)
      KasFMat = FakeFmpqMat(Ker)
      Ksat = saturate(KasFMat.num)
      Ksat = lll(Ksat)
      onee = one(fmpz)
      for i in 1:k
        #bas[i] = elem_from_mat_row(K, KasFMat.num, i, KasFMat.den)
        bas[i] = elem_from_mat_row(K, Ksat, i, onee)
      end
    end
  end
  return subfield(K, bas, isbasis = true)
end

function fixed_field(K::NfRel, A::Vector{T}; simplify::Bool = true) where {T <: NumFieldMor}
  autos = A

    # Everything is fixed by nothing :)
  if length(autos) == 0
    return K, id_hom(K)
  end

  F = base_field(K)
  a = gen(K)
  n = degree(K)
  ar_mat = Vector{dense_matrix_type(elem_type(F))}()
  v = Vector{elem_type(K)}(undef, n)
  for i in 1:length(autos)
    domain(autos[i]) !== codomain(autos[i]) && throw(error("Maps must be automorphisms"))
    domain(autos[i]) !== K && throw(error("Maps must be automorphisms of K"))
    o = one(K)
    # Compute the image of the basis 1,a,...,a^(n - 1) under autos[i] and write
    # the coordinates in a matrix. This is the matrix of autos[i] with respect
    # to 1,a,...a^(n - 1).
    as = autos[i](a)
    if a == as
      continue
    end
    v[1] = o
    for j in 2:n
      o = o * as
      v[j] = o
    end

    bm = basis_matrix(v)
    # In the generic case just subtract the identity
    m = bm - identity_matrix(F, degree(K))
    push!(ar_mat, m)
  end

  if length(ar_mat) == 0
    return K, id_hom(K)
  else
    bigmatrix = hcat(ar_mat)
    k, Ker = kernel(bigmatrix, side = :left)
    bas = Vector{elem_type(K)}(undef, k)
    for i in 1:k
      bas[i] = elem_from_mat_row(K, Ker, i)
    end
  end
  return subfield(K, bas, isbasis = true)
end

function fixed_field1(K::AnticNumberField, auts::Vector{NfToNfMor})

	auts_new = small_generating_set(auts)
  orderG = _order(auts)
  degree_subfield = divexact(degree(K), orderG)
  #TODO: Experiments to see if this is helpful
  #=
  if length(auts_new) == 1 && is_prime_power(degree_subfield)
    #In this case, one of the coefficients of the minpoly of gen(K)
    #over the subfield is a generator for the subfield.
    #if the given generator was not too large, also this element will be ok
		gens = auts
		if orderG != length(auts)
		  gens = closure(auts, orderG)
    end
    conjs = nf_elem[image_primitive_element(x) for x in gens]
		prim_el = sum(conjs)
		def_pol = minpoly(prim_el)
    if degree(def_pol) != degree_subfield
			conjs1 = copy(conjs)
      while degree(def_pol) != degree_subfield
				for i = 1:length(conjs)
          conjs1[i] *= conjs[i]
				end
				prim_el = sum(conjs1)
       	def_pol = minpoly(prim_el)
			end
		end
    subK = number_field(def_pol, cached = false)[1]
    mp = hom(subK, K, prim_el, check = false)
    return subK, mp
	end
=#
  OK = maximal_order(K)
  if isdefined(OK, :lllO)
    OK = lll(OK)
  end
  M = zero_matrix(FlintZZ, degree(K), degree(K)*length(auts_new))
  v = Vector{nf_elem}(undef, degree(K))
  MOK = basis_matrix(OK, copy = false)
  MOKinv = basis_mat_inv(OK, copy = false)
  for i = 1:length(auts_new)
		v[1] = one(K)
    v[2] = image_primitive_element(auts_new[i])
    for j = 3:degree(K)
      v[j] = v[j-1]*v[2]
		end
    B = basis_matrix(v, FakeFmpqMat)
    mul!(B, B, MOKinv)
    mul!(B, MOK, B)
    @assert isone(B.den)
    for i = 1:degree(K)
      B.num[i, i] -= 1
    end
		_copy_matrix_into_matrix(M, 1, (i-1)*degree(K)+1, B.num)
	end
	@vtime :Subfields 1 rk, Ker = kernel(M, side = :left)
  @assert rk == degree_subfield
  Ker = view(Ker, 1:rk, 1:degree(K))
  @vtime :Subfields 1 Ker = lll(Ker)
	#The kernel is the maximal order of the subfield.
  bas = Vector{nf_elem}(undef, degree_subfield)
	for i = 1:degree_subfield
    bas[i] = elem_from_mat_row(OK, Ker, i).elem_in_nf
	end
  return subfield(K, bas, isbasis = true)
end

################################################################################
#
#  Fixed field as relative extension
#
################################################################################

function fixed_field(K::AnticNumberField, auts::Vector{NfToNfMor}, ::Type{NfRel{nf_elem}}; simplify_subfield::Bool = true)
  F, mF = fixed_field(K, auts)
  if simplify_subfield
    F, mF1 = simplify(F, cached = false)
    mF = mF1*mF
  end
  all_auts = closure(auts, div(degree(K), degree(F)))
  Kx, x = PolynomialRing(K, "x", cached = false)
  p = prod(x-image_primitive_element(y) for y in all_auts)
  def_eq = map_coefficients(x -> haspreimage(mF, x)[2], p)
  L, gL = number_field(def_eq, cached = false, check = false)
  iso = hom(K, L, gL, image_primitive_element(mF), gen(K))
  #I also set the automorphisms...
  autsL = Vector{NfRelToNfRelMor{nf_elem, nf_elem}}(undef, length(all_auts))
  for i = 1:length(autsL)
    autsL[i] = hom(L, L, iso(image_primitive_element(all_auts[i])))
  end
  set_automorphisms!(L, autsL)
  return L, iso
end

redpajama_set_name: RedPajamaGithub


text:
<form>

        <md-input-container flex>
            Nome
            <input name="parentName" ng-model="ctrl.parent.name">
        </md-input-container>

         <md-input-container flex>
            Identidade
            <input name="parentId" ng-model="ctrl.parent.id">
        </md-input-container>
         <md-input-container flex>
            CPF
            <input name="parentCpf" ng-model="ctrl.parent.cpf">
        </md-input-container>

        <md-input-container flex="30">
            <md-datepicker md-open-on-focus ng-model="ctrl.parent.birthDate" md-placeholder="Data de Nascimento"></md-datepicker>
        </md-input-container>
        <md-input-container flex-gt-sm="20">
            Raça
            <md-select name="parentRace" ng-model="ctrl.parent.race">
                <md-option ng-disabled="true">Selecione</md-option>
                <md-option ng-repeat="race in ctrl.races" ng-value="race.value">{{ race.label }}</md-option>
            </md-select>
        </md-input-container>

        <md-input-container class="md-block" layout-gt-sm="row">
            <md-radio-group name="parentReligion" ng-model="ctrl.parent.religion"
                            layout="row">
                <md-radio-button value="Católico">Católico</md-radio-button>
                <md-radio-button value="Não Católico">Não Católico</md-radio-button>
                <md-radio-button value="Outros">Outros</md-radio-button>
            </md-radio-group>
        </md-input-container>
        <md-input-container flex>
            Especifique aqui
            <input name="parentOtherReligion" ng-model="ctrl.parent.otherReligion">
        </md-input-container>

Origem

         <md-input-container flex>
            Estado
            <input name="parentStateOfBirth" ng-model="ctrl.parent.stateOfBirth">
        </md-input-container>
        <md-input-container flex>
            Cidade
            <input name="parentCityOfBirth" ng-model="ctrl.parent.cityOfBirth">
        </md-input-container>

Residência

        <md-input-container flex>
            Estado
            <input name="parentStateOfLiving" ng-model="ctrl.parent.stateOfLiving">
        </md-input-container>
        <md-input-container flex>
            Cidade
            <input name="parentCityOfLiving" ng-model="ctrl.parent.cityOfLiving">
        </md-input-container>

        <md-input-container flex-gt-sm="20">
            Escolaridade
            <md-select name="parentScholarity" ng-model="ctrl.parent.scholarity">
                <md-option ng-disabled="true">Selecione</md-option>
                <md-option ng-value="analfabeto">Analfabeto</md-option>
                <md-option ng-value="primeirograuincompleto">1º Grau Inconpleto</md-option>
                <md-option ng-value="primeirograucompleto">1º Grau Completo</md-option>
                <md-option ng-value="segundograuincompleto">2º Grau Inconpleto</md-option>
                <md-option ng-value="segundograucompleto">2º Grau Completo</md-option>
                <md-option ng-value="SuperiorIncompleto">Superior Incompleto</md-option>
                <md-option ng-value="SuperiorCompleto">Superior Completo</md-option>
            </md-select>
        </md-input-container>
        <md-input-container flex>
            Formação Profissional
            <input name="parentProfessionalSkill" ng-model="ctrl.parent.professionalSkill">
        </md-input-container>

        <md-input-container flex>
            Ocupação
            <input name="parentOcupation" ng-model="ctrl.parent.ocupation">
        </md-input-container>
        <md-input-container  flex-gt-sm="30">
            Situação de Emprego
            <md-select name="parentJobSituation" ng-model="ctrl.parent.jobSituation">
                <md-option ng-disabled="true">Selecione</md-option>
                <md-option ng-value="carteiraassinada">Carteira Assinada</md-option>
                <md-option ng-value="semcarteiraassinada">Sem Carteira Assinada</md-option>
                <md-option ng-value="desempregado">Desempregado</md-option>
                <md-option ng-value="aposentado">Aposentado</md-option>
                <md-option ng-value="outro">Outro</md-option>
            </md-select>
        </md-input-container>

        <md-input-container flex>
            Especifique a Situação de Emprego
            <input name="parentOtherJobSituation" ng-model="ctrl.parent.otherJobSituation">
        </md-input-container>

        <md-input-container flex>
            Campo para Observações necessárias
            <textarea name="notes" ng-model="ctrl.parent.notes">
        </md-input-container>

</form>


text:
all: target/sdk-ec2-examples-1.0.jar

target/sdk-ec2-examples-1.0.jar: src/main/java/com/example/ec2/*.java
	mvn package

clean:
	mvn clean


text:
from flask import make_response, request
from flask_restful import abort
from funcy import project

from redash import models
from redash.wsgi import api
from redash.utils.configuration import ConfigurationContainer, ValidationError
from redash.permissions import require_admin
from redash.query_runner import query_runners, get_configuration_schema_for_type
from redash.handlers.base import BaseResource, get_object_or_404

class DataSourceTypeListAPI(BaseResource):
    @require_admin
    def get(self):
        return [q.to_dict() for q in query_runners.values()]

api.add_org_resource(DataSourceTypeListAPI, '/api/data_sources/types', endpoint='data_source_types')

class DataSourceAPI(BaseResource):
    @require_admin
    def get(self, data_source_id):
        data_source = models.DataSource.get_by_id_and_org(data_source_id, self.current_org)
        return data_source.to_dict(all=True)

    @require_admin
    def post(self, data_source_id):
        data_source = models.DataSource.get_by_id_and_org(data_source_id, self.current_org)
        req = request.get_json(True)

        schema = get_configuration_schema_for_type(req['type'])
        if schema is None:
            abort(400)

        try:
            data_source.options.set_schema(schema)
            data_source.options.update(req['options'])
        except ValidationError:
            abort(400)

        data_source.type = req['type']
        data_source.name = req['name']
        data_source.save()

        return data_source.to_dict(all=True)

    @require_admin
    def delete(self, data_source_id):
        data_source = models.DataSource.get_by_id_and_org(data_source_id, self.current_org)
        data_source.delete_instance(recursive=True)

        return make_response('', 204)

class DataSourceListAPI(BaseResource):
    def get(self):
        if self.current_user.has_permission('admin'):
            data_sources = models.DataSource.all(self.current_org)
        else:
            data_sources = models.DataSource.all(self.current_org, groups=self.current_user.groups)

        response = {}
        for ds in data_sources:
            if ds.id in response:
                continue

            d = ds.to_dict()
            d['view_only'] = all(project(ds.groups, self.current_user.groups).values())
            response[ds.id] = d

        return response.values()

    @require_admin
    def post(self):
        req = request.get_json(True)
        required_fields = ('options', 'name', 'type')
        for f in required_fields:
            if f not in req:
                abort(400)

        schema = get_configuration_schema_for_type(req['type'])
        if schema is None:
            abort(400)

        config = ConfigurationContainer(req['options'], schema)
        if not config.is_valid():
            abort(400)

        datasource = models.DataSource.create_with_group(org=self.current_org,
                                                         name=req['name'],
                                                         type=req['type'],
                                                         options=config)

        return datasource.to_dict(all=True)

api.add_org_resource(DataSourceListAPI, '/api/data_sources', endpoint='data_sources')
api.add_org_resource(DataSourceAPI, '/api/data_sources/<data_source_id>', endpoint='data_source')

class DataSourceSchemaAPI(BaseResource):
    def get(self, data_source_id):
        data_source = get_object_or_404(models.DataSource.get_by_id_and_org, data_source_id, self.current_org)
        schema = data_source.get_schema()

        return schema

api.add_org_resource(DataSourceSchemaAPI, '/api/data_sources/<data_source_id>/schema')


text:
include_recipe "apt"

package "build-essential"
package "gfortran"
package "git-core"
package "libncurses5-dev"
package "libopenblas-dev"
package "m4"

git "/tmp/julia" do
  repository "git://github.com/JuliaLang/julia.git"
  reference "master"
  action :checkout
  not_if { `ls /usr/local/bin`.include?("julia") }
end

template "/tmp/julia/Make.inc" do
  source "Make.inc.erb"
  mode "0644"
  not_if { `ls /usr/local/bin`.include?("julia") }
end

bash "compile julia" do
  code "make"
  cwd "/tmp/julia"
  not_if { `ls /usr/local/bin`.include?("julia") }
end

bash "install julia" do
  code "cp julia /usr/local/bin/ && cp -r usr/* /usr/local/"
  cwd "/tmp/julia"
  not_if { `ls /usr/local/bin`.include?("julia") }
end

directory "/tmp/julia" do
  recursive true
  action :delete
end


text:
using ManagerShop.Domain.System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace ManagerShop.Data.Mapping.System
{
    public class RoleMapper : EntityTypeConfiguration<RoleEntity>
    {

        public RoleMapper()
        {
            //DBのテーブル名設定
            this.ToTable("SYS_Role");
            //DBの主キー設定
            this.HasKey(t => new { t.M_Id });

            //主キーは自動生成ではない(not Identity)
            this.Property(p => p.M_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).HasMaxLength(64).HasColumnType("VARCHAR");
            //別の列設定
            this.Property(p => p.RoleName).IsRequired().HasMaxLength(20).HasColumnType("NVARCHAR");
            this.Property(p => p.Status);

            this.Property(p => p.CreateUserId).HasMaxLength(64).HasColumnType("VARCHAR");
            this.Property(p => p.CreateTime).HasColumnType("datetime");

            this.HasMany(a => a.Userlist).WithMany(t => t.RoleList).Map(m =>
            {
                m.ToTable("SYS_RoleUser");
                m.MapLeftKey("RoleId");
                m.MapRightKey("UserId");
            });

        }
    }
}


text:
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findBottomLeftValue = function (root) {
  let q = [root]
  let res
  while (q.length) {
    const temp = []
    res = q[0]
    while (q.length) {
      const current = q.shift()
      const { left, right } = current
      left && temp.push(left)
      right && temp.push(right)
    }
    q = temp
  }
  return res.val
}

// dfs
findBottomLeftValue = function (root) {
  let res,
    maxDepth = 0
  const helper = (node, depth) => {
    if (!node) return
    helper(node.left, depth + 1)
    helper(node.right, depth + 1)
    if (maxDepth < depth) {
      maxDepth = depth
      res = node
    }
  }
  helper(root, 1)
  return res.val
}


text:
<!DOCTYPE html>

    <title>Heartysoft Solutions Limited</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <meta name="description" content="Twitter bootstrap theme">
    <meta name="author" content="prettystrap">

    <link id="the-story-css-file" href="/css/the-story.min.css" rel="stylesheet" media="screen">
    <link id="the-story-css-file" href="/css/hsft.css" rel="stylesheet" media="screen">

    <link rel="shortcut icon" href="/favicon.ico">

    <meta http-equiv=X-UA-Compatible content=IE=edge>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    Toggle navigation

                </button>
                Heartysoft Solutions Limited
                Heartysoft

HSFT

Services

Technology

            Community

                Blog

Ashic's Blog

ramblings of a technologist...standing on the shoulders of giants and all that...

                Blog Archive

.Net 3.5 SP1...finally

                    .NET

            12 Aug, 2008

        Tweet

Fate has a weird sense of humour. I held out from installing .net 3.5 sp1 all through the CTPs, then beta 1 and beta 2. This is also the first time I restrained myself from installing new stuff (coz simply put, having to uninstall a bunch of betas and patches and what not was getting to me). Well, I couldn't hold out any longer. I downloaded the entire thing. My internet is pretty crap, so I had to download the packages individually, then run a command line switch to download the final files. After that, was a quite long install. It failed. I removed silverlight tools. Tried again. Worked perfectly. I played around for a few hours. Made a few apps. Liked the new stuff quite a bit. And then, at 4 am, I went to bed.

I wake up, and what do I see? Damn you Microsoft...you just released the final .net 3.5 sp1 bits while I was asleep. Couldn't you have done it ONE day earlier or a month later? It HAD to be today, right? Why God, WHY?!?!?!

Ah well...guess I'll be downloading it all over again. And I gues I can forgive MS as the sp1 is actually available as an ISO. That is SO much more convenient to me. Thanks guys.

You can download .net 3.5 sp1 from bootstrapper here. You can download the FULL .net 3.5 sp1 from here. You can download the Visual Studio 2008 sp1 bootstrapper here. And you can download the FULL VS 2008 sp1 from here. Please note that the VS 2008 sp1s contain .net 3.5 sp1. Also note that the bootsrappers will require internet connectivity during installation, while the full versions will not.

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

                © 2014 heartysoft.com | all rights reserved | To top

                    Heartysoft Solutions Limited is registered in England & Wales
                    Company Number 07420608 | VAT Number GB 103 3162 72


text:
<?php

namespace Everon\Test\View;

use Everon\Helper;

class WidgetTest extends \Everon\TestCase
{
    use Helper\Arrays;

    public function __construct($name = NULL, array $data=[], $dataName='')
    {
        parent::__construct($name, $data, $dataName);
        require_once($this->getFixtureDirectory().'View'.DIRECTORY_SEPARATOR.'Main'.DIRECTORY_SEPARATOR.'Widget'.DIRECTORY_SEPARATOR.'MyWidget.php');
    }

    public function testConstructor()
    {
        $ViewWidget = new \Everon\Test\View\Main\Widget\MyAbstractWidget();
        $this->assertInstanceOf('Everon\View\Interfaces\Widget', $ViewWidget);
    }

    /**
     * @dataProvider dataProvider
     */
    public function testRender(\Everon\View\Interfaces\Widget $Widget)
    {
        $result = $Widget->render();
        $this->assertEquals('Template data',$result);
    }

    public function dataProvider()
    {
        $fixture_directory = $this->getFixtureDirectory().'View'.DIRECTORY_SEPARATOR;
        $Factory = $this->buildFactory();
        $Container = $Factory->getDependencyContainer();
        $ViewManager = $Factory->buildViewManager(['php' => '.php'], $fixture_directory, $this->getViewCacheDirectory());
        $Container->register('ViewManager', function() use ($ViewManager) {
            return $ViewManager;
        });

        /**
         * @var \Everon\View\Interfaces\Widget $Widget
         */
        $Widget = $ViewManager->createWidget('MyWidget', 'Everon\Test\View');
        return [
            [$Widget]
        ];
    }

}


text:
<?php

namespace ODE\DatasetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Model
 *
 * @ORM\Table(name="paper_predictions")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class PaperPredictions
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="integer")
     */
    protected $paperId;

    /**
     * @ORM\Column(type="float")
     */
    protected $author1Pred;
}


text:
package commands

import (
	"github.com/docker/machine/cli"
	"github.com/docker/machine/libmachine/log"
)

func cmdStatus(c *cli.Context) {
	if len(c.Args()) != 1 {
		fatal(ErrExpectedOneMachine)
	}

	host := getFirstArgHost(c)
	currentState, err := host.Driver.GetState()
	if err != nil {
		log.Errorf("error getting state for host %s: %s", host.Name, err)
	}

	log.Info(currentState)
}


text:
Welcome to Prize Pool

          <join-form :registration="isRegistered"></join-form>


text:
'use strict';
/*eslint-disable no-shadow*/

var tap = require('tap');
var path = require('path');
var Pattern = require('../src/lib/object_factory').Pattern;
var PatternGraph = require('../src/lib/pattern_graph').PatternGraph;
var testPatternsPath = path.resolve(__dirname, 'files', '_patterns');
var eol = require('os').EOL;
var config = require('./util/patternlab-config.json');

// don't run these tests unless mustache is installed
var engineLoader = require('../src/lib/pattern_engines');
engineLoader.loadAllEngines(config);
if (!engineLoader.mustache) {
  tap.test('Mustache engine not installed, skipping tests.', function (test) {
    test.end();
  });
  return;
}

// fake pattern lab constructor:
// sets up a fake patternlab object, which is needed by the pattern processing
// apparatus.
function fakePatternLab() {
  var fpl = {
    graph: PatternGraph.empty(),
    partials: {},
    patterns: [],
    footer: '',
    header: '',
    listitems: {},
    data: {
      link: {},
    },
    config: config,
    package: {},
  };

  // patch the pattern source so the pattern assembler can correctly determine
  // the "subdir"
  fpl.config.paths.source.patterns = testPatternsPath;

  return fpl;
}

// function for testing sets of partials
function testFindPartials(test, partialTests) {
  test.plan(partialTests.length + 1);

  // setup current pattern from what we would have during execution
  // docs on partial syntax are here:
  // https://patternlab.io/docs/including-patterns/
  var currentPattern = Pattern.create(
    'molecules/testing/test-mol.mustache', // relative path now
    null, // data
    {
      template: partialTests.join(eol),
    }
  );

  // act
  var results = currentPattern.findPartials();

  // assert
  test.equal(results.length, partialTests.length);
  partialTests.forEach(function (testString, index) {
    test.equal(results[index], testString);
  });

  test.end();
}

function testFindPartialsWithStyleModifiers(test, partialTests) {
  test.plan(partialTests.length + 1);

  // setup current pattern from what we would have during execution
  // docs on partial syntax are here:
  // https://patternlab.io/docs/including-patterns/
  var currentPattern = Pattern.create(
    'molecules/testing/test-mol.mustache', // relative path now
    null, // data
    {
      template: partialTests.join(eol),
    }
  );

  // act
  var results = currentPattern.findPartialsWithStyleModifiers();

  // assert
  test.equal(results.length, partialTests.length);
  partialTests.forEach(function (testString, index) {
    test.equal(results[index], testString);
  });

  test.end();
}

function testFindPartialsWithPatternParameters(test, partialTests) {
  test.plan(partialTests.length + 1);

  // setup current pattern from what we would have during execution
  // docs on partial syntax are here:
  // https://patternlab.io/docs/including-patterns/
  var currentPattern = Pattern.create(
    'molecules/testing/test-mol.mustache', // relative path now
    null, // data
    {
      template: partialTests.join(eol),
    }
  );

  // act
  var results = currentPattern.findPartialsWithPatternParameters();

  // assert
  test.equal(results.length, partialTests.length);
  partialTests.forEach(function (testString, index) {
    test.equal(results[index], testString);
  });

  test.end();
}

tap.test('find_pattern_partials finds one simple partial', function (test) {
  testFindPartials(test, ['{{> molecules-comment-header}}']);
});

tap.test(
  'find_pattern_partials finds simple partials under stressed circumstances',
  function (test) {
    testFindPartials(test, [
      '{{>molecules-comment-header}}',
      '{{> ' + eol + ' molecules-comment-header' + eol + '}}',
      '{{>      molecules-weird-spacing      }}',
    ]);
  }
);

tap.test(
  'find_pattern_partials finds one simple verbose partial',
  function (test) {
    testFindPartials(test, ['{{> atoms/global/test }}']);
  }
);

tap.test(
  'find_pattern_partials finds partials with parameters',
  function (test) {
    testFindPartials(test, [
      '{{> molecules-single-comment(description: true) }}',
      '{{> molecules-single-comment(description: 42) }}',
      "{{> molecules-single-comment(description: '42') }}",
      '{{> molecules-single-comment(description: "42") }}',
      "{{> molecules-single-comment(description: 'test', anotherThing: 'retest') }}",
      '{{> molecules-single-comment(description: false, anotherThing: "retest") }}',
      '{{> molecules-single-comment(description:"A life is like a "garden". Perfect moments can be had, but not preserved, except in memory.") }}',
    ]);
  }
);

tap.test(
  'find_pattern_partials finds simple partials with style modifiers',
  function (test) {
    testFindPartials(test, [
      '{{> molecules-single-comment:foo }}',
      '{{> molecules-single-comment:foo|bar }}',
    ]);
  }
);

tap.test('find_pattern_partials finds mixed partials', function (test) {
  testFindPartials(test, [
    '{{> molecules-single-comment:foo(description: "test", anotherThing: true) }}',
    '{{> molecules-single-comment:foo|bar(description: true) }}',
  ]);
});

tap.test(
  'find_pattern_partials finds one simple partial with styleModifier',
  function (test) {
    testFindPartialsWithStyleModifiers(test, [
      '{{> molecules-comment-header:test}}',
    ]);
  }
);

tap.test(
  'find_pattern_partials finds partial with many styleModifiers',
  function (test) {
    testFindPartialsWithStyleModifiers(test, [
      '{{> molecules-comment-header:test|test2|test3}}',
    ]);
  }
);

tap.test(
  'find_pattern_partials finds partials with differing styleModifiers',
  function (test) {
    testFindPartialsWithStyleModifiers(test, [
      '{{> molecules-comment-header:test|test2|test3}}',
      '{{> molecules-comment-header:foo-1}}',
      '{{> molecules-comment-header:bar_1}}',
    ]);
  }
);

tap.test(
  'find_pattern_partials finds partials with styleModifiers when parameters present',
  function (test) {
    testFindPartialsWithStyleModifiers(test, [
      '{{> molecules-comment-header:test|test2|test3(description: true)}}',
      "{{> molecules-comment-header:foo-1(description: 'foo')}}",
      "{{> molecules-comment-header:bar_1(descrition: 'bar', anotherThing: 10102010) }}",
    ]);
  }
);

tap.test(
  'find_pattern_partials_with_parameters finds one simple partial with parameters',
  function (test) {
    testFindPartialsWithPatternParameters(test, [
      "{{> molecules-comment-header(description: 'test')}}",
    ]);
  }
);

tap.test(
  'find_pattern_partials_with_parameters finds partials with parameters',
  function (test) {
    testFindPartialsWithPatternParameters(test, [
      '{{> molecules-single-comment(description: true) }}',
      '{{> molecules-single-comment(description: 42) }}',
      "{{> molecules-single-comment(description: '42') }}",
      '{{> molecules-single-comment(description: "42") }}',
      "{{> molecules-single-comment(description: 'test', anotherThing: 'retest') }}",
      '{{> molecules-single-comment(description: false, anotherThing: "retest") }}',
      '{{> molecules-single-comment(description:"A life is like a "garden". Perfect moments can be had, but not preserved, except in memory.") }}',
    ]);
  }
);

tap.test(
  'find_pattern_partials finds partials with parameters when styleModifiers present',
  function (test) {
    testFindPartialsWithPatternParameters(test, [
      '{{> molecules-comment-header:test|test2|test3(description: true)}}',
      "{{> molecules-comment-header:foo-1(description: 'foo')}}",
      "{{> molecules-comment-header:bar_1(descrition: 'bar', anotherThing: 10102010) }}",
    ]);
  }
);


text:
layout: post
title: watir-webdriver 0.4.1
date: 2011-12-13 20:22
author: bpettichord
comments: true
tags: [Releases]
---

watir-webdriver 0.4.1 has been released.

Major changes since the last release:

deprecate element{,s}_by_xpath

Install it with

gem install watir-webdriver

As usual:

see build history at travis-ci.org/#!/jarib/watir-webdriver/builds (wait for a few seconds until older builds appear)

see all the changes at github.com/jarib/watir-webdriver/commits/master

updated API documentation is at rubydoc.info/gems/watir-webdriver


text:
Individual assignment 6
=======================

This is the directory where students have to upload their materials related to the 6th individual assignment.

# GitHub structure

* Each student will create a directory in github for uploading all the materials of the hands-on (e.g., /Assignment6/<Student Name>/).

# Student directory contents

* /queries.sparql - An SPARQL document with the queries defined.


text:
<!DOCTYPE html>
<!--
 | Copyright 2017 The Cobalt Authors. All Rights Reserved.
 |
 | Licensed under the Apache License, Version 2.0 (the "License");
 | you may not use this file except in compliance with the License.
 | You may obtain a copy of the License at
 |
 |     http://www.apache.org/licenses/LICENSE-2.0
 |
 | Unless required by applicable law or agreed to in writing, software
 | distributed under the License is distributed on an "AS IS" BASIS,
 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | See the License for the specific language governing permissions and
 | limitations under the License.
 -->
<html>
<head>
  <title>Encrypted Media Extensions (16 March 2017) Demo</title>
  <style>
    body {
      background-color: white;
    }
    video {
      height: 240px;
      width: 426px;
    }
  </style>
</head>

<body>
  <video></video>
  <script src="eme-demo.js"></script>
</body>
</html>


text:
typedef enum {
    SPR_CONNECTING   = 0,
    SPR_OPEN         = 1,
    SPR_CLOSING      = 2,
    SPR_CLOSED       = 3,
} SPRReadyState;

typedef enum SPRStatusCode : NSInteger {
    SPRStatusCodeNormal = 1000,
    SPRStatusCodeGoingAway = 1001,
    SPRStatusCodeProtocolError = 1002,
    SPRStatusCodeUnhandledType = 1003,
    // 1004 reserved.
    SPRStatusNoStatusReceived = 1005,
    // 1004-1006 reserved.
    SPRStatusCodeInvalidUTF8 = 1007,
    SPRStatusCodePolicyViolated = 1008,
    SPRStatusCodeMessageTooBig = 1009,
} SPRStatusCode;

@class SPRWebSocket;

extern NSString *const SPRWebSocketErrorDomain;
extern NSString *const SPRHTTPResponseErrorKey;

#pragma mark - SPRWebSocketDelegate

@protocol SPRWebSocketDelegate;

#pragma mark - SPRWebSocket

@interface SPRWebSocket : NSObject <NSStreamDelegate>

@property (nonatomic, weak) id <SPRWebSocketDelegate> delegate;

@property (nonatomic, readonly) SPRReadyState readyState;
@property (nonatomic, readonly, retain) NSURL *url;

// This returns the negotiated protocol.
// It will be nil until after the handshake completes.
@property (nonatomic, readonly, copy) NSString *protocol;

// Protocols should be an array of strings that turn into Sec-WebSocket-Protocol.
- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols;
- (id)initWithURLRequest:(NSURLRequest *)request;

// Some helper constructors.
- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols;
- (id)initWithURL:(NSURL *)url;

// Delegate queue will be dispatch_main_queue by default.
// You cannot set both OperationQueue and dispatch_queue.
- (void)setDelegateOperationQueue:(NSOperationQueue*) queue;
- (void)setDelegateDispatchQueue:(dispatch_queue_t) queue;

// By default, it will schedule itself on +[NSRunLoop SPR_networkRunLoop] using defaultModes.
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;

// SPRWebSockets are intended for one-time-use only.  Open should be called once and only once.
- (void)open;

- (void)close;
- (void)closeWithCode:(NSInteger)code reason:(NSString *)reason;

// Send a UTF8 String or Data.
- (void)send:(id)data;

// Send Data (can be nil) in a ping message.
- (void)sendPing:(NSData *)data;

@end

#pragma mark - SPRWebSocketDelegate

@protocol SPRWebSocketDelegate <NSObject>

// message will either be an NSString if the server is using text
// or NSData if the server is using binary.
- (void)webSocket:(SPRWebSocket *)webSocket didReceiveMessage:(id)message;

@optional

- (void)webSocketDidOpen:(SPRWebSocket *)webSocket;
- (void)webSocket:(SPRWebSocket *)webSocket didFailWithError:(NSError *)error;
- (void)webSocket:(SPRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
- (void)webSocket:(SPRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;

@end

#pragma mark - NSURLRequest (CertificateAdditions)

@interface NSURLRequest (CertificateAdditions)

@property (nonatomic, retain, readonly) NSArray *SPR_SSLPinnedCertificates;

@end

#pragma mark - NSMutableURLRequest (CertificateAdditions)

@interface NSMutableURLRequest (CertificateAdditions)

@property (nonatomic, retain) NSArray *SPR_SSLPinnedCertificates;

@end

#pragma mark - NSRunLoop (SPRWebSocket)

@interface NSRunLoop (SPRWebSocket)

+ (NSRunLoop *)SPR_networkRunLoop;

@end


text:
layout: default
title: UnderTasker.
---

UnderTasker // By Tyler Rilling

        View Source »
        Download »

Helping you bootstrap your static web app using Gulp, jekyll, & Yarn.


text:
from pypred import optimizer, ast

class TestOptimizer(object):
    def test_no_pass(self):
        "Should do nothing"
        assert None == optimizer.optimize(None, max_pass=0, min_change=1)

    def test_min_change(self):
        t = ast.Constant(True)
        f = ast.Constant(False)
        left = ast.LogicalOperator('or', t, f)
        right = ast.LogicalOperator('and', t, f)
        r = ast.LogicalOperator('or', left, right)

        # First pass will only replace the left and right
        # with constants, but will not cause 3 changes.
        r = optimizer.optimize(r, max_pass=10, min_change=3)

        assert isinstance(r, ast.LogicalOperator)
        assert isinstance(r.left, ast.Constant)
        assert r.left.value == True
        assert isinstance(r.right, ast.Constant)
        assert r.right.value == False

    def test_max_pass(self):
        t = ast.Constant(True)
        f = ast.Constant(False)
        left = ast.LogicalOperator('or', t, f)
        right = ast.LogicalOperator('and', t, f)
        r = ast.LogicalOperator('or', left, right)

        # First pass will only replace the left and right
        # with constants, but will not cause replace root
        r = optimizer.optimize(r, max_pass=1, min_change=1)

        assert isinstance(r, ast.LogicalOperator)
        assert isinstance(r.left, ast.Constant)
        assert r.left.value == True
        assert isinstance(r.right, ast.Constant)
        assert r.right.value == False

    def test_and_replace(self):
        "Test AND -> False"
        t = ast.Constant(True)
        f = ast.Constant(False)
        n = ast.LogicalOperator('and', t, f)

        # Should reduce to False
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == False

        # Should reduce to False
        n = ast.LogicalOperator('and', f, t)
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == False

    def test_or_replace(self):
        "Test OR -> True"
        t = ast.Constant(True)
        f = ast.Constant(False)
        n = ast.LogicalOperator('or', t, f)

        # Should reduce to True
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == True

        # Should reduce to True
        n = ast.LogicalOperator('or', f, t)
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == True

    def test_negate(self):
        "Test negation static analysis"
        t = ast.Constant(True)
        f = ast.Constant(False)
        n = ast.NegateOperator(t)

        # Should reduce to False
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == False

        # Should reduce to True
        n = ast.NegateOperator(f)
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == True

    def test_push_result(self):
        "Test false push result"
        f = ast.Constant(False)
        n = ast.PushResult(None, f)

        # Should reduce to False
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == False

    def test_both_all_false(self):
        "Test removing a both node when both sides are false"
        f = ast.Constant(False)
        n = ast.Both(f, f)

        # Should reduce to False
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == False

    def test_both_dead(self):
        "Test removing a both node when one side is dead"
        t = ast.Constant(True)
        f = ast.Constant(False)

        # Should reduce to left
        n = ast.Both(t, f)
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert r is t

        # Should reduce to right
        n = ast.Both(f, t)
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert r is t

    def test_or_dead(self):
        "Tests removing OR with dead branch"
        f = ast.Constant(False)
        l = ast.Literal('foo')
        v = ast.Number(42)
        cmp = ast.CompareOperator('=', l, v)
        n = ast.LogicalOperator('or', f, cmp)

        # Should reduce to to the compare
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert r is cmp

    def test_or_dead_right(self):
        "Tests removing OR with dead branch, right side"
        f = ast.Constant(False)
        l = ast.Literal('foo')
        v = ast.Number(42)
        cmp = ast.CompareOperator('=', l, v)
        n = ast.LogicalOperator('or', cmp, f)

        # Should reduce to to the compare
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert r is cmp

    def test_and_dead(self):
        "Tests removing AND with dead branch"
        t = ast.Constant(True)
        l = ast.Literal('foo')
        v = ast.Number(42)
        cmp = ast.CompareOperator('=', l, v)
        n = ast.LogicalOperator('and', t, cmp)

        # Should reduce to to the compare
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert r is cmp

    def test_and_dead_right(self):
        "Tests removing AND with dead branch, right side"
        t = ast.Constant(True)
        l = ast.Literal('foo')
        v = ast.Number(42)
        cmp = ast.CompareOperator('=', l, v)
        n = ast.LogicalOperator('and', cmp, t)

        # Should reduce to to the compare
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert r is cmp

    def test_branch_false_dead(self):
        "Test branch with the false branch being dead"
        t = ast.Constant(True)
        f = ast.Constant(False)
        l = ast.Literal('foo')
        v = ast.Number(42)
        cmp = ast.CompareOperator('=', l, v)
        n = ast.Branch(t, cmp, f)

        # Should reduce to to the compare
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert r is cmp

    def test_branch_true_dead(self):
        "Test branch with the false branch being dead"
        t = ast.Constant(True)
        f = ast.Constant(False)
        l = ast.Literal('foo')
        v = ast.Number(42)
        cmp = ast.CompareOperator('=', l, v)
        n = ast.Branch(f, t, cmp)

        # Should reduce to to the compare
        c, r = optimizer.optimization_pass(n)
        assert c == 1
        assert r is cmp

    def test_empty_set(self):
        "Test removing an empty literal set"
        s = ast.LiteralSet([])
        c, r = optimizer.optimization_pass(s)
        assert c == 1
        assert isinstance(r, ast.Empty)

    def test_empty_contains(self):
        "Tests removing an Empty contains X"
        e = ast.Empty()
        v = ast.Literal('foo')
        cn = ast.ContainsOperator(e, v)
        c, r = optimizer.optimization_pass(cn)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == False

    def test_undef_contains(self):
        "Tests removing an Empty contains X"
        u = ast.Undefined()
        v = ast.Literal('foo')
        cn = ast.ContainsOperator(u, v)
        c, r = optimizer.optimization_pass(cn)
        assert c == 1
        assert isinstance(r, ast.Constant)
        assert r.value == False


text:
package org.apache.activemq.transport.tcp;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import javax.net.SocketFactory;

import org.apache.activemq.CombinationTestSupport;
import org.apache.activemq.command.WireFormatInfo;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.transport.Transport;
import org.apache.activemq.transport.TransportAcceptListener;
import org.apache.activemq.transport.TransportFactory;
import org.apache.activemq.transport.TransportListener;
import org.apache.activemq.transport.TransportServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InactivityMonitorTest extends CombinationTestSupport implements TransportAcceptListener {
    private static final Logger LOG = LoggerFactory.getLogger(InactivityMonitorTest.class);

    public Runnable serverRunOnCommand;
    public Runnable clientRunOnCommand;

    private TransportServer server;
    private Transport clientTransport;
    private Transport serverTransport;
    private int serverPort;

    private final AtomicInteger clientReceiveCount = new AtomicInteger(0);
    private final AtomicInteger clientErrorCount = new AtomicInteger(0);
    private final AtomicInteger serverReceiveCount = new AtomicInteger(0);
    private final AtomicInteger serverErrorCount = new AtomicInteger(0);

    private final AtomicBoolean ignoreClientError = new AtomicBoolean(false);
    private final AtomicBoolean ignoreServerError = new AtomicBoolean(false);

    protected void setUp() throws Exception {
        super.setUp();
        startTransportServer();
    }

    /**
     * @throws Exception
     * @throws URISyntaxException
     */
    private void startClient() throws Exception, URISyntaxException {
        clientTransport = TransportFactory.connect(new URI("tcp://localhost:" + serverPort + "?trace=true&wireFormat.maxInactivityDuration=1000"));
        clientTransport.setTransportListener(new TransportListener() {
            public void onCommand(Object command) {
                clientReceiveCount.incrementAndGet();
                if (clientRunOnCommand != null) {
                    clientRunOnCommand.run();
                }
            }

            public void onException(IOException error) {
                if (!ignoreClientError.get()) {
                    LOG.info("Client transport error:");
                    error.printStackTrace();
                    clientErrorCount.incrementAndGet();
                }
            }

            public void transportInterupted() {
            }

            public void transportResumed() {
            }
        });
        clientTransport.start();
    }

    /**
     * @throws IOException
     * @throws URISyntaxException
     * @throws Exception
     */
    private void startTransportServer() throws IOException, URISyntaxException, Exception {
        server = TransportFactory.bind(new URI("tcp://localhost:0?trace=true&wireFormat.maxInactivityDuration=1000"));
        server.setAcceptListener(this);
        server.start();

        serverPort = server.getSocketAddress().getPort();
    }

    protected void tearDown() throws Exception {
        ignoreClientError.set(true);
        ignoreServerError.set(true);
        try {
            if (clientTransport != null) {
                clientTransport.stop();
            }
            if (serverTransport != null) {
                serverTransport.stop();
            }
            if (server != null) {
                server.stop();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        super.tearDown();
    }

    public void onAccept(Transport transport) {
        try {
            LOG.info("[" + getName() + "] Server Accepted a Connection");
            serverTransport = transport;
            serverTransport.setTransportListener(new TransportListener() {
                public void onCommand(Object command) {
                    serverReceiveCount.incrementAndGet();
                    if (serverRunOnCommand != null) {
                        serverRunOnCommand.run();
                    }
                }

                public void onException(IOException error) {
                    if (!ignoreClientError.get()) {
                        LOG.info("Server transport error:", error);
                        serverErrorCount.incrementAndGet();
                    }
                }

                public void transportInterupted() {
                }

                public void transportResumed() {
                }
            });
            serverTransport.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onAcceptError(Exception error) {
        LOG.trace(error.toString());
    }

    public void testClientHang() throws Exception {

        //
        // Manually create a client transport so that it does not send KeepAlive
        // packets.
        // this should simulate a client hang.
        clientTransport = new TcpTransport(new OpenWireFormat(), SocketFactory.getDefault(), new URI("tcp://localhost:" + serverPort), null);
        clientTransport.setTransportListener(new TransportListener() {
            public void onCommand(Object command) {
                clientReceiveCount.incrementAndGet();
                if (clientRunOnCommand != null) {
                    clientRunOnCommand.run();
                }
            }

            public void onException(IOException error) {
                if (!ignoreClientError.get()) {
                    LOG.info("Client transport error:");
                    error.printStackTrace();
                    clientErrorCount.incrementAndGet();
                }
            }

            public void transportInterupted() {
            }

            public void transportResumed() {
            }
        });
        clientTransport.start();
        WireFormatInfo info = new WireFormatInfo();
        info.setVersion(OpenWireFormat.DEFAULT_VERSION);
        info.setMaxInactivityDuration(1000);
        clientTransport.oneway(info);

        assertEquals(0, serverErrorCount.get());
        assertEquals(0, clientErrorCount.get());

        // Server should consider the client timed out right away since the
        // client is not hart beating fast enough.
        Thread.sleep(6000);

        assertEquals(0, clientErrorCount.get());
        assertTrue(serverErrorCount.get() > 0);
    }

    public void testNoClientHang() throws Exception {
        startClient();

        assertEquals(0, serverErrorCount.get());
        assertEquals(0, clientErrorCount.get());

        Thread.sleep(4000);

        assertEquals(0, clientErrorCount.get());
        assertEquals(0, serverErrorCount.get());
    }

    /**
     * Used to test when a operation blocks. This should not cause transport to
     * get disconnected.
     *
     * @throws Exception
     * @throws URISyntaxException
     */
    public void initCombosForTestNoClientHangWithServerBlock() throws Exception {

        startClient();

        addCombinationValues("clientInactivityLimit", new Object[] {Long.valueOf(1000)});
        addCombinationValues("serverInactivityLimit", new Object[] {Long.valueOf(1000)});
        addCombinationValues("serverRunOnCommand", new Object[] {new Runnable() {
            public void run() {
                try {
                    LOG.info("Sleeping");
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                }
            }
        }});
    }

    public void testNoClientHangWithServerBlock() throws Exception {

        startClient();

        assertEquals(0, serverErrorCount.get());
        assertEquals(0, clientErrorCount.get());

        Thread.sleep(4000);

        assertEquals(0, clientErrorCount.get());
        assertEquals(0, serverErrorCount.get());
    }

}


text:
.. python-aqi documentation master file, created by
   sphinx-quickstart on Sun Sep 21 13:55:04 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

.. include:: ../README.rst

.. toctree::
   :maxdepth: 2

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
//
//  GUI_MenuBar.hpp
//  GUI_App
//
//  Created by Panutat Tejasen on 21/1/2562 BE.
//  Copyright © 2562 Jimmy Software Co., Ltd. All rights reserved.
//

#ifndef GUI_MenuBar_hpp
#define GUI_MenuBar_hpp

#include <stdio.h>

#include <stdio.h>
#include "GUI_View.h"
#include "GUI_Label.h"
#include "GUI_Menu.h"
#include "GUI_PopupView.h"
#include "GUI_ScrollView.h"

class GUI_PopupMenu : public GUI_PopupView {
protected:
    GUI_ScrollView *scrollView;
public:
    static GUI_PopupMenu *create( GUI_View *parent, const char *title, int x=0, int y=0, int width=0, int height=0,
                            std::function<void(GUI_View*)>callbackFunction = NULL );
    GUI_PopupMenu(GUI_View *parent, const char *title, int x=0, int y=0, int width=0, int height=0,
             std::function<void(GUI_View*)>callbackFunction = NULL );
    virtual ~GUI_PopupMenu();

    virtual void add(GUI_MenuItem* child);
    virtual void remove(GUI_MenuItem* child);

    virtual GUI_MenuItem* addSimpleMenu( const char *title, bool separator=false );

    GUI_MenuItem *selectedItem;
	std::vector<GUI_MenuItem *>menuItems;
};

class GUI_MenuBarItem : public GUI_View {
protected:
    GUI_PopupMenu *popupMenu;
public:
    static GUI_MenuBarItem *create( GUI_View *parent, const char *title, int x=0, int y=0, int width=0, int height=0,
                                std::function<void(GUI_View*)>callbackFunction = NULL );
    GUI_MenuBarItem(GUI_View *parent, const char *title, int x=0, int y=0, int width=0, int height=0,
                 std::function<void(GUI_View*)>callbackFunction = NULL );
    virtual ~GUI_MenuBarItem();

    void setPopupMenu( GUI_PopupMenu *menu );
    GUI_PopupMenu *getPopupMenu() { return popupMenu; };

    GUI_PopupMenu *addPopupMenu(GUI_View *parent);
};

class GUI_MenuBar : public GUI_View {
protected:
    std::vector<GUI_MenuBarItem *>menuItems;
public:
    static GUI_MenuBar *create( GUI_View *parent, const char *title,
                              std::function<void(GUI_View*)>callbackFunction = NULL );
    GUI_MenuBar(GUI_View *parent, const char *title,
               std::function<void(GUI_View*)>callbackFunction = NULL );
    virtual ~GUI_MenuBar();

    virtual void add(GUI_MenuBarItem* child);
    virtual void remove(GUI_MenuBarItem* child);

    GUI_MenuBarItem * addSimpleMenu( const char *title );
    GUI_MenuBarItem * addPopupMenu( const char *title, GUI_View *parentView, std::function<void(GUI_View*)>ucb = NULL);
    GUI_MenuItem *selectedItem;
};

#endif /* GUI_MenuBar_hpp */


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Concept',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('category', models.CharField(max_length=200)),
                ('label', models.CharField(max_length=200)),
                ('description', models.TextField(blank=True)),
            ],
        ),
        migrations.CreateModel(
            name='Idea',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('label', models.CharField(max_length=200)),
                ('description', models.TextField()),
                ('created_date', models.DateTimeField()),
            ],
        ),
        migrations.CreateModel(
            name='Inspiration',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('label', models.CharField(max_length=200)),
                ('category', models.CharField(blank=True, max_length=200)),
                ('description', models.TextField(blank=True)),
                ('idea', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ideas.Idea')),
            ],
        ),
    ]


text:
<resources>
    <string name="app_name">Kadecot (Device Connect Device Plug-in)</string>

    <string name="summary_title">[1/4] 概要</string>
    <string name="summary_body">Kadecot プラグインを動作させるために、以下の手順でKadecotの設定を行います。\n\n・Kadecotインストール\n\n・Kadecotサーバー起動確認</string>
    <string name="install_kadecot_title">[2/4] Kadecotインストール</string>
    <string name="install_kadecot_body">本デバイスプラグインは家電連携のコンセプトを実証する目的で作成しております。\n\n動作させるためには最新のkadecotアプリがスマートデバイスにインストールされていることが必須となります。\n\nインストールされていない場合はGoogle Playよりインストールしてください。</string>
    <string name="not_install_kadecot_body">Kadecotがインストールされていません。</string>
    <string name="installed_kadecot_body">Kadecotはインストール済みです。</string>
    <string name="check_kadecot_server_title">[3/4] Kadecotサーバー起動確認</string>
    <string name="check_kadecot_server_body">Kadecotを起動して「SERVER ON」と表示されているか確認してください。\n\n「SERVER OFF」の時はスライドボタンをタップして「SERVER ON」としてください。</string>
    <string name="server_switch_contend_description">Kadecot Server Switch.</string>
    <string name="launch_kadecot_button">Kadecot起動</string>
    <string name="finish_title">[4/4] 設定完了</string>
    <string name="finish_body">以上で、Kadecotの設定が完了しました。</string>
    <string name="kadecot_package_name">com.sonycsl.Kadecot</string>
</resources>


text:
var GameObject2D = function(mesh) {
  this.alive = true;
  this.mesh = mesh;

  this.position = new Vec3(0, 0, 0);
  this.orientation = 0;
  this.speedCircular = 0.5;
  this.scale = new Vec3(1, 1, 1);

  this.modelMatrix = new Mat4();
  this.updateModelTransformation();

  this.move = function (dt) {

  }
};

GameObject2D.prototype.updateModelTransformation =
                              function(){
  this.modelMatrix.set().
    scale(this.scale).
    rotate(this.orientation).
    translate(this.position);

};

GameObject2D.prototype.hitByProjectile = function () {

}

GameObject2D.prototype.draw = function(camera){

  Material.shared.modelViewProjMatrix.set().
    mul(this.modelMatrix).
    mul(camera.viewProjMatrix);

  this.mesh.draw();
};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.tremolosecurity.unison</groupId>
		<artifactId>unison</artifactId>
		<version>1.0.32</version>
	</parent>
	<artifactId>unison-applications-argocd</artifactId>
	<name>unison-applications-argocd</name>
	<dependencies>
		<dependency>
			<groupId>com.tremolosecurity.unison</groupId>
			<artifactId>unison-sdk</artifactId>
			<version>${openunison.version}</version>
		</dependency>
		<dependency>
			<groupId>com.tremolosecurity.unison</groupId>
			<artifactId>unison-applications-openshift3</artifactId>
			<version>${openunison.version}</version>
		</dependency>
	</dependencies>
</project>


text:
package symtable;

// corresponde a uma declaraco de mtodo na tabela de smbolos
public class EntryMethod extends EntryTable {
    public EntryTable type; // tipo de retorno do mtodo
    public int dim; // nmero de dimenses do retorno
    public EntryRec param; // tipo dos parmetros
    public int totallocals; // nmero de variveis locais
    public int totalstack; // tamanho da pilha necessria
    public boolean fake; // true se  um falso construtor
    public boolean hassuper; // true se mtodo possui chamada super

    // cria elemento para inserir na tabela
    public EntryMethod(String n, EntryTable p, int d, EntryRec r) {
        name = n;
        type = p;
        dim = d;
        param = r;
        totallocals = 0;
        totalstack = 0;
        fake = false;
        hassuper = false;
    }

    public EntryMethod(String n, EntryTable p, boolean b) {
        name = n;
        type = p;
        dim = 0;
        param = null;
        totallocals = 0;
        totalstack = 0;
        fake = b;
        hassuper = false;
    }

    public String dscJava() {
        String s = strDim(dim);
        s += type.dscJava();

        return s;
    }
}


text:
var LanceTrack;
(function (LanceTrack) {
    function datesFactory() {
        return new Dates();
    }
    LanceTrack.datesFactory = datesFactory;
    var Dates = (function () {
        function Dates() {
        }
        Dates.prototype.format = function (date, format) {
            return this.parseMoment(date).format(format || Dates.DateFormat);
        };
        Dates.prototype.formatDay = function (date) {
            return this.parseMoment(date).format(Dates.DayFormat);
        };
        Dates.prototype.parse = function (date) {
            return this.parseMoment(date).toDate();
        };
        Dates.prototype.startOfCurrentWeek = function () {
            return this.format(moment().startOf("week"));
        };
        Dates.prototype.endOfCurrentWeek = function () {
            return this.format(moment().endOf("week"));
        };
        Dates.prototype.startOfWeek = function (date) {
            return this.format(this.parseMoment(date).startOf("week"));
        };
        Dates.prototype.previousWeek = function (date) {
            var d = this.parseMoment(date).add(-1, "week");
            return this.format(d);
        };
        Dates.prototype.nextWeek = function (date) {
            var d = this.parseMoment(date).add(1, "week");
            return this.format(d);
        };
        Dates.prototype.endOfWeek = function (date) {
            return this.format(this.parseMoment(date).endOf("week"));
        };
        Dates.prototype.allDateInWeek = function (date) {
            return this.allDateInRange(this.startOfWeek(date), this.endOfWeek(date));
        };
        Dates.prototype.allDateInRange = function (startDate, endDate) {
            var range = this.getValidRange(startDate, endDate);
            var start = moment(range.start);
            var end = moment(range.end);
            var result = [];
            while (start.unix() <= end.unix()) {
                result.push(start.clone().toDate());
                start.add(1, "day");
            }
            return result;
        };
        Dates.prototype.now = function () {
            return this.format(moment());
        };
        /*
         * From two dates selects max and uses it as range end.
         * Then makes range 31 day long max.
         *
         */
        Dates.prototype.getValidRange = function (startDate, endDate) {
            var d1 = this.parseMoment(startDate);
            var d2 = this.parseMoment(endDate);
            var end = moment.max([d1, d2]);
            var start = moment.max([
                end.clone().subtract(31, "day"),
                moment.min([d1, d2])
            ]);
            return {
                start: start.toDate(),
                end: end.toDate()
            };
        };
        Dates.prototype.eq = function (date1, date2) {
            var d1 = moment(this.parse(date1));
            var d2 = moment(this.parse(date2));
            return d1.year() === d2.year() && d1.dayOfYear() === d2.dayOfYear();
        };
        Dates.prototype.parseMoment = function (date) {
            if (moment.isMoment(date))
                return date;
            if (typeof date == "string")
                return moment(date, Dates.DateFormat);
            return moment(date);
        };
        Dates.DateFormat = "YYYY-MM-DD";
        Dates.DayFormat = "ddd, DD MMM";
        return Dates;
    })();
    LanceTrack.Dates = Dates;
})(LanceTrack || (LanceTrack = {}));
//# sourceMappingURL=dateService.js.map


text:
/*
	Overflow by HTML5 UP
	html5up.net | @ajlkn
	Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/

(function($) {

	var settings = {

		// Full screen header?
        fullScreenHeader: true,

	};

	skel.breakpoints({
		wide: '(max-width: 1680px)',
		normal: '(max-width: 1080px)',
		narrow: '(max-width: 840px)',
		mobile: '(max-width: 736px)'
	});

	$(function() {

		var	$window = $(window),
			$body = $('body');

		if (skel.vars.touch) {

			$body.addClass('is-scroll');

		}

		// Disable animations/transitions until the page has loaded.
        $body.addClass('is-loading');

		function centerProjectImages() {
            // Center the images inside of the outer container
            $('.right-image').each(function(index, image) {
                var $image = $(image);

                $image.css('left', -(($image.width() - $image.parent().width()) / 2));
            });

            $('.left-image').each(function(index, image) {
                var $image = $(image);

                $image.css('right', -(($image.width() - $image.parent().width()) / 2));
            });
        }

        function configurePortfolioBox() {
		    // Match the overlay portfolio box's padding with the parent's to prevent overflow
		    $('.portfolio-box').css('padding', $('.portfolio-box').parent().css('padding'));

		    // Align each portfolio box's text vertically
            $('.gallery p').each(function(index, text) {
                var $text = $(text);

                $text.css('margin-top', ($text.parent().height() - $text.height()) / 2)
            });
        }

        $window.on('load', function() {
            $body.removeClass('is-loading');

            centerProjectImages();
            configurePortfolioBox();
        });

        $window.on('resize', function() {
            centerProjectImages();
            configurePortfolioBox();
        });

		// CSS polyfills (IE<9).
        if (skel.vars.IEVersion < 9)
            $(':last-child').addClass('last-child');

		// Fix: Placeholder polyfill.
        $('form').placeholder();

		// Prioritize "important" elements on mobile.
        skel.on('+mobile -mobile', function() {
            $.prioritize(
                '.important\\28 mobile\\29',
                skel.breakpoint('mobile').active
            );
        });

		// Scrolly links.
        $('.scrolly-middle').scrolly({
            speed: 1000,
            anchor: 'middle'
        });

        $('.scrolly').scrolly({
            speed: 1000,
            offset: function() { return (skel.breakpoint('mobile').active ? 70 : 190); }
        });

		// Full screen header.
        if (settings.fullScreenHeader) {

            var $header = $('#header');

            if ($header.length > 0) {

                var $header_header = $header.find('header');

                $window
                    .on('resize.overflow_fsh', function() {

                        if (skel.breakpoint('mobile').active)
                            $header.css('padding', '');
                        else {

                            var p = Math.max(192, ($window.height() - $header_header.outerHeight()) / 2);
                            $header.css('padding', p + 'px 0 ' + p + 'px 0');

                        }

                    })
                    .trigger('resize.overflow_fsh');

                $window.load(function() {
                    $window.trigger('resize.overflow_fsh');
                });

            }

        }

	});

})(jQuery);


text:
#import "NSObject-Protocol.h"

@protocol SFAirDropBrowserDelegate <NSObject>
- (void)browserDidChangePeople:(id)arg1;
- (void)browser:(id)arg1 didDeletePersonAtIndex:(unsigned long long)arg2;
- (void)browser:(id)arg1 didInsertPersonAtIndex:(unsigned long long)arg2;
- (void)browserWillChangePeople:(id)arg1;
@end


text:
app.models.Logout = Backbone.Model.extend({
  urlRoot: '/logout'
});


text:
package com.elmakers.mine.bukkit.utility.platform;

import java.util.Collection;

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;

import com.elmakers.mine.bukkit.mob.GoalConfiguration;
import com.elmakers.mine.bukkit.mob.GoalType;

public interface MobUtils {
    boolean removeGoals(Entity entity);

    boolean removeGoal(Entity entity, GoalType goalType);

    Collection<String> getGoalDescriptions(Entity entity);

    boolean addGoal(Entity entity, GoalType goalType, int priority, ConfigurationSection config);

    boolean addGoal(Entity entity, GoalConfiguration goal);

    boolean removeTargetGoals(Entity entity);

    boolean removeTargetGoal(Entity entity, GoalType goalType);

    Collection<String> getTargetGoalDescriptions(Entity entity);

    boolean addTargetGoal(Entity entity, GoalType goalType, int priority, ConfigurationSection config);

    boolean addTargetGoal(Entity entity, GoalConfiguration goal);

    boolean setPathfinderTarget(Entity entity, Entity target, double speed);
}


text:
import logging
import re
from textwrap import dedent

import click
from praw.errors import SubredditExists, RateLimitExceeded

from images_of import command, settings, Reddit

DRY_RUN = False
LOG = logging.getLogger(__name__)

def create_sub(r, sub):
    try:
        LOG.info('Attempting to create /r/{}'.format(sub))
        if not DRY_RUN:
            r.create_subreddit(sub, sub)
        LOG.info('Created /r/{}'.format(sub))
    except SubredditExists:
        LOG.warning('/r/{} exists'.format(sub))

def copy_settings(r, sub, topic):
    LOG.info('Copying settings from {}'.format(settings.PARENT_SUB))
    if not DRY_RUN:
        sub_settings = r.get_settings(settings.PARENT_SUB)
    else:
        sub_settings = {'title': settings.NETWORK_NAME}

    LOG.debug('{}'.format(sub_settings))

    sub_settings['title'] = "{} {}".format(sub_settings['title'], topic)
    sub_settings['public_description'] = 'Pictures and images of {}'.format(topic)

    LOG.info('Copying settings to /r/{}'.format(sub))

    if DRY_RUN:
        return

    sub_obj = r.get_subreddit(sub)
    try:
        r.set_settings(sub_obj, **sub_settings)
    except RateLimitExceeded:
        # when we change settings on a subreddit,
        # if it's been created within the last 10 minutes,
        # reddit alwasy issues a rate limiting warning
        # informing us about how long we have until we
        # can create a new subreddit, and PRAW interprets
        # this as an error. It's not.
        pass

def invite_mods(r, sub):
    mods = settings.DEFAULT_MODS

    if not DRY_RUN:
        cur_mods = [u.name for u in r.get_moderators(sub)]
    else:
        cur_mods = []
    LOG.debug('current mods for /r/{}: {}'.format(sub, cur_mods))

    need_mods = [mod for mod in mods if mod not in cur_mods]
    if not need_mods:
        LOG.info('All mods already invited.')
        return
    else:
        LOG.info('Inviting moderators: {}'.format(need_mods))

    if not DRY_RUN:
        s = r.get_subreddit(sub)
        for mod in need_mods:
            s.add_moderator(mod)

    LOG.info('Mods invited.')

def copy_wiki_pages(r, sub):
    for page in settings.WIKI_PAGES:
        LOG.info('Copying wiki page "{}"'.format(page))
        if not DRY_RUN:
            content = r.get_wiki_page(settings.PARENT_SUB, page).content_md
            r.edit_wiki_page(sub, page, content=content, reason='Subreddit stand-up')

def setup_flair(r, sub):
    # XXX should this be copied from the parent?
    LOG.info('Setting up flair')
    if not DRY_RUN:
        r.configure_flair(sub,
                          flair_enabled=True,
                          flair_position='right',
                          link_flair_enabled=True,
                          link_flair_position='right',
                          flair_self_assign=False)

def add_to_multi(r, sub, multi):
    if not multi:
        LOG.warning("No multireddit to add /r/{} to.".format(sub))
        return

    LOG.info('Adding /r/{} to /user/{}/m/{}'
                 .format(sub, settings.MULTIREDDIT_USER, multi))

    if DRY_RUN:
        return

    m = r.get_multireddit(settings.MULTIREDDIT_USER, multi)

    # NOTE: for some reason, at least for this version of PRAW,
    # adding a sub to a multireddit requires us to be logged in.
    r.login()
    m.add_subreddit(sub)

def setup_notifications(r, sub):
    setup = dedent("""\
        {
        "subreddit": "{{subreddit}}",
        "karma": 1,
        "filter-users": [],
        "filter-subreddits": []
        }""")

    LOG.info('Requesting notifications about /r/{} from /u/Sub_Mentions'
                 .format(sub))

    if not DRY_RUN:
        r.send_message('Sub_Mentions', 'Action: Subscribe',
                       setup.replace('{{subreddit}}', sub), from_sr=sub)

_start_points = ['creation', 'settings', 'mods', 'wiki', 'flair', 'multireddit', 'notifications']

@command
@click.option('-m', '--multi', type=click.Choice(settings.MULTIREDDITS),
              default=settings.MULTIREDDITS[0], help="Which multireddit to add the new sub to.")
@click.option('--start-at', type=click.Choice(_start_points),
              help='Where to start the process from.')
@click.option('--only', type=click.Choice(_start_points),
              help='Only run one section of expansion script.')
@click.option('--dry-run', is_flag=True, help='Don\'t hit reddit')
@click.argument('topic', required=True, nargs=-1)
def main(multi, topic, start_at, only, dry_run):
    """Prop up new subreddit and set it for the network."""
    global DRY_RUN
    DRY_RUN = dry_run

    if not DRY_RUN:
        r = Reddit('Expand {} Network v0.2 /u/{}'
                   .format(settings.NETWORK_NAME, settings.USERNAME))
        r.oauth()
    else:
        r = None

    topic = ' '.join(topic)
    nice_topic = ''.join(re.findall('[A-Za-z0-9]', topic))
    sub = settings.NETWORK_NAME + ''.join(nice_topic)

    # little helper script to check if we're at or after
    # where we want to start.
    def should_do(point):
        point_idx = _start_points.index(point)
        if only:
            only_idx = _start_points.index(only)
            return only_idx == point_idx
        elif start_at:
            start_idx = _start_points.index(start_at)
            return start_idx <= point_idx
        return True

    if should_do('creation'):
        create_sub(r, sub)

    if should_do('settings'):
        copy_settings(r, sub, topic)

    if should_do('mods'):
        invite_mods(r, sub)

    if should_do('wiki'):
        copy_wiki_pages(r, sub)

    if should_do('flair'):
        setup_flair(r, sub)

    if should_do('multireddit'):
        add_to_multi(r, sub, multi)

    if should_do('notifications'):
        setup_notifications(r, sub)

if __name__ == '__main__':
    main()


text:
package com.m1.mimeui.api.codec;

public interface DataUriCodec extends UriCodec<DataUriPayload>
{
    public final static String DATA_URI_SCHEME = "data:"; // RFC-2397 Section 3

    public DataUriPayload parse (final String dataUri);
    public String toString (final DataUriPayload data);
}


text:
`new FileInput([options])`

(See Options)

### Syntax:
```javascript
var options = {type:FileInput.TYPE.FILE};
var fi = new FileInput(options);
```
### Options
```javascript
var options = {
    accept : "image/jpeg",
    fileupload : document.querySelector("input[type=file]"),
    dragndrop : document.querySelector("div"),
    onload : function (file) { console.log("File loaded",file); },
    onerror : function (e) { console.log("Some error happened: ",e.message); },
    dragndrop_hoverclass : "drophover",
    type : FileInput.TYPE.FILE
}
```
#### options.accept
The accept option is used to specify the types of files that the FileInput object should accept.

The specification will apply to the file upload element and raise an error on drop events.

The accept option can contain comma separated MIME types or file extensions.

##### Examples
```javascript
options.accept = "image/jpeg, image/png";
options.accept = ".gif, .jpeg, .png";
```

#### options.fileupload
A string for querySelector or a input DOM element.

The type parameter is automatically set to "file".

##### Examples
```javascript
options.fileupload = "input#fileuploadid";
options.fileupload = document.querySelector("input#fileuploadid");
```

#### options.dragndrop
A string for querySelector or any DOM element (supporting the drop event).

The necessary parameter is automatically applied.

##### Examples
```javascript
options.dragndrop = "div#dropelement";
options.dragndrop = document.querySelector("div#dropelement");
```

#### options.onload
An eventhandler which is called when a file is successfull parsed.

##### Examples
```javascript
options.onload = function (file) { console.log("File loaded",file); };
```

#### options.onload
An errorhandler which is called when anything goes wrong, including when accept isn't fulfilled.

##### Examples
```javascript
options.onerror = function (e) { console.log("Some error happened: ",e.message); };
```

#### options.dragndrop_hoverclass
The class name which will appear when a user is hovering the dragndrop element with a file.

##### Examples
```javascript
options.dragndrop_hoverclass = "drophover";
options.dragndrop_hoverclass = "glow";
```

#### options.type
The type which the fileinput should return

The following types are available:

* `FileInput.TYPE.ARRAYBUFFER`
 * [ArrayBuffer](http://www.javascripture.com/ArrayBuffer)
* `FileInput.TYPE.DATAURL`
  * Data as encoded string (dataurl - base64)
* `FileInput.TYPE.TEXT`
  * Data as string
* `FileInput.TYPE.FILE`
 * [File](http://www.javascripture.com/File)

##### Examples
```javascript
options.type = FileInput.TYPE.FILE;
options.type = FileInput.TYPE.TEXT;
```


text:
import numpy as np
import torch

def track2result(bboxes, labels, ids, num_classes):
    valid_inds = ids > -1
    bboxes = bboxes[valid_inds]
    labels = labels[valid_inds]
    ids = ids[valid_inds]

    if bboxes.shape[0] == 0:
        return [np.zeros((0, 6), dtype=np.float32) for i in range(num_classes)]
    else:
        if isinstance(bboxes, torch.Tensor):
            bboxes = bboxes.cpu().numpy()
            labels = labels.cpu().numpy()
            ids = ids.cpu().numpy()
        return [
            np.concatenate((ids[labels == i, None], bboxes[labels == i, :]), axis=1)
            for i in range(num_classes)
        ]

def restore_result(result, return_ids=False):
    labels = []
    for i, bbox in enumerate(result):
        labels.extend([i] * bbox.shape[0])
    bboxes = np.concatenate(result, axis=0).astype(np.float32)
    labels = np.array(labels, dtype=np.int64)
    if return_ids:
        ids = bboxes[:, 0].astype(np.int64)
        bboxes = bboxes[:, 1:]
        return bboxes, labels, ids
    else:
        return bboxes, labels


text:
package rx.math.operators;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;

/**
 * Returns the minimum element in an observable sequence.
 */
public final class OperatorMinMax {
    private OperatorMinMax() { throw new IllegalStateException("No instances!"); }

    public static <T extends Comparable<? super T>> Observable<T> min(
            Observable<T> source) {
        return minMax(source, -1L);
    }

    public static <T> Observable<T> min(Observable<T> source,
            final Comparator<? super T> comparator) {
        return minMax(source, comparator, -1L);
    }

    public static <T, R extends Comparable<? super R>> Observable<List<T>> minBy(
            Observable<T> source, final Func1<T, R> selector) {
        return minMaxBy(source, selector, -1L);
    }

    public static <T, R> Observable<List<T>> minBy(Observable<T> source,
            final Func1<T, R> selector, final Comparator<? super R> comparator) {
        return minMaxBy(source, selector, comparator, -1L);
    }

    public static <T extends Comparable<? super T>> Observable<T> max(
            Observable<T> source) {
        return minMax(source, 1L);
    }

    public static <T> Observable<T> max(Observable<T> source,
            final Comparator<? super T> comparator) {
        return minMax(source, comparator, 1L);
    }

    public static <T, R extends Comparable<? super R>> Observable<List<T>> maxBy(
            Observable<T> source, final Func1<T, R> selector) {
        return minMaxBy(source, selector, 1L);
    }

    public static <T, R> Observable<List<T>> maxBy(Observable<T> source,
            final Func1<T, R> selector, final Comparator<? super R> comparator) {
        return minMaxBy(source, selector, comparator, 1L);
    }

    private static <T extends Comparable<? super T>> Observable<T> minMax(
            Observable<T> source, final long flag) {
        return source.reduce(new Func2<T, T, T>() {
            @Override
            public T call(T acc, T value) {
                if (flag * acc.compareTo(value) > 0) {
                    return acc;
                }
                return value;
            }
        });
    }

    private static <T> Observable<T> minMax(Observable<T> source,
            final Comparator<? super T> comparator, final long flag) {
        return source.reduce(new Func2<T, T, T>() {
            @Override
            public T call(T acc, T value) {
                if (flag * comparator.compare(acc, value) > 0) {
                    return acc;
                }
                return value;
            }
        });
    }

    private static <T, R extends Comparable<? super R>> Observable<List<T>> minMaxBy(
            Observable<T> source, final Func1<T, R> selector, final long flag) {
        return source.reduce(new ArrayList<T>(),
                new Func2<List<T>, T, List<T>>() {

                    @Override
                    public List<T> call(List<T> acc, T value) {
                        if (acc.isEmpty()) {
                            acc.add(value);
                        } else {
                            int compareResult = selector.call(acc.get(0))
                                    .compareTo(selector.call(value));
                            if (compareResult == 0) {
                                acc.add(value);
                            } else if (flag * compareResult < 0) {
                                acc.clear();
                                acc.add(value);
                            }
                        }
                        return acc;
                    }
                });
    }

    private static <T, R> Observable<List<T>> minMaxBy(Observable<T> source,
            final Func1<T, R> selector, final Comparator<? super R> comparator,
            final long flag) {
        return source.reduce(new ArrayList<T>(),
                new Func2<List<T>, T, List<T>>() {

                    @Override
                    public List<T> call(List<T> acc, T value) {
                        if (acc.isEmpty()) {
                            acc.add(value);
                        } else {
                            int compareResult = comparator.compare(
                                    selector.call(acc.get(0)),
                                    selector.call(value));
                            if (compareResult == 0) {
                                acc.add(value);
                            } else if (flag * compareResult < 0) {
                                acc.clear();
                                acc.add(value);
                            }
                        }
                        return acc;
                    }
                });
    }

}


text:
{% extends "_layouts/default.html" %}

{% block content %}
	{% include "_includes/detailcontent.html" %}
{% endblock %}


text:
package array

import "github.com/apache/arrow/go/arrow"

// A type which represents an immutable sequence of fixed-length binary strings.
type FixedSizeBinary struct {
	array
	valueOffsets []int32
	valueBytes   []byte
}

// NewFixedSizeBinaryData constructs a new fixed-size binary array from data.
func NewFixedSizeBinaryData(data *Data) *FixedSizeBinary {
	a := &FixedSizeBinary{}
	a.refCount = 1
	a.setData(data)
	return a
}

// Value returns the fixed-size slice at index i. This value should not be mutated.
func (a *FixedSizeBinary) Value(i int) []byte {
	return a.valueBytes[a.valueOffsets[i]:a.valueOffsets[i+1]]
}

func (a *FixedSizeBinary) ValueOffset(i int) int { return int(a.valueOffsets[i]) }
func (a *FixedSizeBinary) ValueLen(i int) int    { return int(a.valueOffsets[i+1] - a.valueOffsets[i]) }
func (a *FixedSizeBinary) ValueOffsets() []int32 { return a.valueOffsets }
func (a *FixedSizeBinary) ValueBytes() []byte    { return a.valueBytes }

func (a *FixedSizeBinary) setData(data *Data) {
	if len(data.buffers) != 3 {
		panic("len(data.buffers) != 3")
	}

	a.array.setData(data)

	if valueBytes := data.buffers[2]; valueBytes != nil {
		a.valueBytes = valueBytes.Bytes()
	}
	if valueOffsets := data.buffers[1]; valueOffsets != nil {
		a.valueOffsets = arrow.Int32Traits.CastFromBytes(valueOffsets.Bytes())
	}
}

var (
	_ Interface = (*FixedSizeBinary)(nil)
)


text:
describe('<Ideas />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(false);
  });
});