text:
"""
  `syllable_count(string, vowels="aeiouy", exceptions=[r"[aeiou]les?\b",r"[^l]e\b"])`

  Counts the syllables in a string.

  The algorithm given simply counts contiguous sequences of vowels, adjusting
  for regex-specified exceptions, which reduce the count by one. Where a string
  with multiple words is input, the result is the sum for each word.

  The default arguments for `vowels` and `exceptions` mean that the function
  gives good output for English text, though certain words like 'Maria' will trip
  it up. Replacing vowels and rules would allow for the algorithm to apply for other
  languages.

  The function should always return at least one syllable per word.
"""
function syllable_count(word::Union{String,SubString}, vowels::String="aeiouy", exceptions::Array{Regex,1}=[r"[aeiou][lr]es?\b", r"[^lri]es?\b"])

  #Catch sentence input
  if occursin(" ", word)
    words = split(word, [' ','-','\n','\t'])
    return sum(map(w -> syllable_count(w, vowels, exceptions), words))
  end

  #Count vowels.
  word = lowercase(word)
  lc = ' '
  count = 0
  for char in word
    if char in vowels && ! (lc in vowels)
      count += 1
    end
    lc = char
  end

  #Remove silent endings
  for ex in exceptions
    if occursin(ex,word) && count > 1
      count -= 1
    end
  end

  return count
end

num_matches(r::Regex, w::AbstractString) = length(collect(eachmatch(r, w)))

function time_word(word, language)
    if length(word) == 0
      return 0
    elseif language == "de"
      return 0.201443 + 0.247255*num_matches(r"[0-9]{2}", word) + 0.220354*num_matches(r"[0-9]", word) + 0.155791*num_matches(r"q", word) + 0.147522*num_matches(r"x", word) + 0.141111*num_matches(r"[0-9]{4}", word) + 0.111575*num_matches(r"\u00ee", word) + 0.109382*num_matches(r"[^a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fdbcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.099467*num_matches(r"o", word) + 0.094990*num_matches(r"a", word) + 0.089802*num_matches(r"z", word) + 0.088050*num_matches(r"\u00f3", word) + 0.080506*num_matches(r"\u00e1", word) + 0.079824*num_matches(r"\u00e2", word) + 0.078788*num_matches(r"y", word) + 0.073479*num_matches(r"\u00e0", word) + 0.068338*num_matches(r"\u00e4", word) + 0.066598*num_matches(r"s", word) + 0.063880*num_matches(r"\u00ef", word) + 0.062730*num_matches(r"i", word) + 0.061144*num_matches(r"k", word) + 0.057448*num_matches(r"\u00f4", word) + 0.055320*num_matches(r"\u00e9", word) + 0.055251*num_matches(r"\u00e8", word) + 0.053560*num_matches(r"v", word) + 0.052198*num_matches(r"\u00ed", word) + 0.050962*num_matches(r"\u00ea", word) + 0.049994*num_matches(r"b", word) + 0.049982*num_matches(r"f", word) + 0.047746*num_matches(r"e", word) + 0.047723*num_matches(r"^[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd]", word) + 0.047120*num_matches(r"j", word) + 0.046027*num_matches(r"p", word) + 0.045183*num_matches(r"t", word) + 0.040199*num_matches(r"r", word) + 0.039382*num_matches(r"d", word) + 0.037563*num_matches(r"\u00f1", word) + 0.037290*num_matches(r"\u00f6", word) + 0.037290*num_matches(r"\u00f6", word) + 0.036302*num_matches(r"^[bcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]{3}", word) + 0.035693*num_matches(r"g", word) + 0.034323*num_matches(r"\u00fb", word) + 0.032789*num_matches(r"u", word) + 0.032789*num_matches(r"u", word) + 0.032587*num_matches(r"[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd][bcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.030861*num_matches(r"n", word) + 0.029051*num_matches(r"m", word) + 0.027110*num_matches(r"l", word) + 0.027075*num_matches(r"w", word) + 0.025398*num_matches(r"h", word) + 0.023578*num_matches(r"\u00e7", word) + 0.013630*num_matches(r"[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd]\$", word) + 0.012129*num_matches(r"c", word) + 0.002293*num_matches(r"\u00eb", word)
    elseif language == "en-US"
      return 0.288128 + 0.954096*num_matches(r"[0-9]{4}", word) + 0.356994*num_matches(r"[0-9]", word) + 0.289716*num_matches(r"\u0169", word) + 0.260762*num_matches(r"^[bcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]{3}", word) + 0.202507*num_matches(r"\u00f1", word) + 0.189280*num_matches(r"q", word) + 0.172014*num_matches(r"x", word) + 0.138827*num_matches(r"n", word) + 0.132514*num_matches(r"m", word) + 0.128558*num_matches(r"\u012b", word) + 0.117963*num_matches(r"d", word) + 0.115260*num_matches(r"\u00ed", word) + 0.111563*num_matches(r"b", word) + 0.109092*num_matches(r"v", word) + 0.107073*num_matches(r"\u00e7", word) + 0.105800*num_matches(r"p", word) + 0.104254*num_matches(r"l", word) + 0.100262*num_matches(r"r", word) + 0.099480*num_matches(r"j", word) + 0.097076*num_matches(r"t", word) + 0.096195*num_matches(r"c", word) + 0.095999*num_matches(r"\u00fa", word) + 0.090362*num_matches(r"[0-9]{2}", word) + 0.082615*num_matches(r"\u016b", word) + 0.080488*num_matches(r"s", word) + 0.075311*num_matches(r"g", word) + 0.075048*num_matches(r"z", word) + 0.067591*num_matches(r"k", word) + 0.065711*num_matches(r"f", word) + 0.065148*num_matches(r"[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd][bcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.063661*num_matches(r"a", word) + 0.060130*num_matches(r"y", word) + 0.059559*num_matches(r"\u0159", word) + 0.056398*num_matches(r"i", word) + 0.054900*num_matches(r"o", word) + 0.050908*num_matches(r"\u00e1", word) + 0.048779*num_matches(r"w", word) + 0.046645*num_matches(r"\u00fb", word) + 0.034323*num_matches(r"\u00e2", word) + 0.033232*num_matches(r"\u00eb", word) + 0.031705*num_matches(r"\u00f4", word) + 0.029573*num_matches(r"\u0101", word) + 0.028180*num_matches(r"u", word) + 0.028180*num_matches(r"u", word) + 0.027809*num_matches(r"\u00e4", word) + 0.026002*num_matches(r"\u00f3", word) + 0.024175*num_matches(r"[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd]\$", word) + 0.021481*num_matches(r"e", word) + 0.019389*num_matches(r"\u0131", word) + 0.018713*num_matches(r"[^a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fdbcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.012112*num_matches(r"\u00e0", word) + 0.010956*num_matches(r"h", word) + 0.007262*num_matches(r"\u00ee", word) + 0.004981*num_matches(r"\u00e8", word)
    elseif language == "es"
      return 0.187036 + 0.317005*num_matches(r"\u00e3", word) + 0.315815*num_matches(r"\u0169", word) + 0.292691*num_matches(r"\u0103", word) + 0.253129*num_matches(r"\u011b", word) + 0.227771*num_matches(r"[^a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fdbcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.207797*num_matches(r"\u0159", word) + 0.189736*num_matches(r"[0-9]{2}", word) + 0.184000*num_matches(r"\u00e6", word) + 0.182175*num_matches(r"\u012b", word) + 0.167399*num_matches(r"\u00f5", word) + 0.139567*num_matches(r"\u0101", word) + 0.111823*num_matches(r"x", word) + 0.102212*num_matches(r"\u016b", word) + 0.099673*num_matches(r"k", word) + 0.099467*num_matches(r"\u00fd", word) + 0.097008*num_matches(r"z", word) + 0.090673*num_matches(r"y", word) + 0.077894*num_matches(r"\u0131", word) + 0.075144*num_matches(r"p", word) + 0.068023*num_matches(r"j", word) + 0.064888*num_matches(r"f", word) + 0.064057*num_matches(r"t", word) + 0.062861*num_matches(r"c", word) + 0.061194*num_matches(r"s", word) + 0.059466*num_matches(r"o", word) + 0.059261*num_matches(r"d", word) + 0.058316*num_matches(r"w", word) + 0.057997*num_matches(r"g", word) + 0.052533*num_matches(r"a", word) + 0.051308*num_matches(r"r", word) + 0.050576*num_matches(r"i", word) + 0.048901*num_matches(r"b", word) + 0.047846*num_matches(r"v", word) + 0.047137*num_matches(r"q", word) + 0.045976*num_matches(r"[0-9]{4}", word) + 0.043086*num_matches(r"n", word) + 0.042979*num_matches(r"m", word) + 0.040604*num_matches(r"\u00e4", word) + 0.039670*num_matches(r"h", word) + 0.039339*num_matches(r"l", word) + 0.038610*num_matches(r"[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd][bcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.035417*num_matches(r"e", word) + 0.032111*num_matches(r"\u00e1", word) + 0.030724*num_matches(r"^[bcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]{3}", word) + 0.023949*num_matches(r"[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd]\$", word) + 0.021964*num_matches(r"\u00f6", word) + 0.021964*num_matches(r"\u00f6", word) + 0.014352*num_matches(r"u", word) + 0.014352*num_matches(r"u", word) + 0.000250*num_matches(r"[0-9]", word)
    elseif language == "fr"
      return 0.094123 + 0.524550*num_matches(r"[0-9]{4}", word) + 0.146372*num_matches(r"[0-9]{2}", word) + 0.115989*num_matches(r"\u00ef", word) + 0.075470*num_matches(r"j", word) + 0.071641*num_matches(r"w", word) + 0.067887*num_matches(r"[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd]\$", word) + 0.066211*num_matches(r"[a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fd][bcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.064186*num_matches(r"g", word) + 0.062926*num_matches(r"k", word) + 0.060646*num_matches(r"y", word) + 0.059996*num_matches(r"x", word) + 0.059590*num_matches(r"f", word) + 0.057422*num_matches(r"c", word) + 0.055183*num_matches(r"\u00e7", word) + 0.054494*num_matches(r"r", word) + 0.053814*num_matches(r"z", word) + 0.051429*num_matches(r"t", word) + 0.049218*num_matches(r"s", word) + 0.044615*num_matches(r"\u00eb", word) + 0.044090*num_matches(r"i", word) + 0.043803*num_matches(r"d", word) + 0.042808*num_matches(r"\u00f6", word) + 0.042808*num_matches(r"\u00f6", word) + 0.042791*num_matches(r"b", word) + 0.042591*num_matches(r"q", word) + 0.039526*num_matches(r"p", word) + 0.038798*num_matches(r"v", word) + 0.035982*num_matches(r"\u00e9", word) + 0.034998*num_matches(r"o", word) + 0.032743*num_matches(r"[0-9]", word) + 0.031503*num_matches(r"a", word) + 0.028726*num_matches(r"[^a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fdbcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.027647*num_matches(r"h", word) + 0.027537*num_matches(r"m", word) + 0.027147*num_matches(r"l", word) + 0.025762*num_matches(r"\u00f4", word) + 0.020906*num_matches(r"^[bcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]{3}", word) + 0.020085*num_matches(r"\u00e8", word) + 0.016057*num_matches(r"n", word) + 0.014943*num_matches(r"\u00e2", word) + 0.011852*num_matches(r"u", word) + 0.011852*num_matches(r"u", word) + 0.008881*num_matches(r"\u00e0", word) + 0.006535*num_matches(r"e", word) + 0.003959*num_matches(r"\u00ea", word)
    elseif language == "it"
      return 0.216031 + 0.280613*num_matches(r"[0-9]{2}", word) + 0.219277*num_matches(r"x", word) + 0.149924*num_matches(r"[0-9]", word) + 0.145241*num_matches(r"[^a\u00e2\u00e1\u00e0\u00e4\u01ce\u0103\u00e3\u0101\u00e6\u01e3e\u00ea\u00e9\u00e8\u00eb\u011b\u0115\u0113i\u00ef\u00ed\u00ee\u01d0\u012d\u0129\u0131\u012bo\u00f6\u00f3\u00f4\u00f6\u01d2\u014f\u00f5u\u00fa\u00f9\u00fbu\u01d4\u016d\u0169\u016by\u00fdbcdfghjklmnpqrstvwxz\u00f1\u00e7\u0159]", word) + 0.115833*num_matches(r"z", word) + 0.104811*num_matches(r"c", word) + 0.104514*num_matches(r"p", word) + 0.101104*num_matches(r"t", word) + 0.096837*num_matches(r"k", word) + 0.094215*num_matches(r"q", word) + 0.092929*num_matches(r"f", word) + 0.091644*num_matches(r"s", word) + 0.075643*num_matches(r"n", word) + 0.073194*num_matches(r"g", word) + 0.071579*num_matches(r"y", word) + 0.067655*num_matches(r"j", word) + 0.066069*num_matches(r"b", word) + 0.064722*num_matches(r"e", word) + 0.059960*num_matches(r"v", word) + 0.058603*num_matches(r"i", word) + 0.057001*num_matches(r"m", word) + 0.054888*num_matches(r"w", word) + 0.053622*num_matches(r"o", word) + 0.052965*num_matches(r"d", word) + 0.052437*num_matches(r"a", word) + 0.051798*num_matches(r"l", word) + 0.051058*num_matches(r"\u00e9", word) + 0.050466*num_matches(r"\u00e1", word) + 0.049816*num_matches(r"r", word) + 0.049440*num_matches(r"\u00f9", word) + 0.048566*num_matches(r"\u00fa", word) + 0.044918*num_matches(r"\u00e2", word) + 0.034806*num_matches(r"\u00f1", word) + 0.031362*num_matches(r"u", word) + 0.031362*num_matches(r"u", word) + 0.028077*num_matches(r"\u00f3", word) + 0.023515*num_matches(r"\u00ea", word) + 0.013186*num_matches(r"\u00f4", word)
    elseif language == "ja"
      return 0.192934 + 0.401897*num_matches(r"\uff57", word) + 0.391781*num_matches(r"\uff37", word) + 0.345174*num_matches(r"\uff16", word) + 0.337752*num_matches(r"\uff17", word) + 0.335693*num_matches(r"\uff18", word) + 0.305787*num_matches(r"\uff19", word) + 0.284248*num_matches(r"\uff13", word) + 0.260788*num_matches(r"\uff14", word) + 0.250454*num_matches(r"\uff32", word) + 0.249550*num_matches(r"\uff52", word) + 0.239987*num_matches(r"\uff48", word) + 0.232954*num_matches(r"\uff15", word) + 0.224712*num_matches(r"\uff28", word) + 0.201113*num_matches(r"\uff4d", word) + 0.198311*num_matches(r"\uff56", word) + 0.197385*num_matches(r"\uff12", word) + 0.195817*num_matches(r"\uff23", word) + 0.194144*num_matches(r"\uff2c", word) + 0.191657*num_matches(r"\uff47", word) + 0.187868*num_matches(r"\uff4e", word) + 0.183400*num_matches(r"\uff27", word) + 0.181215*num_matches(r"\uff50", word) + 0.177365*num_matches(r"\uff2d", word) + 0.175796*num_matches(r"\uff34", word) + 0.175779*num_matches(r"\uff11", word) + 0.174960*num_matches(r"\uff42", word) + 0.172881*num_matches(r"\uff49", word) + 0.171703*num_matches(r"\uff43", word) + 0.171623*num_matches(r"\uff4c", word) + 0.168697*num_matches(r"\uff53", word) + 0.166248*num_matches(r"\uff54", word) + 0.162419*num_matches(r"\uff25", word) + 0.161625*num_matches(r"\uff2a", word) + 0.159372*num_matches(r"\uff22", word) + 0.158361*num_matches(r"\uff55", word) + 0.158059*num_matches(r"\uff24", word) + 0.156341*num_matches(r"\uff41", word) + 0.153941*num_matches(r"\uff45", word) + 0.153059*num_matches(r"\uff39", word) + 0.149345*num_matches(r"\uff33", word) + 0.147929*num_matches(r"\uff2e", word) + 0.146199*num_matches(r"\uff46", word) + 0.144357*num_matches(r"\uff35", word) + 0.144285*num_matches(r"\uff44", word) + 0.134242*num_matches(r"\uff21", word) + 0.132635*num_matches(r"\uff26", word) + 0.129675*num_matches(r"\uff29", word) + 0.122793*num_matches(r"\uff4b", word) + 0.122485*num_matches(r"\uff2b", word) + 0.122419*num_matches(r"\uff30", word) + 0.122348*num_matches(r"\uff4f", word) + 0.117883*num_matches(r"\uff36", word) + 0.116234*num_matches(r"\uff59", word) + 0.110487*num_matches(r"^[\u4E00-\u9FFF]", word) + 0.104395*num_matches(r"\u304f", word) + 0.100524*num_matches(r"\u30b6", word) + 0.099742*num_matches(r"\u30ba", word) + 0.095281*num_matches(r"\u5cf6", word) + 0.094178*num_matches(r"\u30ab", word) + 0.094091*num_matches(r"\u308f", word) + 0.088825*num_matches(r"\u30bc", word) + 0.086408*num_matches(r"\u30b5", word) + 0.086084*num_matches(r"[\u4E00-\u9FFF]\$", word) + 0.083627*num_matches(r"\u30dd", word) + 0.082973*num_matches(r"\uff2f", word) + 0.082004*num_matches(r"\u304c", word) + 0.081355*num_matches(r"\u30bb", word) + 0.080537*num_matches(r"\u56fd", word) + 0.080233*num_matches(r"\u90ce", word) + 0.076580*num_matches(r"\u30b9", word) + 0.071712*num_matches(r"\u30db", word) + 0.071397*num_matches(r"\u30cb", word) + 0.070678*num_matches(r"\u30b3", word) + 0.070540*num_matches(r"\u30cf", word) + 0.069523*num_matches(r"\u305f", word) + 0.066932*num_matches(r"\u30d1", word) + 0.066558*num_matches(r"\u7acb", word) + 0.066497*num_matches(r"\u30c8", word) + 0.065144*num_matches(r"\u30bf", word) + 0.065009*num_matches(r"\u308d", word) + 0.064780*num_matches(r"\u3068", word) + 0.064771*num_matches(r"\u3064", word) + 0.063986*num_matches(r"\u30af", word) + 0.062007*num_matches(r"\u5357", word) + 0.061800*num_matches(r"\u30bd", word) + 0.060136*num_matches(r"\u30e4", word) + 0.059696*num_matches(r"\u307e", word) + 0.059586*num_matches(r"\u30d9", word) + 0.059112*num_matches(r"\u30ef", word) + 0.058790*num_matches(r"\u3084", word) + 0.058416*num_matches(r"\u30b0", word) + 0.058322*num_matches(r"\u5ddd", word) + 0.058256*num_matches(r"\u30ad", word) + 0.058247*num_matches(r"\u30ea", word) + 0.057527*num_matches(r"\u30e1", word) + 0.057262*num_matches(r"\u30c9", word) + 0.057210*num_matches(r"\u5c71", word) + 0.056999*num_matches(r"\u30cc", word) + 0.056670*num_matches(r"\u30e0", word) + 0.056596*num_matches(r"\u30d3", word) + 0.056482*num_matches(r"\u672c", word) + 0.055207*num_matches(r"\u30d4", word) + 0.055031*num_matches(r"\u30c0", word) + 0.054831*num_matches(r"\u4e2d", word) + 0.054312*num_matches(r"\u305b", word) + 0.053996*num_matches(r"\u3053", word) + 0.053672*num_matches(r"\u30b7", word) + 0.053307*num_matches(r"\u30cd", word) + 0.053183*num_matches(r"\u3061", word) + 0.053151*num_matches(r"\u30ed", word) + 0.053137*num_matches(r"\u30fc", word) + 0.052671*num_matches(r"\u30b8", word) + 0.052482*num_matches(r"\u30ce", word) + 0.052469*num_matches(r"\u30df", word) + 0.052218*num_matches(r"\u3059", word) + 0.051149*num_matches(r"\u30d0", word) + 0.051120*num_matches(r"\u30c1", word) + 0.050576*num_matches(r"\u3055", word) + 0.050530*num_matches(r"\u9ad8", word) + 0.050406*num_matches(r"\u3051", word) + 0.050285*num_matches(r"\u30d5", word) + 0.049924*num_matches(r"\u30b2", word) + 0.049910*num_matches(r"\u3057", word) + 0.049552*num_matches(r"\u30d2", word) + 0.048954*num_matches(r"\u304d", word) + 0.048841*num_matches(r"\u30e2", word) + 0.047662*num_matches(r"\u306a", word) + 0.046810*num_matches(r"\u30d7", word) + 0.046802*num_matches(r"\u306e", word) + 0.046168*num_matches(r"\u3046", word) + 0.045981*num_matches(r"\u30f3", word) + 0.045687*num_matches(r"\u3089", word) + 0.045390*num_matches(r"\u30ec", word) + 0.045015*num_matches(r"\u30ac", word) + 0.044927*num_matches(r"\u30da", word) + 0.044909*num_matches(r"\u884c", word) + 0.043977*num_matches(r"\u30de", word) + 0.043935*num_matches(r"\u30f4", word) + 0.043439*num_matches(r"\u30c4", word) + 0.042776*num_matches(r"\u307f", word) + 0.042713*num_matches(r"\u30ca", word) + 0.041510*num_matches(r"\u30c3", word) + 0.039911*num_matches(r"\u30e9", word) + 0.039382*num_matches(r"\u30ae", word) + 0.036680*num_matches(r"\u5317", word) + 0.034881*num_matches(r"\u30b1", word) + 0.034862*num_matches(r"\u30eb", word) + 0.033453*num_matches(r"\u539f", word) + 0.033265*num_matches(r"\u65b0", word) + 0.031582*num_matches(r"^[\u3040-\u30FA\uFF66-\uFF9D]{3}", word) + 0.031414*num_matches(r"\u795e", word) + 0.030574*num_matches(r"\u30d6", word) + 0.030494*num_matches(r"\u30dc", word) + 0.030311*num_matches(r"\u3063", word) + 0.030213*num_matches(r"\u30c6", word) + 0.029947*num_matches(r".", word) + 0.029441*num_matches(r"[\u4E00-\u9FFF]", word) + 0.027448*num_matches(r"\u3093", word) + 0.026703*num_matches(r"\u3052", word) + 0.026097*num_matches(r"\u308a", word) + 0.025692*num_matches(r"\u3081", word) + 0.024119*num_matches(r"\u3044", word) + 0.023380*num_matches(r"\u30a2", word) + 0.022242*num_matches(r"\u3058", word) + 0.021137*num_matches(r"\u4e0a", word) + 0.019239*num_matches(r"\u30a6", word) + 0.018306*num_matches(r"\u30c7", word) + 0.017776*num_matches(r"\u6b63", word) + 0.017477*num_matches(r"\u9577", word) + 0.013000*num_matches(r"\u5e73", word) + 0.012673*num_matches(r"\u30b4", word) + 0.009949*num_matches(r"\u6771", word) + 0.009247*num_matches(r"\u897f", word) + 0.006630*num_matches(r"\u30a8", word) + 0.006460*num_matches(r"[^\u4E00-\u9FFF\u3040-\u30FA\uFF66-\uFF9D]", word)
  end
end

"""
  `spoken_length(str, language="en-US")`

  Estimates the time in seconds that it would take to say a piece of text.

  Credit for this algorithm should go to [Hal Daumé III](http://nlpers.blogspot.co.uk/2015/09/how-longll-it-take-to-say-that.html).
  The implementation here is based on his Python implementation. In short, the
  algorithm finds certain features using regular expressions and assigns a weight
  to each of them, based on data collected during experiments with speech synthesis
  software, with some modification for inter-word gaps.
"""
function spoken_length(str::String, language::String="en-US")

  languages = ["en-us", "de", "fr", "it", "es", "ja"]
  if ! (lowercase(language) in languages)
    error("Requested language '$language' is not supported.")
  end

  #Divvy our string.
  words = split(str)

  #
  time = -0.116751 + 0.099640 * length(words)

  for word in words
    time += 0.691677 * time_word(word, language)
  end

  #sanity check output
  if time < 0
    return 0
  else
    return time
  end
end

export spoken_length, syllable_count


text:
#
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons
# Licensed under the MIT license. See LICENSE file in the project root for details.
#

using FMI
using Flux
using DifferentialEquations: Tsit5

import Random
Random.seed!(5678);

t_start = 0.0
t_step = 0.01
t_stop = 5.0
tData = t_start:t_step:t_stop

# generate training data
realFMU = fmiLoad("SpringFrictionPendulum1D", ENV["EXPORTINGTOOL"], ENV["EXPORTINGVERSION"])
fmiInstantiate!(realFMU; loggingOn=false)
fmiSetupExperiment(realFMU, t_start, t_stop)
fmiEnterInitializationMode(realFMU)
fmiExitInitializationMode(realFMU)
x0 = fmiGetContinuousStates(realFMU)
realSimData = fmiSimulateCS(realFMU, t_start, t_stop; recordValues=["mass.s", "mass.v"], setup=false, reset=false, instantiate=false, saveat=tData)

# load FMU for NeuralFMU
myFMU = fmiLoad("SpringFrictionPendulum1D", ENV["EXPORTINGTOOL"], ENV["EXPORTINGVERSION"])
fmiInstantiate!(myFMU; loggingOn=false)
fmiSetupExperiment(myFMU, t_start, t_stop)
fmiEnterInitializationMode(myFMU)
fmiExitInitializationMode(myFMU)

# setup traing data
posData = fmi2GetSolutionValue(realSimData, "mass.s")

# loss function for training
function losssum()
    global problem, x0, posData
    solution = problem(x0)

    posNet = fmi2GetSolutionState(solution, 1; isIndex=true)

    Flux.Losses.mse(posNet, posData)
end

# callback function for training
global iterCB = 0
global lastLoss = 0.0
function callb()
    global iterCB += 1
    global lastLoss

    if iterCB % 25 == 0
        loss = losssum()
        @info "Loss: $loss"
        @test loss < lastLoss
        lastLoss = loss
    end
end

vr = fmi2StringToValueReference(myFMU, "mass.m")

numStates = fmiGetNumberOfStates(myFMU)

# some NeuralFMU setups
nets = []

for handleEvents in [true, false]
    @testset "handleEvents: $handleEvents" begin
        for config in [FMU_EXECUTION_CONFIGURATION_RESET, FMU_EXECUTION_CONFIGURATION_NO_RESET, FMU_EXECUTION_CONFIGURATION_NO_FREEING]
            @testset "config: $config" begin

                global problem, lastLoss, iterCB

                myFMU.executionConfig = config
                myFMU.executionConfig.handleStateEvents = handleEvents
                myFMU.executionConfig.handleTimeEvents = handleEvents

                net = Chain(Dense( [1.0 0.0; 0.0 1.0] + rand(numStates,numStates)*0.01, zeros(numStates), identity),
                    states -> fmiEvaluateME(myFMU, states),
                    Dense(numStates, 16, tanh),
                    Dense(16, numStates))

                optim = ADAM(1e-4)
                problem = ME_NeuralFMU(myFMU, net, (t_start, t_stop), Tsit5(); saveat=tData)
                @test problem != nothing

                solutionBefore = problem(x0)
                if solutionBefore.success
                    @test length(solutionBefore.states.t) == length(tData)
                    @test solutionBefore.states.t[1] == t_start
                    @test solutionBefore.states.t[end] == t_stop
                end

                # train it ...
                p_net = Flux.params(problem)

                iterCB = 0
                lastLoss = losssum()
                lastInstCount = length(problem.fmu.components)

                Flux.train!(losssum, p_net, Iterators.repeated((), 50), optim; cb=callb)

                # check results
                solutionAfter = problem(x0)
                if solutionAfter.success
                    @test length(solutionAfter.states.t) == length(tData)
                    @test solutionAfter.states.t[1] == t_start
                    @test solutionAfter.states.t[end] == t_stop
                end

                # clean-up the dead components
                while length(problem.fmu.components) > 1
                    fmiFreeInstance!(problem.fmu)
                end
            end

        end
    end
end

fmiUnload(realFMU)
fmiUnload(myFMU)

ext: jl


text:
"Helper function to lookup a symbol from libsymengine"
function get_symbol(sym::Symbol)
    handle = Base.Libdl.dlopen_e(libsymengine)
    if handle == C_NULL
        C_NULL
    else
        Libdl.dlsym_e(handle, sym)
    end
end

"Get libsymengine version"
function get_libversion()
    func = get_symbol(:symengine_version)
    if func != C_NULL
        a = ccall(func, Ptr{UInt8}, ())
        VersionNumber(unsafe_string(a))
    else
        # Above method is not in 0.2.0 which is the earliest version supported
        VersionNumber("0.2.0")
    end
end

"Check whether libsymengine was compiled with comp"
function have_component(comp::String)
    func = get_symbol(:symengine_have_component)
    if func != C_NULL
        ccall(func, Cint, (Ptr{UInt8},), comp) == 1
    elseif comp == "mpfr"
        get_symbol(:real_mpfr_set_d) != C_NULL
    elseif comp == "mpc"
        get_symbol(:complex_mpc_real_part) != C_NULL
    else
        false
    end
end


text:
#Demo 10: Delay tests
#-------------------------------------------------------------------------------

using CMDimCircuits
CMDimCircuits.@using_CData()

#Get a demo display:
include(CMDimCircuits.demoplotcfgscript)
#Normally use something like:
#CMDimData.@includepkg EasyPlotInspect

#==Constants
===============================================================================#
vvst = cons(:a, labels = set(yaxis="Amplitude (V)", xaxis="Time (s)"))
dpsvst = cons(:a, labels = set(yaxis="Delay (ps)", xaxis="Time (s)"))
dpsvsx = cons(:a, labels = set(yaxis="Delay (ps)", xaxis="Crossing"))
ldelay = cons(:a, line = set(width=3, style=:solid))
gdelay = cons(:a, glyph = set(shape=:x, size=2))

#==Input data
===============================================================================#
tbit = 1e-9 #Bit period
osr = 20 #samples per bit
nsamples = 127

#==Computations
===============================================================================#
seq = 1.0*prbs(reglen=7, seed=1, nsamples=nsamples)
t = DataF1(0:(tbit/osr):(nsamples*tbit))
tmax = maximum(t)

#Generate parameter sweeps:
sweeplist = PSweep[
	PSweep("L", [1]) #Add extra level to test more code
	PSweep("tau", tbit.*[1/5, 1/2.5, 1/1.5])
]

#Generate data:
Π = fill(DataHR, sweeplist) do EL, tau
	return pulse(t, Pole(1/tau,:rad), tpw=tbit)
end

pat = (pattern(seq, Π, tbit=tbit)-0.5)*2 #Center data pattern
refpat = pat.elem[1]
Δ = measdelay(refpat, pat, xing_ref=CrossType(:risefall), xing_main=CrossType(:risefall))
Δxn = measdelay(Event, refpat, pat, xing_ref=CrossType(:risefall), xing_main=CrossType(:risefall))
Δ = DataRS(Δ) #Test support for DataRS objects

#==Generate plot
===============================================================================#
p1 = push!(cons(:plot, vvst, title="Patterns"),
	cons(:wfrm, refpat, line=set(width=5, color=:black), label="Ref"),
	cons(:wfrm, pat, label="pat"),
)
p2 = push!(cons(:plot, dpsvst, title="Delays"),
	cons(:wfrm, Δ/1e-12, ldelay, gdelay, label="D"),
)
p3 = push!(cons(:plot, dpsvsx, title="Delays vs Crossing Number"),
	cons(:wfrm, Δxn/1e-12, ldelay, gdelay, label="D"),
)

pcoll = push!(cons(:plotcoll, title="Signal Delay Tests"), p1, p2, p3)
	pcoll.ncolumns = 1

#==Display results in pcoll
===============================================================================#
EasyPlot.displaygui(pcoll)

#==Return pcoll to user (call evalfile(...))
===============================================================================#
pcoll


text:
using Distributions, Plots; pyplot()

include("../data/mvParams.jl")
biNorm = MvNormal(meanVect,covMat)

N = 10^3
points = rand(MvNormal(meanVect,covMat),N)

support = 15:0.5:40
z = [ pdf(biNorm,[x,y]) for y in support, x in support ]

p1 = scatter(points[1,:], points[2,:], ms=0.5, c=:black, legend=:none)
p1 = contour!(support, support, z,
		levels=[0.001, 0.005, 0.02], c=[:blue, :red, :green],
		xlims=(15,40), ylims=(15,40), ratio=:equal, legend=:none,
		xlabel="x", ylabel="y")
p2 = surface(support, support, z, lw=0.1, c=cgrad([:blue, :red]),
		 legend=:none, xlabel="x", ylabel="y",camera=(-35,20))

plot(p1, p2, size=(800, 400))

max_stars_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook

max_issues_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook

max_forks_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook


text:
module ITensorNetworkMaps

using ..ITensors
using LinearMaps

using ITensors: promote_itensor_eltype

import Base: *

import ITensors: contract

export ITensorNetworkMap, input_inds, output_inds

# convert from Tuple to Vector
tuple_to_vector(t::Tuple) = collect(t)
tuple_to_vector(v::Vector) = v

function default_input_inds(itensors::Vector{ITensor})
  return filter(i -> plev(i) == 0, noncommoninds(itensors...))
end

# Represents the action of applying the
# vector of ITensors to a starting state and then mapping
# them back (from output_inds to input_inds)
struct ITensorNetworkMap{T} <: LinearMap{T}
  itensors::Vector{ITensor}
  input_inds::Vector{Index}
  output_inds::Vector{Index}
  function ITensorNetworkMap(itensors::Vector{ITensor}, input_inds, output_inds)
    inds_in = tuple_to_vector(input_inds)
    inds_out = tuple_to_vector(output_inds)
    return new{promote_itensor_eltype(itensors)}(itensors, inds_in, inds_out)
  end
end
function ITensorNetworkMap(
  itensors::Vector{ITensor};
  input_inds=default_input_inds(itensors),
  output_inds=dag(input_inds'),
)
  return ITensorNetworkMap(itensors, input_inds, output_inds)
end

Base.size(T::ITensorNetworkMap) = (dim(output_inds(T)), dim(input_inds(T)))
Base.eltype(T::ITensorNetworkMap) = promote_itensor_eltype(T.itensors)
input_inds(T::ITensorNetworkMap) = T.input_inds
output_inds(T::ITensorNetworkMap) = T.output_inds

(T::ITensorNetworkMap * v::ITensor) = contract(pushfirst!(copy(T.itensors), v))
(T::ITensorNetworkMap)(v::ITensor) = replaceinds(T * v, output_inds(T) => input_inds(T))

(v::ITensor * T::LinearMap) = transpose(T) * v
contract(T::LinearMap) = T * ITensor(1)

function Base.transpose(T::ITensorNetworkMap)
  return ITensorNetworkMap(reverse(T.itensors), output_inds(T), input_inds(T))
end

# This is actually a Hermitian conjugation, not priming
function Base.adjoint(T::ITensorNetworkMap)
  return ITensorNetworkMap(
    reverse(dag.(T.itensors)), dag(output_inds(T)), dag(input_inds(T))
  )
end

function input_inds(A::LinearMaps.LinearCombination)
  in_inds = input_inds(A.maps[1])
  @assert all(M -> hassameinds(input_inds(M), in_inds), A.maps)
  return in_inds
end
function output_inds(A::LinearMaps.LinearCombination)
  out_inds = output_inds(A.maps[1])
  @assert all(M -> hassameinds(output_inds(M), out_inds), A.maps)
  return out_inds
end

function input_inds(A::LinearMaps.CompositeMap)
  # TODO: Check it is actually an ITensorNetworkMap
  return input_inds(first(A.maps))
end
function output_inds(A::LinearMaps.CompositeMap)
  # TODO: Check it is actually an ITensorNetworkMap
  return output_inds(last(A.maps))
end

callable(x, y) = x(y)

apply(f, A::LinearMaps.ScaledMap, v::ITensor) = (A.λ * f(A.lmap, v))
(A::LinearMaps.ScaledMap)(v::ITensor) = apply(callable, A, v)
(A::LinearMap * v::ITensor) = apply(*, A, v)

apply(f, A::LinearMaps.UniformScalingMap, v::ITensor) = (A.λ * v)
(A::LinearMaps.UniformScalingMap)(v::ITensor) = apply(callable, A, v)

function apply(f, A::LinearMaps.LinearCombination, v::ITensor)
  N = length(A.maps)
  Av = f(A.maps[1], v)
  for n in 2:N
    Av += f(A.maps[n], v)
  end
  return Av
end
(A::LinearMaps.LinearCombination)(v::ITensor) = apply(callable, A, v)

function _replaceinds(::typeof(callable), A::LinearMaps.CompositeMap, v::ITensor)
  output_inds_A = output_inds(A)
  input_inds_A = input_inds(A)
  return replaceinds(v, output_inds_A => input_inds_A)
end
function _replaceinds(::typeof(*), A::LinearMaps.CompositeMap, v::ITensor)
  return v
end

function apply(f, A::LinearMaps.CompositeMap, v::ITensor)
  N = length(A.maps)
  Av = v
  for n in 1:N
    Av = A.maps[n] * Av
  end
  Av = _replaceinds(f, A, Av)
  return Av
end
(A::LinearMaps.CompositeMap)(v::ITensor) = apply(callable, A, v)

function apply(f, A::LinearMaps.BlockMap, v::Vector{ITensor})
  nrows = length(A.rows)
  ncols = A.rows[1]
  @assert all(==(ncols), A.rows)
  M = reshape(collect(A.maps), nrows, ncols)
  Av = fill(ITensor(), nrows)
  for i in 1:nrows, j in 1:ncols
    Av[i] += f(M[i, j], v[j])
  end
  return Av
end
(A::LinearMaps.BlockMap)(v::Vector{ITensor}) = apply(callable, A, v)
(A::LinearMaps.BlockMap * v::Vector{ITensor}) = apply(*, A, v)

end


text:
type GtkTreeModelIface
  g_iface :: GTypeInterface
  row_changed :: Ptr{Void}
  row_inserted :: Ptr{Void}
  row_has_child_toggled :: Ptr{Void}
  row_deleted :: Ptr{Void}
  rows_reordered :: Ptr{Void}

  get_flags :: Ptr{Void}
  get_n_columns :: Ptr{Void}
  get_column_type :: Ptr{Void}
  get_iter :: Ptr{Void}
  get_path :: Ptr{Void}
  get_value :: Ptr{Void}
  iter_next :: Ptr{Void}
  iter_previous :: Ptr{Void}
  iter_children :: Ptr{Void}
  iter_has_child :: Ptr{Void}
  iter_n_children :: Ptr{Void}
  iter_nth_child :: Ptr{Void}
  iter_parent :: Ptr{Void}
  ref_node :: Ptr{Void}
  unref_node :: Ptr{Void}
end
type GtkTreeIterImpl
  stamp :: Cint
  user1 :: UInt64
  user2 :: UInt64
  user3 :: UInt64
end

max_stars_repo_name: barcharcraz/eve-julia-gui

max_issues_repo_name: barcharcraz/eve-julia-gui

max_forks_repo_name: barcharcraz/eve-julia-gui


text:
include("settings.jl")

makedocs(; sitename=sitename, settings...)

deploydocs(; repo="github.com/ITensor/ITensorsBenchmarks.jl.git", devbranch="main", push_preview=true)


text:
function normalsum(x, y, m)
    ((x % m) + (y % m)) % m
end

function fastsum(x, y, m)
    T = typeof(x)
    xy = x + y
    (xy - ( Base.ashr_int(xy, sizeof(T)*8 - 1) & (m^2) ) ) % m
end

T = UInt8
m = T(11)
x = T(9)

for y in T(0) : T(typemax(T) - x)
    normal  = normalsum(x, y, m)
    fast = fastsum(x, y, m)
    if normal != fast
        println("$x + $y = $normal,  fast = $fast")
    end
end

################

T = UInt64
m = T(2^31-1)
x = T(232423)

for y in rand(T, 1000)
    normal  = normalsum(x, y, m)
    fast = fastsum(x, y, m)
    if normal != fast
        println("$x + $y = $normal,  fast = $fast")
    end
end


text:
using Plots
using Measures

include("helper_functions.jl")

begin
    λ1 = 1
    λ2 = 1.5
    α = 1
    β = 1
    μ(α) = 1 / (1.5 * (α))
    ν(α) = 1 / (0.7 * (α))
    parameters = (λ1, λ2, α, μ, ν)
    he_parameters = (λ1, λ2, α, μ, ν, β)
    # opponent_parameters = (λ2, λ1, α, μ, ν)
    # opponent_he_parameters = (λ2, λ1, α, μ, ν, β)
    # qs = 0:0.001:1
end

itr = 0.1:0.05:2.1

poa(1.5, 1.5, α, μ, ν)
heatmap(itr, itr, (x, y) -> poa(x, y, α, μ, ν))
surface(itr, itr, (x, y) -> poa(x, y, α, μ, ν))
# heatmap(itr, itr, (x, y) -> total_cost(equilibrium_probability(x, y, α, μ, ν)..., x, y, α, μ, ν))
# heatmap(itr, itr, (x, y) -> total_cost(he_equilibrium_probability(x, y, α, μ, ν, 1)..., x, y, α, μ, ν))
# plot(0.666:0.00001:0.667, 2.095:0.00001:2.0953, (x, y) -> poa(x, y, α, μ, ν), st = :contourf)
poa(0.66655, 2.09522, 1, μ, ν)
poa(0.666, 2.095, 1, μ, ν)
poa(0.66, 2.0, 1, μ, ν)
poac(x, y) = poa(x, y, 1, μ, ν)
poac(0.1, 2.095)

plot!(
    xlabel = "Player 1 arrival rate",
    ylabel = "Player 2 arrival rate",
    title = "Price of Anarchy for Various Arrival Rates",
    xticks = 0:0.25:2,
    yticks = 0:0.25:2,
    clim = (1, Inf),
    margin = 6pt,
    size = (450, 400),
)
annotate!(1.45, 1.45, text("Infeasible \n Arrival Rates", 9, rotation = -45))

savefig("outputs/price_of_anarchy_heatmap.pdf")


text:
mutable struct Input
    graph::DiGraph
    weights::Array{Float64,2}
    ndds::Array{Int64,1}
    max_cycle_length::Int64
    max_chain_length::Int64
    solver_instance::Any
    time_param::String
    time_factor::Float64
    start_time::Float64

    function Input(
        graph::DiGraph,
        weights::Array{Float64,2},
        ndds::Array{Int64,1},
        max_cycle_length::Int64,
        max_chain_length::Int64,
        solver_instance::Any,
        time_param::String,
        time_factor::Float64,
        start_time::Float64
    )
        new(graph, weights, ndds, max_cycle_length, max_chain_length, solver_instance, time_param, time_factor, start_time)
    end
end

mutable struct Output
    match_vertices::Array{Float64,1}
    match_edges::Any
    match_cycles::Union{Array{Float64,1}, Nothing}
    graph_cycles::Union{Array{Array{Int64,1},1}, Nothing}
    value::Float64
    optimal::Bool

    function Output()
        match_vertices = Float64[]
        match_edges = Float64[]
        match_cycles = Array{Float64}[]
        graph_cycles = Array{Float64}[]
        value = typemin(Float64)
        optimal = false
        new(match_vertices, match_edges, match_cycles, graph_cycles, value, optimal)
    end

    function Output(
        match_vertices::Array{Float64,1},
        match_edges::Any,
        match_cycles::Union{Array{Float64,1}, Nothing},
        graph_cycles::Union{Array{Array{Int64,1},1}, Nothing},
        value::Float64,
        optimal::Bool,
    )
        new(match_vertices, match_edges, match_cycles, graph_cycles, value, optimal)
    end
end


text:
### A Pluto.jl notebook ###
# v0.12.18

using Markdown
using InteractiveUtils

# ╔═╡ 621fa420-5392-11eb-1c1e-d35ed6a9ddc0
begin
	using OffsetArrays
	using BenchmarkTools
	using Memoization
end

# ╔═╡ d35a7228-5394-11eb-29b1-43cd660605f0
md"
This notebook shows a translation of [this notebook](https://www.kaggle.com/lewisfogden/the-life-modelling-problem) into Julia and an example of memoization of actuarial calculations.

To *not* memoize, remove the `@memoize` placed before various function definitions.

When memoized, the calculations benchmark goes from `~650µs` to `~15µs`
"

# ╔═╡ 135c48c4-5391-11eb-1941-07f9ffd5e22d
q = OffsetArray([0.001,
     0.002,
     0.003,
     0.003,
     0.004,
     0.004,
     0.005,
     0.007,
     0.009,
     0.011],-1)

# ╔═╡ 3e501fda-5391-11eb-2c84-dfc93c9b8871
w = OffsetArray([0.05,
     0.07,
     0.08,
     0.10,
     0.14,
     0.20,
     0.20,
     0.20,
     0.10,
     0.04],-1)

# ╔═╡ d6f1f9da-5395-11eb-2608-a10b027a9721
md" Note that all of the loose parameters in the source notebook are combined into one parameters tuple:"

# ╔═╡ 55440cf6-5391-11eb-06f7-ed0c64129bde
params = (
	prem = 100,
	face = 25_000,
	term = 10,
	w = w,
	q = q,
	int_rate = 0.02
	)

# ╔═╡ 6d50caa0-5391-11eb-0572-9de6d4af4b85
begin
	@memoize function num_in_force(t,params)
		if t == 0
			return 1.0
		elseif t >= params.term
			return 0.0
		else
			return num_in_force(t-1,params) - num_deaths(t-1,params) - num_lapses(t-1,params)
		end
	end

	@memoize function num_deaths(t,params)
		if t < params.term
			return num_in_force(t,params) * params.q[t]
		else
			return 0
		end
	end

	@memoize function num_lapses(t,params)
		if t < params.term
			return num_in_force(t,params) * params.w[t]
		end
	end

end

# ╔═╡ e275cd2a-5392-11eb-2e41-a5eddbdaa5e9
begin
	claims(t,params) = num_deaths(t,params) * params.face
	premiums(t, params) = num_in_force(t,params) * params.prem
	net_cashflows(t,params) = return premiums(t,params) - claims(t,params)
end

# ╔═╡ 9478fbba-5392-11eb-017b-91c4a8ddde90
map(0:10) do t
	(
		time = t,
		ℓ = num_in_force(t,params),
		claims = claims(t,params),
		premiums = premiums(t,params),
		net_cfs = net_cashflows(t,params),
	)
end

# ╔═╡ 4109cc9c-5393-11eb-3e82-59e4b89f6e05
function npv(cashflow, params)
	val = 0
	for t in 0:params.term
		val = (val + cashflow(t, params)) / (1 + params.int_rate)
	end
	return val
end

# ╔═╡ 83ce88a6-5393-11eb-0c7c-551d48ada79d
@benchmark npv(net_cashflows,params)

# ╔═╡ 24013174-5395-11eb-0ed6-2f9b874a2d20

# ╔═╡ Cell order:
# ╟─d35a7228-5394-11eb-29b1-43cd660605f0
# ╠═621fa420-5392-11eb-1c1e-d35ed6a9ddc0
# ╠═135c48c4-5391-11eb-1941-07f9ffd5e22d
# ╠═3e501fda-5391-11eb-2c84-dfc93c9b8871
# ╟─d6f1f9da-5395-11eb-2608-a10b027a9721
# ╠═55440cf6-5391-11eb-06f7-ed0c64129bde
# ╠═6d50caa0-5391-11eb-0572-9de6d4af4b85
# ╠═e275cd2a-5392-11eb-2e41-a5eddbdaa5e9
# ╠═9478fbba-5392-11eb-017b-91c4a8ddde90
# ╠═4109cc9c-5393-11eb-3e82-59e4b89f6e05
# ╠═83ce88a6-5393-11eb-0c7c-551d48ada79d
# ╠═24013174-5395-11eb-0ed6-2f9b874a2d20

max_stars_repo_name: JeannotJeannot/Learn

max_issues_repo_name: JeannotJeannot/Learn

max_forks_repo_name: JeannotJeannot/Learn


text:
function LongestWord(sen::String)
    sentence =[(split(sen, " "))]
    parole = [length(x) for x in split(sen, " ")]
    parole_index = (findmax(parole))
    index_n = (parole_index[2])::Int64
    print(sentence, length(sentence))
    return((parole, index_n, length(parole)))
    #println(sentence[index_n])
end

LongestWord("Ciao pippo come va tutto bene djhakdfjhsdfk oiweruwotidfgsjdfhgsdjhfgsdjfhgsdjfgdsjhfgsjfgdpweokudfks?")

function LongestWord(sen::AbstractString)
    word = [(length(x), x) for x in split(sen, " ")]
    findmax(word)[1][2]
end

LongestWord("Hello, how are you? nested, punctuation?")

#Solution from StackOver flow
#https://stackoverflow.com/questions/49775954/julia-how-to-find-the-longest-word-in-a-given-string/49779704#49779704

function LongestWord2(sen::AbstractString)
           words = matchall(r"\w+", sen) #questa funzione è incredibile e mi ritorna ogni parola!
           words[findmax(length.(words))[2]]
       end

LongestWord2("Ciao pippo come stai, come va tutto, ?jhgjhgfhgfhg, bene? che fai di bellojfhghkgjhfjg")

#problem it shows also punctuation
function LongestWord3(sen::AbstractString)
           word = split(sen, " ")
           word[indmax(length.(word))]
       end

LongestWord3("Hello, how are you? nested, ?punctuation, rano?")

#it splits strangely
function LongestWord2(sen::AbstractString)
           words = split(sen, r"\w+")
           print(words)
           words[findmax(length.(words))[2]]
end

LongestWord2("Ciao pippo come stai, come va tutto bene? che fai di bello!")

#I have not manage to find the right answer to this problem right now, but I will think on that
function FirstFactorial(numero::Int64)

    number_before = collect(1:numero)
    lista = [(x) for x in number_before]
    print(lista)
end

FirstFactorial(8)

function FirstFactorial1(numero::Int64)
    return(factorial(numero))
end

FirstFactorial1(8)

#It is a superficial solution, I am missing how to reverse the structure
a = []
function FirstReverse(stringa::AbstractString)
    for x in matchall(r"\w+", stringa) #se metti uno spazio dopo la w+, la regex cambia!
        insert!(a,1, reverse(x))#https://docs.julialang.org/en/release-0.4/stdlib/collections/?highlight=push#Base.push! this
        #made the trick, but now it is printing all the process
        #the insert! takes(array, index, element)
    end
    println(a)#if I insert here the print I get the results after the loop is done, so I get the final function.
    #I guess that the presence of this in the loop could be good for debugging purposes
end

FirstReverse("I Love Code")

#= Reasoning here. First: i will need a split in every letter and make an string array of it.
Second: Create an array of letter string, where all the alphabet is
Third: Match the letters which appears on the given string with the ones in the letter array.This will give the index.
Fifth: If the letter is a Z in the given string, the index on the letter array needs to go back to 1
=#

function LetterChanges(stringa::AbstractString)
    #faccio le lettere
    #alphabet = convert(String, collect('a':'z'))#in questo modo converto da char in string \:curry:
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    #Il print dopo mi serve per confermare che i caratteri sono in string e che sono stati convertiti
    println(typeof(alphabet))
    vowels = "aeiou"
    #converto il testo iniziale in stringhe
    for Char(x) in split(stringa, "")
        if x == 'a'
            x = 'Z'
        elseif x in vowels
            uppercase(x)
            else
            Int(x)+1
            Char(x)
            println(x)
        end
    end
end

    #devo trovare il modo di matchare le lettere in alphabet e farmi dare l'index, cosi' posso sommarlo di uno
    #dovrei fare un array di match da alphabet
    #matched = [eachindex(x) for x in testo_iniziale if contains(alphabet, x)]

    #println(length(testo_iniziale))

LetterChanges("Ciao pippo come stai")

#https://gist.github.com/zemadi/11071837
#this solution is very important but it is only for the python 3
def LetterChanges(str):
	lower = str.lower()

	newstring = ""
	lookup = 'abcdefghijklmnopqrstuvwxyz'
	vowels = "aeiou"

	for letter in lower:
	  if letter == "z":
	    newstring += "A"
	  else:
	    letter_index = lookup.index(letter)
	    if lookup[(letter_index+1)] in vowels:
	      vowel_set = lookup[(letter_index+1)]
	      newstring += vowel_set.upper()
	    else:
	      newstring += lookup[(letter_index+1)]
print newstring

def LetterChanges(str):

  # our new string with the modified characters
  newString = ""

  # begin by looping through each character in the string
  for char in str:

    # check if the current character is an alphabetic character
    if char.isalpha():

      # check if character is z
      if char.lower() == 'z':
        char = 'a'

      # if alphabetic character then add 1 to its ASCII value
      # by using the built-in ord function then convert back to character
      else:
        char = chr(ord(char) + 1)

    # if new character is a vowel then capitalize it
    if char in 'aeiou':
      char = char.upper()

    # add this modified character to the new string
    newString = newString + char

  return newString

print LetterChanges("fun times!")

println(Int('a'))

function changeletters(str::String)
    vowels = "aeiouy"
    carr = Vector{Char}(length(str))
    i = 0
    for c in str
        newchar = c == 'z' ? 'a' : c + 1
        #changer = c in vowels? uppercase(c):c
        carr[i+=1] = newchar in vowels ? uppercase(newchar) : newchar
    end
    return String(carr)
end

changeletters("coderbyte")

function LetterChanges2(str::AbstractString)
    v = Set("aeiou")
    #sprint(sizehint=sizeof(str)) do io # use on Julia 0.7 - new keyword argument
    sprint() do io # use on Julia 0.6.2
        for c in str
            c = c == 'z' ? 'a' : c+1 # we assume that we got only letters from 'a':'z'
            print(io, c in v ? uppercase(c) : c)

        end
    end
end

LetterChanges2("coderbyte")

function SimpleAdding(num::Int64)
    #set borders with an if. Note that the first end has to be at the end of the if
    if num > 1000
        return("The number is too big!!")
    end

    for x in reverse(collect(0:num))
        sum = (x*(1+(x))/2)
        #1+1/2= 0; 2+4/2=3;3+9/2
        return(sum)
    end
end

SimpleAdding(15)

function LetterCapitalize(str::AbstractString)
    list = [(string(uppercase(x[1])*x[2:end] * " ")) for x in matchall(r"\w+", str)]
        return(join(list))
end

LetterCapitalize("i ran there last day come stai sei pazzo")

#this function works fine, but the only problem is that once the interger introduced are the same, then the progrsm troll me with an error, for a reason which I do not understand at the moment
function checknumber(num_a::Integer, num_b::Integer)
    if num_b > num_a ? print("True"):num_b < num_a print("False")
    elseif num_a == num_b
        print(-1)
    end
    #return(num_a+num_b)
  end
checknumber(67,67)

function TimeConvert(num::Integer)
    hours = floor(round((num / 60.0), 1), 0)
    if num <= 59
        hours = 0
    end
    minutes = (num % 60)
    if minutes <= 1 && hours <=1
        tempo = ["hour", "minute"]
    elseif minutes > 1 && hours > 1
        tempo = ["hours", "minutes"]
    elseif hours <= 1 && minutes >1
        tempo = ["hour", "minutes"]
    else
        tempo = ["hours", "minute"]
    end
    return(println(hours," ", tempo[1], " : ",minutes, " ", tempo[2]))
end

TimeConvert(63)

function AlphabetSoup(stri::AbstractString)

        lista = [x for x in split(stri, "") if x != " "]
        #Amount of letter for adding the spaces every 4 spaces
        #final = [split(x, "") for x in lista if length > 4]
        #THIS IS THE APPROACH IN PYTHON#s = " ".join(s[i:i+2] for i in range(0, len(s), 2))
        #ricordati della idea di fare un dizionario con carattere da una parte e dall'altra il numero ascii
        return (join(sort(lista)))
end

AlphabetSoup("ciao dottore pussone pissone")

function KaprekarsConstant(num::AbstractString)
    #Control of the length and of the values, I am treating the number as a string
    if length(num) >= 4
        println("Performing operation...")
    else
        println("The lenght of the entered number is not big enough, minumum 4 digits")
      end
        values = [x for x in num]
        values = sort(values)
        values = Set(values)
        values = join(values, "")

return(values)
end

KaprekarsConstant("1876867578779812343264364776896977")

#I can do the set comphrehension also on sets
a = collect(1:100)
b = Set(x for x in a  if x % 2 == 0 && x % 3 == 0)

function CorrectPath(str::AbstractString)


text:
import .ForwardDiff

const DiffResult = ForwardDiff.DiffResults.DiffResult

function cld_fast(a::A,b::B) where {A,B}
    T = promote_type(A,B)
    cld_fast(a%T,b%T)
end
function cld_fast(n::T, d::T) where {T}
    x = Base.udiv_int(n, d)
    x += n != d*x
end

store_val!(r::Base.RefValue{T}, x::T) where {T} = (r[] = x)
store_val!(r::Ptr{T}, x::T) where {T} = Base.unsafe_store!(r, x)

function evaluate_chunks!(f::F, (r,Δx,x), start, stop, ::ForwardDiff.Chunk{C}) where {F,C}
    cfg = ForwardDiff.GradientConfig(f, x, ForwardDiff.Chunk{C}(), nothing)
    N = length(x)
    last_stop = cld_fast(N, C)
    is_last = last_stop == stop
    stop -= is_last

    xdual = cfg.duals
    seeds = cfg.seeds
    ForwardDiff.seed!(xdual, x)
    for c ∈ start:stop
        i = (c-1) * C + 1
        ForwardDiff.seed!(xdual, x, i, seeds)
        ydual = f(xdual)
        ForwardDiff.extract_gradient_chunk!(Nothing, Δx, ydual, i, C)
        ForwardDiff.seed!(xdual, x, i)
    end
    if is_last
        lastchunksize = C + N - last_stop*C
        lastchunkindex = N - lastchunksize + 1
        ForwardDiff.seed!(xdual, x, lastchunkindex, seeds, lastchunksize)
        _ydual = f(xdual)
        ForwardDiff.extract_gradient_chunk!(Nothing, Δx, _ydual, lastchunkindex, lastchunksize)
        store_val!(r, ForwardDiff.value(_ydual))
    end
end

function threaded_gradient!(f::F, Δx::AbstractVector, x::AbstractVector, ::ForwardDiff.Chunk{C}) where {F,C}
    N = length(x)
    d = cld_fast(N, C)
    r = Ref{eltype(Δx)}()
    batch((d,min(d,num_threads())), r, Δx, x) do rΔxx,start,stop
        evaluate_chunks!(f, rΔxx, start, stop, ForwardDiff.Chunk{C}())
    end
    r[]
end


text:
export @prisec_str

macro prisec_str(s)
  a = Array{Bool,1}()
  pos = 1
  done = false
  while ~done
    m = match(r"[sp]"i,s,pos)
    if m!=nothing
      pos = m.offset + 1
      push!(a, m.match in ("P","p"))
    else
      done = true
    end
  end
  Tuple(a)
end


text:
using Dates

function startup(outdir::String; remove_existing::Bool=false)
    # if no outdir specified, error out
    if outdir == ""
        error("Output folder cannot be empty string.")
    end

    # create output folder if it doesn't exist already
    if isdir(outdir) && remove_existing
        rm(outdir, recursive=true)
    end
    if !isdir(outdir)
        mkdir(outdir)
    end

    # copy execution script to outdir folder
    scriptname = basename(Base.source_path())
    dst = joinpath(outdir, scriptname)
    try
        cp(Base.source_path(), dst)
    catch e
        if isa(e, ArgumentError) # file already exist
            nothing
        else
            throw(e)
        end
    end

    timenow = now()
    datef   = Dates.format(timenow, "e, dd u yyyy (HH:MM:SS)")

    date    = string(datef)
    host    = gethostname()
    user    = try
        ENV["USER"]
    catch e
        if isa(e, KeyError) # probably on windows
            splitdir(homedir())[end]
        else
            throw(e)
        end
    end

    num_threads = try
        ENV["JULIA_NUM_THREADS"]
    catch e
        if isa(e, KeyError)
            # no JULIA_NUM_THREADS defined; set num_threads to 1
            1
        else
            # unknown error
            throw(e)
        end
    end

    println("-------------------------------------------------------------")

    println(raw"                                     _      ")
    println(raw"                                 .:'/   _..._  ")
    println(raw"           Jecco                // ( ```-.._.'  ")
    println(raw"                                \| /    0\___    ")
    println(raw"                                |     0      \    ")
    println(raw"       Julia Einstein           |            /  ")
    println(raw"                                \_       .--'  ")
    println(raw"    Characteristic Code         (_'---'`)      ")
    println(raw"                                / `'---`|  ")
    println(raw"                              ,'        |  ")
    println(raw"              .            .'`          |  ")
    println(raw"              )\       _.-'             ;  ")
    println(raw"             / |    .'`   _            /  ")
    println(raw"           /` /   .'       '.        , |  ")
    println(raw"          /  /   /           \   ;   | |  ")
    println(raw"          |  \  |            |  .|   | |  ")
    println(raw"           \  ``|           /.-' |   | |  ")
    println(raw"            '-..-\       _.;.._  |   |.;-.  ")
    println(raw"                  \    <`.._  )) |  .;-. ))  ")
    println(raw"                  (__.  `  ))-'  \_    ))'   ")
    println(raw"                      `'--``       `````  ")

    println("-------------------------------------------------------------")
    println("")

    println("Run date:          $date")
    println("Run host:          $host")
    println("username:          $user")
    println("")
    println("This process contains $num_threads threads")
    println("")

end


text:
struct LDAPConnection
    handle::Ptr{Cvoid}
    url::String
end

# typedef struct ldap_url_desc
struct LDAPURLDesc
    lud_next::Ptr{Cvoid}
    lud_scheme::Cstring
    lud_host::Cstring
    lud_port::Cint
    lud_dn::Cstring
    lud_attrs::Ptr{Ptr{UInt8}}
    lud_scope::Cint
    lud_filter::Cstring
    lud_exts::Ptr{Ptr{UInt8}}
    lud_crit_exts::Cint
end

struct URL
    scheme::String
    host::String
    port::Int
    dn::Union{Nothing, String}
    attrs::Vector{String}
    scope::Int
    filter::Union{Nothing, String}
    exts::Vector{String}
    crit_exts::Int
end

Base.:(==)(ua::URL, ub::URL) = ua.scheme == ub.scheme && ua.host == ub.host && ua.port == ub.port && ua.dn == ub.dn && ua.attrs == ub.attrs && ua.scope == ub.scope && ua.filter == ub.filter && ua.exts == ub.exts && ua.crit_exts == ub.crit_exts

abstract type AuthenticationResult end

struct AuthOk <: AuthenticationResult
    uri::String
    who::String
end

struct AuthErr <: AuthenticationResult
    uri::String
    who::String
    err_code::Cint
end


text:
using Plots
using Reproduce
using JLD2
using FileIO
include("plot_utils.jl")

function plot_single_intrinsic_reward(results ; smooth_step = 300)
    save_file = "plotting/chunlok/generated_plots/ttmaze_intrinsic_reward.svg"

    p = plot()
    logger_key = :wc_per_demon

    intrinsic_rewards = results[logger_key]
    num_steps = size(intrinsic_rewards)[2]

    for i in 1:4
        line = smooth_lines(intrinsic_rewards[i, :], smooth_step)
        xs = 1:smooth_step:num_steps
        # println(line)
        # println(size(error[i, :]))
        plot!(p, xs, line)
    end

    # print(error[3,10])
    savefig(save_file)
    println("Single intrinsic reward plot saved to $(save_file)")
end

max_stars_repo_name: MatthewMcLeod/curiosity

max_issues_repo_name: MatthewMcLeod/curiosity

max_forks_repo_name: MatthewMcLeod/curiosity


text:
# SAM Meta-Information
# ====================

mutable struct MetaInfo
    # data and filled range
    data::Vector{UInt8}
    filled::UnitRange{Int}
    # indexes
    tag::UnitRange{Int}
    val::UnitRange{Int}
    dictkey::Vector{UnitRange{Int}}
    dictval::Vector{UnitRange{Int}}
end

function MetaInfo(data::Vector{UInt8}=UInt8[])
    metainfo = MetaInfo(data, 1:0, 1:0, 1:0, UnitRange{Int}[], UnitRange{Int}[])
    if !isempty(data)
        index!(metainfo)
    end
    return metainfo
end

"""
    MetaInfo(str::AbstractString)

Create a SAM metainfo from `str`.

# Examples

    julia> SAM.MetaInfo("@CO\tsome comment")
    BioAlignments.SAM.MetaInfo:
        tag: CO
      value: some comment

    julia> SAM.MetaInfo("@SQ\tSN:chr1\tLN:12345")
    BioAlignments.SAM.MetaInfo:
        tag: SQ
      value: SN=chr1 LN=12345

"""
function MetaInfo(str::AbstractString)
    return MetaInfo(Vector{UInt8}(str))
end

"""
    MetaInfo(tag::AbstractString, value)

Create a SAM metainfo with `tag` and `value`.

`tag` is a two-byte ASCII string. If `tag` is `"CO"`, `value` must be a string;
otherwise, `value` is an iterable object with key and value pairs.

# Examples

    julia> SAM.MetaInfo("CO", "some comment")
    BioAlignments.SAM.MetaInfo:
        tag: CO
      value: some comment

    julia> string(ans)
    "@CO\tsome comment"

    julia> SAM.MetaInfo("SQ", ["SN" => "chr1", "LN" => 12345])
    BioAlignments.SAM.MetaInfo:
        tag: SQ
      value: SN=chr1 LN=12345

    julia> string(ans)
    "@SQ\tSN:chr1\tLN:12345"

"""
function MetaInfo(tag::AbstractString, value)
    buf = IOBuffer()
    if tag == "CO"  # comment
        if !isa(value, AbstractString)
            throw(ArgumentError("value must be a string"))
        end
        write(buf, "@CO\t", value)
    elseif occursin(r"[A-Z][A-Z]", tag)
        print(buf, '@', tag)
        for (key, val) in value
            print(buf, '\t', key, ':', val)
        end
    else
        throw(ArgumentError("tag must match r\"[A-Z][A-Z]\""))
    end
    return MetaInfo(take!(buf))
end

function initialize!(metainfo::MetaInfo)
    metainfo.filled = 1:0
    metainfo.tag = 1:0
    metainfo.val = 1:0
    empty!(metainfo.dictkey)
    empty!(metainfo.dictval)
    return metainfo
end

function isfilled(metainfo::MetaInfo)
    return !isempty(metainfo.filled)
end

function datarange(metainfo::MetaInfo)
    return metainfo.filled
end

function checkfilled(metainfo::MetaInfo)
    if !isfilled(metainfo)
        throw(ArgumentError("unfilled SAM metainfo"))
    end
end

function isequalkey(metainfo::MetaInfo, key::AbstractString)
    if !isfilled(metainfo) || sizeof(key) != 2
        return false
    end
    k1, k2 = UInt8(key[1]), UInt8(key[2])
    return metainfo.data[metainfo.tag[1]] == k1 && metainfo.data[metainfo.tag[2]] == k2
end

function Base.show(io::IO, metainfo::MetaInfo)
    print(io, summary(metainfo), ':')
    if isfilled(metainfo)
        println(io)
        println(io, "    tag: ", tag(metainfo))
          print(io, "  value:")
        if !iscomment(metainfo)
            for (key, val) in zip(keys(metainfo), values(metainfo))
                print(io, ' ', key, '=', val)
            end
        else
            print(io, ' ', value(metainfo))
        end
    else
        print(io, " <not filled>")
    end
end

function Base.print(io::IO, metainfo::MetaInfo)
    write(io, metainfo)
    return nothing
end

function Base.write(io::IO, metainfo::MetaInfo)
    checkfilled(metainfo)
    r = datarange(metainfo)
    return unsafe_write(io, pointer(metainfo.data, first(r)), length(r))
end

# Accessor Functions
# ------------------

"""
    iscomment(metainfo::MetaInfo)::Bool

Test if `metainfo` is a comment (i.e. its tag is "CO").
"""
function iscomment(metainfo::MetaInfo)::Bool
    return isequalkey(metainfo, "CO")
end

"""
    tag(metainfo::MetaInfo)::String

Get the tag of `metainfo`.
"""
function tag(metainfo::MetaInfo)::String
    checkfilled(metainfo)
    return String(metainfo.data[metainfo.tag])
end

"""
    value(metainfo::MetaInfo)::String

Get the value of `metainfo` as a string.
"""
function value(metainfo::MetaInfo)::String
    checkfilled(metainfo)
    return String(metainfo.data[metainfo.val])
end

"""
    keyvalues(metainfo::MetaInfo)::Vector{Pair{String,String}}

Get the values of `metainfo` as string pairs.
"""
function keyvalues(metainfo::MetaInfo)::Vector{Pair{String,String}}
    checkfilled(metainfo)
    if iscomment(metainfo)
        throw(ArgumentError("not a dictionary"))
    end
    return Pair{String,String}[key => val for (key, val) in zip(keys(metainfo), values(metainfo))]
end

function Base.keys(metainfo::MetaInfo)
    checkfilled(metainfo)
    if iscomment(metainfo)
        throw(ArgumentError("not a dictionary"))
    end
    return [String(metainfo.data[r]) for r in metainfo.dictkey]
end

function Base.values(metainfo::MetaInfo)
    checkfilled(metainfo)
    if iscomment(metainfo)
        throw(ArgumentError("not a dictionary"))
    end
    return [String(metainfo.data[r]) for r in metainfo.dictval]
end

function Base.haskey(metainfo::MetaInfo, key::AbstractString)
    return findkey(metainfo, key) > 0
end

function Base.getindex(metainfo::MetaInfo, key::AbstractString)
    i = findkey(metainfo, key)
    if i == 0
        throw(KeyError(key))
    end
    return String(metainfo.data[metainfo.dictval[i]])
end

function findkey(metainfo::MetaInfo, key::AbstractString)
    checkfilled(metainfo)
    if sizeof(key) != 2
        return 0
    end
    t1, t2 = UInt8(key[1]), UInt8(key[2])
    for (i, k) in enumerate(metainfo.dictkey)
        if metainfo.data[first(k)] == t1 && metainfo.data[first(k)+1] == t2
            return i
        end
    end
    return 0
end


text:
using BinaryBuilder

name = "Lua"
version = v"5.4.3"

sources = [
    ArchiveSource("https://www.lua.org/ftp/lua-$(version).tar.gz",
                  "f8612276169e3bfcbcfb8f226195bfc6e466fe13042f1076cbde92b7ec96bbfb"),
    DirectorySource("./bundled"),
]

script = raw"""
cd ${WORKSPACE}/srcdir/lua-*

atomic_patch -p1 "${WORKSPACE}/srcdir/patches/src_Makefile.patch"
atomic_patch -p1 "${WORKSPACE}/srcdir/patches/src_lauxlib.c.patch"

if [[ ${target} == *-apple-* ]]; then
    MAKE_TARGET=macosx
elif [[ ${target} == *-freebsd* ]]; then
    # NOTE: The FreeBSD ports build also uses the bsd instead of the freebsd target,
    # since it hard-codes fewer things, apparently
    MAKE_TARGET=bsd
elif [[ ${target} == *-mingw* ]]; then
    MAKE_TARGET=mingw
else
    MAKE_TARGET=linux
    export CPPFLAGS="-I${prefix}/include"
fi

# XXX: Work around Lua apparently not understanding its own Windows setup
if [[ ${target} == *-mingw* ]]; then
    TO_BIN="lua.exe luac.exe"
    TO_LIB="lua54.dll"
else
    TO_BIN="lua luac"
    TO_LIB="liblua.${dlext}"
fi

make -j${nproc} ${MAKE_TARGET} DLEXT="${dlext}"
make install INSTALL_TOP="${prefix}" INSTALL_LIB="${libdir}" TO_BIN="${TO_BIN}" TO_LIB="${TO_LIB}"

install_license "${WORKSPACE}/srcdir/LICENSE"
"""

platforms = supported_platforms(experimental=true)

products = [
    ExecutableProduct("lua", :lua),
    ExecutableProduct("luac", :luac),
    LibraryProduct(["liblua", "lua54"], :liblua),
]

dependencies = [
    Dependency("Readline_jll"),
]

build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies;
               julia_compat="1.6")

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
#!/usr/bin/env julia

using Eigenbroetler

function lachryma(x::Number, y::Number)
    r = sqrt(x * x + y * y)
    return exp(-(r / 100) ^ 2) * exp(2 * im * ((x + y) * exp(-(r / 100) ^ 2)))
end

eb = fft(Eigenbrot(lachryma, 512, 512))
save("lachryma.png", eb, ImageSetting(Magn, LogScale), colours = :rainbow)


text:
ENV["PKG_CONFIG_PATH"] = "/Users/dc/anaconda/envs/python35/lib/pkgconfig"

using OpenCV
using Images
using Cxx

import ImageView

function opencv_to_image(img_opencv)

    converted_image = zeros(Float16, (3, rows(img_opencv), cols(img_opencv)));

    for i = 1:size(converted_image, 2)
        for j = 1:size(converted_image, 3)
            pixel_value = @cxx at_v3b(img_opencv, i, j)
            converted_image[:, i, j] = map(x -> Int(at(pixel_value, x)), [2, 1, 0]) ./ 255
        end
    end

    return converted_image
end

# C++ OpenCV code
cxx"""

#include "opencv2/videoio.hpp"
#include "opencv2/imgproc.hpp"

using namespace std;
using namespace cv;

/// Retrieve video device by index
cv::VideoCapture get_video_device(int device_index) {

    cv::VideoCapture capture(device_index);
    cv::Mat frame;

    capture.read(frame);

    return capture;
}

/// Capture frame
cv::Mat capture_frame(cv::VideoCapture capture) {

    cv::Mat frame;
    bool Success = capture.read(frame);
    return frame;
}

/// Capture and save frame
void capture_save_frame(cv::VideoCapture capture, String dest) {

    cv::Mat frame;
    bool success = capture.read(frame);

    if (success) {
        cv::imwrite(dest, frame);
    }
}

/// Release an active camera
void release_camera(cv::VideoCapture capture) {
    capture.release();
}

"""

video_device = @cxx get_video_device(CAP_ANY);

@time current_frame = @cxx capture_frame(video_device);
@time current_frame_image = opencv_to_image(current_frame);
ImageView.imshow(colorview(RGB, current_frame_image))

filename = joinpath(pwd(), "camera-frame.jpg");
@time @cxx capture_save_frame(video_device, pointer(filename));
@time current_frame_image_2 = load(filename);
ImageView.imshow(current_frame_image_2)


text:
function Base.:+(x::T, y::S) where {T<:InfExtendedTime, S<:Period}
    isinf(x) ? x : T(x.finitevalue + y)
end
Base.:+(x::S, y::T) where {T<:InfExtendedTime, S<:Period} = y + x
Base.:-(x::T, y::S) where {T<:InfExtendedTime, S<:Period} = x + -y
Base.:-(x::S, y::T) where {T<:InfExtendedTime, S<:Period} = isposinf(y) ? neginf(T) : y + -x

for TType in (TimeType, Period, UTInstant)
    @eval begin
        Base.:+(x::Infinite, y::T) where {T<:$TType} = x
        Base.:+(x::T, y::Infinite) where {T<:$TType} = y
        Base.:-(x::Infinite, y::T) where {T<:$TType} = x
        Base.:-(x::T, y::Infinite) where {T<:$TType} = Infinite(!y.signbit)
    end
end

function Base.:+(x::T, y::Infinite) where {T<:InfExtendedTime}
    if isfinite(x)
        return T(y)
    else
        val = isposinf(x) ? ∞ : -∞
        return T(val + y)
    end
end
Base.:+(x::Infinite, y::T) where {T<:InfExtendedTime} = y + x
function Base.:-(x::T, y::Infinite) where {T<:InfExtendedTime}
    if isfinite(x)
        return T(-y)
    else
        val = isposinf(x) ? ∞ : -∞
        return T(val - y)
    end
end
function Base.:-(x::Infinite, y::T) where {T<:InfExtendedTime}
    if isfinite(y)
        return T(x)
    else
        val = isposinf(y) ? ∞ : -∞
        return T(x - val)
    end
end


text:
# Average waves are usually numerical solutions of the ensemble average wave equations. Here we mostly deal with the scenario where a halfspace filled with particles are ensemble averaged. The resulting govering equations are a 1D Fredholm integral equation.

export intergrand_kernel, average_wave_system, integrate_S, integrate_B
export integration_scheme, trap_scheme, simpson_scheme
export average_error

include("average_waves.jl")
include("numerical_integration.jl")
include("integral_form.jl")
include("reflection.jl")


text:
module PrecompileMacro

export @precompile

function _precompile(func::Expr)
    func_signature = func.args[1]::Expr
    func_signature.head == :where && error("PrecompileMacro.@precompile is not implemented for methods with type parameters")

    signature_args = func_signature.args::Vector{Any}
    func_name = signature_args[1]::Symbol

    # Drop function name and kwargs.
    args = convert(Vector{Expr}, filter(x -> x isa Expr && x.head != :parameters, signature_args))
    types = Tuple(eval(last(arg.args))::DataType for arg in args)
    for type in types
        if !isconcretetype(type)
            error("The type $type in the signature $(func_name)$(types) is not concrete")
        end
    end

    precompile_ex = :(precompile($func_name, $types))

    # Note that `precompile` returns a boolean to indicate whether a statement is active.
    # Might be useful at some point.
    return esc(quote
        Base.@__doc__($func)
        $precompile_ex
    end)
end
precompile(_precompile, (Expr,))

"""
    @precompile(func)

Define function `func` and define a precompile statement for `func`, see `precompile` for more info.
Return whether a precompile statement is active.
"""
macro precompile(func)
    return _precompile(func)
end

end # module


text:
"""
    Compression(c, d, i; σ = 1.0, μ = 0.0)

Maps ``ℝ → (-1, 1)``.

# Arguments
- `c`: the "compression", i.e., the map ``ℝ → (-1, 1)``,
- `d`: the "decompression", i.e., the map ``(-1, 1) → ℝ``,
- `i`: the jacobian of the map, i.e., ``∂d(τ) /∂τ``,
- `σ`, `μ`: control the width and offset in the numerical integrations
"""
struct Compression
	comp::Function
	decomp::Function
	inv_jacobian::Function

	σ::Float64
	μ::Float64
	function Compression(c, d, i; σ = 1.0, μ = 0.0)
		σ ≤ 0.0 && error("σ needs to be positive")
		new(c, d, i, σ, μ)
	end
end

"""
    Algebraic(; σ = 1.0, μ = 0.0)

Maps ``ℝ → (-1, 1)`` by ``t ↦ \\frac{t}{1 + |t|}``.
Equivalent symbol is `:algebraic`.
"""
Algebraic(; σ = 1.0, μ = 0.0) = Compression(
	t ->   t / (1.0 + abs(t)),
	τ ->   τ / (1.0 - abs(τ)),
	τ -> 1.0 / (1.0 - abs(τ))^2, # == (1.0 + abs( τ / (1.0 - abs(τ)) ) )^2
	σ = σ, μ = μ
)

"""
    Exponential(; σ = 1.0, μ = 0.0)

Maps ``ℝ → (-1, 1)`` by ``t ↦ \\mathrm{tanh}(t)``.
Equivalent symbol is `:exponential`.
"""
Exponential(; σ = 1.0, μ = 0.0) = Compression(
	t -> tanh(t),
	τ -> atanh(τ),
	τ -> 1.0 / (1.0 - τ^2), # == cosh(atanh(τ))^2
	σ = σ, μ = μ
)

"""
    Trigonometric(; σ = 1.0, μ = 0.0)

Maps ``ℝ → (-1, 1)`` by ``t ↦ \\frac{2}{π} \\mathrm{tan}^{-1}(t)``.
Equivalent symbol is `:trigonometric`.
"""
Trigonometric(; σ = 1.0, μ = 0.0) = Compression(
	t -> 2.0 * atan(t) / π,
	τ -> tan(π*τ/2.0),
	τ -> π * (1.0 + tan(π*τ/2.0)^2) / 2.0,
	σ = σ, μ = μ
)

Compressions = Dict(
	:algebraic     => Algebraic(),
	:exponential   => Exponential(),
	:trigonometric => Trigonometric()
)


text:
"""
Kibaek Kim - ANL MCS 2016
  Updated in 2020
Farmer example from Birge and Louveaux book.

To use MPI, add
- MPI.Init()
- DSPopt.parallelize(comm)
- MPI.Finalize()
"""

using MPI
using StructJuMP
using DSPopt

MPI.Init()

# Initialize DSPopt.jl with the communicator.
DSPopt.parallelize(MPI.COMM_WORLD)

NS = 3;                        # number of scenarios
probability = [1/3, 1/3, 1/3]; # probability

CROPS  = 1:3 # set of crops (wheat, corn and sugar beets, resp.)
PURCH  = 1:2 # set of crops to purchase (wheat and corn, resp.)
SELL   = 1:4 # set of crops to sell (wheat, corn, sugar beets under 6K and those over 6K)

Cost     = [150 230 260]   # cost of planting crops
Budget   = 500             # budget capacity
Purchase = [238 210];      # purchase price
Sell     = [170 150 36 10] # selling price
Yield    = [3.0 3.6 24.0;
            2.5 3.0 20.0;
            2.0 2.4 16.0]
Minreq   = [200 240 0]     # minimum crop requirement

m = StructuredModel(num_scenarios = NS)

@variable(m, 0 <= x[i=CROPS] <= 500, Int)
@objective(m, Min, sum(Cost[i] * x[i] for i=CROPS))
@constraint(m, const_budget, sum(x[i] for i=CROPS) <= Budget)

# TODO: Distributing blocks is not supported yet.
# This is because of the DSPopt implementation.
for s in 1:NS
    blk = StructuredModel(parent = m, id = s, prob = probability[s])

    @variable(blk, y[j=PURCH] >= 0)
    @variable(blk, w[k=SELL] >= 0)

    @objective(blk, Min, sum(Purchase[j] * y[j] for j=PURCH) - sum(Sell[k] * w[k] for k=SELL))

    @constraint(blk, const_minreq[j=PURCH], Yield[s,j] * x[j] + y[j] - w[j] >= Minreq[j])
    @constraint(blk, const_minreq_beets, Yield[s,3] * x[3] - w[3] - w[4] >= Minreq[3])
    @constraint(blk, const_aux, w[3] <= 6000)
end

status = optimize!(m,
    is_stochastic = true, # Needs to indicate that the model is of the stochastic program.
    solve_type = DSPopt.DW, # see instances(DSPopt.Methods) for other methods
    param = "examples/params.txt" # This path assumes running from the one-level upper directory (i.e., ../).
    )

if DSPopt.myrank() == 0 && status == MOI.OPTIMAL
    @show objective_value(m)
    @show dual_objective_value(m)
    @show value.(x)
    @show dual() # This is available only for solve_type = DSPopt.Dual.
end

MPI.Finalize()


text:
module JSONSchema

# using Compat
using JSON
import HTTP

import Base: isvalid

export Schema, isvalid, diagnose

include("schema.jl")
include("validation.jl")

end # module


text:
# parallel loops:
function buffon(n)
	hit = 0
	for i = 1:n
		mp = rand()
		phi = (rand() * pi) - pi / 2
		xright = mp + cos(phi)/2
		xleft = mp - cos(phi)/2
		# if xright >= 1 || xleft <= 0
		# 	hit += 1
		# end
		p = (xright >= 1 || xleft <= 0) ? 1 : 0
		hit += p
	end
	miss = n - hit
	piapprox = n / hit * 2
end

@time buffon(100000)
# elapsed time: 0.005487779 seconds (96 bytes allocated)
# 3.1467321186947355
@time buffon(100000000)
# elapsed time: 5.362294859 seconds (96 bytes allocated)
# 3.1418351308191026

function buffon_par(n)
	hit = @parallel (+) for i = 1:n
			mp = rand()
			phi = (rand() * pi) - pi / 2
			xright = mp + cos(phi)/2
			xleft = mp - cos(phi)/2
			(xright >= 1 || xleft <= 0) ? 1 : 0
		end
	miss = n - hit
	piapprox = n / hit * 2
end
@time buffon_par(100000)
# elapsed time: 0.005903334 seconds (296920 bytes allocated)
# 3.136762860727729
@time buffon_par(100000000)
# elapsed time: 0.849702686 seconds (300888 bytes allocated)
# 3.141665751394711

# arr is not correctly initialized:
arr = zeros(100000)
@parallel for i=1:100000
  arr[i] = i
end
#> arr only contains zeros!

# parallel maps:
function rank_marray()
	marr = [rand(1000,1000) for i=1:10]
	for arr in marr
	   println(rank(arr))
	end
end

@time rank_marray()
# 1000
# 1000
# 1000
# 1000
# 1000
# 1000
# 1000
# 1000
# 1000
# 1000
# elapsed time: 4.351479797 seconds (166177728 bytes allocated, 1.43% gc time)

function prank_marray()
	marr = [rand(1000,1000) for i=1:10]
	println(pmap(rank, marr))
end
@time prank_marray()
# {1000,1000,1000,1000,1000,1000,1000,1000,1000,1000}
# elapsed time: 2.785466798 seconds (163955848 bytes allocated, 1.96% gc time)


text:
# ---
# title: 279. Perfect Squares
# id: problem279
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Math, Dynamic Programming, Breadth-first Search
# link: <https://leetcode.com/problems/perfect-squares/description/>
# hidden: true
# ---
#
# Given a positive integer _n_ , find the least number of perfect square numbers
# (for example, `1, 4, 9, 16, ...`) which sum to _n_.
#
# **Example 1:**
#
#
#
#     Input: _n_ = 12
#     Output: 3
#     Explanation:12 = 4 + 4 + 4.
#
# **Example 2:**
#
#
#
#     Input: _n_ = 13
#     Output: 2
#     Explanation:13 = 4 + 9.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
function pprint(io::GarishIO, ::MIME"text/plain", s::Set)
    # use default printing if it's the root
    io.state.level == 0 && return show(io, mime, d)

    if isempty(s)
        if get(io, :typeinfo, Any) == typeof(s)
            print_token(io, :type, "Set")
        else
            print_token(io, :type, typeof(s))
            print(io, "()")
        end
    else
        print_token(io, :type, "Set")
        print(io, "(")
        # io.compact && return pprint_list_like(io, X)
        # heurostics to print vector in compact form
        if length(s) < 20 && !max_indent_reached(io, length(string(s)))
            pprint_list_like(io, s; compact=true)
        else
            pprint_list_like(io, s)
        end
        print(io, ")")
    end
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct BlobRestoreStatus <: SwaggerModel
    status::Any # spec type: Union{ Nothing, String } # spec name: status
    failureReason::Any # spec type: Union{ Nothing, String } # spec name: failureReason
    restoreId::Any # spec type: Union{ Nothing, String } # spec name: restoreId
    parameters::Any # spec type: Union{ Nothing, BlobRestoreParameters } # spec name: parameters

    function BlobRestoreStatus(;status=nothing, failureReason=nothing, restoreId=nothing, parameters=nothing)
        o = new()
        validate_property(BlobRestoreStatus, Symbol("status"), status)
        setfield!(o, Symbol("status"), status)
        validate_property(BlobRestoreStatus, Symbol("failureReason"), failureReason)
        setfield!(o, Symbol("failureReason"), failureReason)
        validate_property(BlobRestoreStatus, Symbol("restoreId"), restoreId)
        setfield!(o, Symbol("restoreId"), restoreId)
        validate_property(BlobRestoreStatus, Symbol("parameters"), parameters)
        setfield!(o, Symbol("parameters"), parameters)
        o
    end
end # type BlobRestoreStatus

const _property_map_BlobRestoreStatus = Dict{Symbol,Symbol}(Symbol("status")=>Symbol("status"), Symbol("failureReason")=>Symbol("failureReason"), Symbol("restoreId")=>Symbol("restoreId"), Symbol("parameters")=>Symbol("parameters"))
const _property_types_BlobRestoreStatus = Dict{Symbol,String}(Symbol("status")=>"String", Symbol("failureReason")=>"String", Symbol("restoreId")=>"String", Symbol("parameters")=>"BlobRestoreParameters")
Base.propertynames(::Type{ BlobRestoreStatus }) = collect(keys(_property_map_BlobRestoreStatus))
Swagger.property_type(::Type{ BlobRestoreStatus }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_BlobRestoreStatus[name]))}
Swagger.field_name(::Type{ BlobRestoreStatus }, property_name::Symbol) =  _property_map_BlobRestoreStatus[property_name]

const _allowed_BlobRestoreStatus_status = ["InProgress", "Complete", "Failed"]

function check_required(o::BlobRestoreStatus)
    true
end

function validate_property(::Type{ BlobRestoreStatus }, name::Symbol, val)
    if name === Symbol("status")
        Swagger.validate_param(name, "BlobRestoreStatus", :enum, val, _allowed_BlobRestoreStatus_status)
    end
end