text:
int_rules_4_1_4_2 = @theory begin

    #= ::Subsection::Closed:: =#
    #= 4.1.4.2*(a+b*sin)^m*(c+d*sin)^n*(A+B*sin+C*sin^2) =#
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (1 / (~b) ^ 2) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * ((~b * ~B - ~a * ~C) + ~b * ~C * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && EqQ((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C, 0))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) / (~b) ^ 2) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * (~a - ~b * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && EqQ(~A * (~b) ^ 2 + (~a) ^ 2 * ~C, 0))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-((~b * ~c - ~a * ~d)) * ((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1)) / ((~b) ^ 2 * ~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) - (1 / ((~b) ^ 2 * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * Simp((~b * (~m + 1) * ((~b * ~B - ~a * ~C) * (~b * ~c - ~a * ~d) - ~A * ~b * (~a * ~c - ~b * ~d)) + (~b * ~B * (((~a) ^ 2 * ~d + (~b) ^ 2 * ~d * (~m + 1)) - ~a * ~b * ~c * (~m + 2)) + (~b * ~c - ~a * ~d) * (~A * (~b) ^ 2 * (~m + 2) + ~C * ((~a) ^ 2 + (~b) ^ 2 * (~m + 1)))) * sin(~e + ~f * ~x)) - ~b * ~C * ~d * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && LtQ(~m, -1)))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-((~b * ~c - ~a * ~d)) * (~A * (~b) ^ 2 + (~a) ^ 2 * ~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1)) / ((~b) ^ 2 * ~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) + (1 / ((~b) ^ 2 * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * Simp((~b * (~m + 1) * (~a * ~C * (~b * ~c - ~a * ~d) + ~A * ~b * (~a * ~c - ~b * ~d)) - ((~b * ~c - ~a * ~d) * (~A * (~b) ^ 2 * (~m + 2) + ~C * ((~a) ^ 2 + (~b) ^ 2 * (~m + 1)))) * sin(~e + ~f * ~x)) + ~b * ~C * ~d * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && LtQ(~m, -1)))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~c + ~(d') * sin(~(e') + ~(f') * ~x)) * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) * ~d * cos(~e + ~f * ~x) * sin(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1)) / (~b * ~f * (~m + 3)) + (1 / (~b * (~m + 3))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * Simp((~a * ~C * ~d + ~A * ~b * ~c * (~m + 3) + ~b * (~B * ~c * (~m + 3) + ~d * (~C * (~m + 2) + ~A * (~m + 3))) * sin(~e + ~f * ~x)) - (2 * ~a * ~C * ~d - ~b * (~c * ~C + ~B * ~d) * (~m + 3)) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(LtQ(~m, -1))))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~c + ~(d') * sin(~(e') + ~(f') * ~x)) * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) * ~d * cos(~e + ~f * ~x) * sin(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1)) / (~b * ~f * (~m + 3)) + (1 / (~b * (~m + 3))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * Simp((~a * ~C * ~d + ~A * ~b * ~c * (~m + 3) + ~b * ~d * (~C * (~m + 2) + ~A * (~m + 3)) * sin(~e + ~f * ~x)) - (2 * ~a * ~C * ~d - ~b * ~c * ~C * (~m + 3)) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(LtQ(~m, -1))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (((~a * ~A - ~b * ~B) + ~a * ~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (2 * ~b * ~c * ~f * (2 * ~m + 1)) - (1 / (2 * ~b * ~c * ~d * (2 * ~m + 1))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp(((~A * ((~c) ^ 2 * (~m + 1) + (~d) ^ 2 * (2 * ~m + ~n + 2)) - ~B * ~c * ~d * ((~m - ~n) - 1)) - ~C * ((~c) ^ 2 * ~m - (~d) ^ 2 * (~n + 1))) + ~d * ((~A * ~c + ~B * ~d) * (~m + ~n + 2) - ~c * ~C * (3 * ~m - ~n)) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m, ~n], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1 / 2) || EqQ(~m + ~n + 2, 0) && NeQ(2 * ~m + 1, 0))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => ((~a * ~A + ~a * ~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (2 * ~b * ~c * ~f * (2 * ~m + 1)) - (1 / (2 * ~b * ~c * ~d * (2 * ~m + 1))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp((~A * ((~c) ^ 2 * (~m + 1) + (~d) ^ 2 * (2 * ~m + ~n + 2)) - ~C * ((~c) ^ 2 * ~m - (~d) ^ 2 * (~n + 1))) + ~d * (~A * ~c * (~m + ~n + 2) - ~c * ~C * (3 * ~m - ~n)) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m, ~n], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1 / 2) || EqQ(~m + ~n + 2, 0) && NeQ(2 * ~m + 1, 0))))
    @apply_utils Antiderivative(((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2)) / sqrt(~(c') + ~(d') * sin(~(e') + ~(f') * ~x)), ~x) => (-2 * ~C * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1)) / (~b * ~f * (2 * ~m + 3) * sqrt(~c + ~d * sin(~e + ~f * ~x))) + Antiderivative(((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * Simp(~A + ~C + ~B * sin(~e + ~f * ~x), ~x)) / sqrt(~c + ~d * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(LtQ(~m, -1 / 2))))
    @apply_utils Antiderivative(((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2)) / sqrt(~(c') + ~(d') * sin(~(e') + ~(f') * ~x)), ~x) => (-2 * ~C * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1)) / (~b * ~f * (2 * ~m + 3) * sqrt(~c + ~d * sin(~e + ~f * ~x))) + (~A + ~C) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m / sqrt(~c + ~d * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(LtQ(~m, -1 / 2))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~m + ~n + 2)) + (1 / (~b * ~d * (~m + ~n + 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp(~A * ~b * ~d * (~m + ~n + 2) + ~C * (~a * ~c * ~m + ~b * ~d * (~n + 1)) + (~b * ~B * ~d * (~m + ~n + 2) - ~b * ~c * ~C * (2 * ~m + 1)) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m, ~n], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (Not(LtQ(~m, -1 / 2)) && NeQ(~m + ~n + 2, 0))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~m + ~n + 2)) + (1 / (~b * ~d * (~m + ~n + 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp((~A * ~b * ~d * (~m + ~n + 2) + ~C * (~a * ~c * ~m + ~b * ~d * (~n + 1))) - ~b * ~c * ~C * (2 * ~m + 1) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m, ~n], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (Not(LtQ(~m, -1 / 2)) && NeQ(~m + ~n + 2, 0))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (((~a * ~A - ~b * ~B) + ~a * ~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~f * (~b * ~c - ~a * ~d) * (2 * ~m + 1)) + (1 / (~b * (~b * ~c - ~a * ~d) * (2 * ~m + 1))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp(((~A * (~a * ~c * (~m + 1) - ~b * ~d * (2 * ~m + ~n + 2)) + ~B * (~b * ~c * ~m + ~a * ~d * (~n + 1))) - ~C * (~a * ~c * ~m + ~b * ~d * (~n + 1))) + (~d * (~a * ~A - ~b * ~B) * (~m + ~n + 2) + ~C * (~b * ~c * (2 * ~m + 1) - ~a * ~d * ((~m - ~n) - 1))) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && LtQ(~m, -1 / 2))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (~a * (~A + ~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~f * (~b * ~c - ~a * ~d) * (2 * ~m + 1)) + (1 / (~b * (~b * ~c - ~a * ~d) * (2 * ~m + 1))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp((~A * (~a * ~c * (~m + 1) - ~b * ~d * (2 * ~m + ~n + 2)) - ~C * (~a * ~c * ~m + ~b * ~d * (~n + 1))) + (~a * ~A * ~d * (~m + ~n + 2) + ~C * (~b * ~c * (2 * ~m + 1) - ~a * ~d * ((~m - ~n) - 1))) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && LtQ(~m, -1 / 2))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-((((~c) ^ 2 * ~C - ~B * ~c * ~d) + ~A * (~d) ^ 2)) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~n + 1) * ((~c) ^ 2 - (~d) ^ 2)) + (1 / (~b * ~d * (~n + 1) * ((~c) ^ 2 - (~d) ^ 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1) * Simp(~A * ~d * (~a * ~d * ~m + ~b * ~c * (~n + 1)) + (~c * ~C - ~B * ~d) * (~a * ~c * ~m + ~b * ~d * (~n + 1)) + ~b * (~d * (~B * ~c - ~A * ~d) * (~m + ~n + 2) - ~C * ((~c) ^ 2 * (~m + 1) + (~d) ^ 2 * (~n + 1))) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (Not(LtQ(~m, -1 / 2)) && (LtQ(~n, -1) || EqQ(~m + ~n + 2, 0))))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(((~c) ^ 2 * ~C + ~A * (~d) ^ 2)) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~n + 1) * ((~c) ^ 2 - (~d) ^ 2)) + (1 / (~b * ~d * (~n + 1) * ((~c) ^ 2 - (~d) ^ 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1) * Simp((~A * ~d * (~a * ~d * ~m + ~b * ~c * (~n + 1)) + ~c * ~C * (~a * ~c * ~m + ~b * ~d * (~n + 1))) - ~b * (~A * (~d) ^ 2 * (~m + ~n + 2) + ~C * ((~c) ^ 2 * (~m + 1) + (~d) ^ 2 * (~n + 1))) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (Not(LtQ(~m, -1 / 2)) && (LtQ(~n, -1) || EqQ(~m + ~n + 2, 0))))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~m + ~n + 2)) + (1 / (~b * ~d * (~m + ~n + 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp(~A * ~b * ~d * (~m + ~n + 2) + ~C * (~a * ~c * ~m + ~b * ~d * (~n + 1)) + (~C * (~a * ~d * ~m - ~b * ~c * (~m + 1)) + ~b * ~B * ~d * (~m + ~n + 2)) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (Not(LtQ(~m, -1 / 2)) && NeQ(~m + ~n + 2, 0)))))
    @apply_utils Antiderivative((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~m + ~n + 2)) + (1 / (~b * ~d * (~m + ~n + 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp(~A * ~b * ~d * (~m + ~n + 2) + ~C * (~a * ~c * ~m + ~b * ~d * (~n + 1)) + ~C * (~a * ~d * ~m - ~b * ~c * (~m + 1)) * sin(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (Not(LtQ(~m, -1 / 2)) && NeQ(~m + ~n + 2, 0)))))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-((((~c) ^ 2 * ~C - ~B * ~c * ~d) + ~A * (~d) ^ 2)) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~n + 1) * ((~c) ^ 2 - (~d) ^ 2)) + (1 / (~d * (~n + 1) * ((~c) ^ 2 - (~d) ^ 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m - 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1) * Simp(((~A * ~d * (~b * ~d * ~m + ~a * ~c * (~n + 1)) + (~c * ~C - ~B * ~d) * (~b * ~c * ~m + ~a * ~d * (~n + 1))) - (~d * (~A * (~a * ~d * (~n + 2) - ~b * ~c * (~n + 1)) + ~B * (~b * ~d * (~n + 1) - ~a * ~c * (~n + 2))) - ~C * (~b * ~c * ~d * (~n + 1) - ~a * ((~c) ^ 2 + (~d) ^ 2 * (~n + 1)))) * sin(~e + ~f * ~x)) + ~b * (~d * (~B * ~c - ~A * ~d) * (~m + ~n + 2) - ~C * ((~c) ^ 2 * (~m + 1) + (~d) ^ 2 * (~n + 1))) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (GtQ(~m, 0) && LtQ(~n, -1)))))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(((~c) ^ 2 * ~C + ~A * (~d) ^ 2)) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~n + 1) * ((~c) ^ 2 - (~d) ^ 2)) + (1 / (~d * (~n + 1) * ((~c) ^ 2 - (~d) ^ 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m - 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1) * Simp(((~A * ~d * (~b * ~d * ~m + ~a * ~c * (~n + 1)) + ~c * ~C * (~b * ~c * ~m + ~a * ~d * (~n + 1))) - (~A * ~d * (~a * ~d * (~n + 2) - ~b * ~c * (~n + 1)) - ~C * (~b * ~c * ~d * (~n + 1) - ~a * ((~c) ^ 2 + (~d) ^ 2 * (~n + 1)))) * sin(~e + ~f * ~x)) - ~b * (~A * (~d) ^ 2 * (~m + ~n + 2) + ~C * ((~c) ^ 2 * (~m + 1) + (~d) ^ 2 * (~n + 1))) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (GtQ(~m, 0) && LtQ(~n, -1)))))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~m + ~n + 2)) + (1 / (~d * (~m + ~n + 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m - 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp(~a * ~A * ~d * (~m + ~n + 2) + ~C * (~b * ~c * ~m + ~a * ~d * (~n + 1)) + (~d * (~A * ~b + ~a * ~B) * (~m + ~n + 2) - ~C * (~a * ~c - ~b * ~d * (~m + ~n + 1))) * sin(~e + ~f * ~x) + (~C * (~a * ~d * ~m - ~b * ~c * (~m + 1)) + ~b * ~B * ~d * (~m + ~n + 2)) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (GtQ(~m, 0) && Not(IGtQ(~n, 0) && (Not(IntegerQ(~m)) || EqQ(~a, 0) && NeQ(~c, 0)))))))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(~C) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~d * ~f * (~m + ~n + 2)) + (1 / (~d * (~m + ~n + 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m - 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp(~a * ~A * ~d * (~m + ~n + 2) + ~C * (~b * ~c * ~m + ~a * ~d * (~n + 1)) + (~A * ~b * ~d * (~m + ~n + 2) - ~C * (~a * ~c - ~b * ~d * (~m + ~n + 1))) * sin(~e + ~f * ~x) + ~C * (~a * ~d * ~m - ~b * ~c * (~m + 1)) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (GtQ(~m, 0) && Not(IGtQ(~n, 0) && (Not(IntegerQ(~m)) || EqQ(~a, 0) && NeQ(~c, 0)))))))
    @apply_utils Antiderivative((~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / ((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ (3 / 2) * sqrt(~(d') * sin(~(e') + ~(f') * ~x))), ~x) => (~C / (~b * ~d)) * Antiderivative(sqrt(~d * sin(~e + ~f * ~x)) / sqrt(~a + ~b * sin(~e + ~f * ~x)), ~x) + (1 / ~b) * Antiderivative((~A * ~b + (~b * ~B - ~a * ~C) * sin(~e + ~f * ~x)) / ((~a + ~b * sin(~e + ~f * ~x)) ^ (3 / 2) * sqrt(~d * sin(~e + ~f * ~x))), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~A, ~B, ~C], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / ((~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ (3 / 2) * sqrt(~(d') * sin(~(e') + ~(f') * ~x))), ~x) => (~C / (~b * ~d)) * Antiderivative(sqrt(~d * sin(~e + ~f * ~x)) / sqrt(~a + ~b * sin(~e + ~f * ~x)), ~x) + (1 / ~b) * Antiderivative((~A * ~b - ~a * ~C * sin(~e + ~f * ~x)) / ((~a + ~b * sin(~e + ~f * ~x)) ^ (3 / 2) * sqrt(~d * sin(~e + ~f * ~x))), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~A, ~C], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / ((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ (3 / 2) * sqrt(~(c') + ~(d') * sin(~(e') + ~(f') * ~x))), ~x) => (~C / (~b) ^ 2) * Antiderivative(sqrt(~a + ~b * sin(~e + ~f * ~x)) / sqrt(~c + ~d * sin(~e + ~f * ~x)), ~x) + (1 / (~b) ^ 2) * Antiderivative(((~A * (~b) ^ 2 - (~a) ^ 2 * ~C) + ~b * (~b * ~B - 2 * ~a * ~C) * sin(~e + ~f * ~x)) / ((~a + ~b * sin(~e + ~f * ~x)) ^ (3 / 2) * sqrt(~c + ~d * sin(~e + ~f * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / ((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ (3 / 2) * sqrt(~(c') + ~(d') * sin(~(e') + ~(f') * ~x))), ~x) => (~C / (~b) ^ 2) * Antiderivative(sqrt(~a + ~b * sin(~e + ~f * ~x)) / sqrt(~c + ~d * sin(~e + ~f * ~x)), ~x) + (1 / (~b) ^ 2) * Antiderivative(((~A * (~b) ^ 2 - (~a) ^ 2 * ~C) - 2 * ~a * ~b * ~C * sin(~e + ~f * ~x)) / ((~a + ~b * sin(~e + ~f * ~x)) ^ (3 / 2) * sqrt(~c + ~d * sin(~e + ~f * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-(((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C)) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~f * (~m + 1) * (~b * ~c - ~a * ~d) * ((~a) ^ 2 - (~b) ^ 2)) + (1 / ((~m + 1) * (~b * ~c - ~a * ~d) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp((((~m + 1) * (~b * ~c - ~a * ~d) * ((~a * ~A - ~b * ~B) + ~a * ~C) + ~d * ((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C) * (~m + ~n + 2)) - (~c * ((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C) + (~m + 1) * (~b * ~c - ~a * ~d) * ((~A * ~b - ~a * ~B) + ~b * ~C)) * sin(~e + ~f * ~x)) - ~d * ((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C) * (~m + ~n + 3) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (LtQ(~m, -1) && (EqQ(~a, 0) && (IntegerQ(~m) && Not(IntegerQ(~n))) || Not(IntegerQ(2 * ~n) && (LtQ(~n, -1) && (IntegerQ(~n) && Not(IntegerQ(~m)) || EqQ(~a, 0)))))))))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => (-((~A * (~b) ^ 2 + (~a) ^ 2 * ~C)) * cos(~e + ~f * ~x) * (~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n + 1)) / (~f * (~m + 1) * (~b * ~c - ~a * ~d) * ((~a) ^ 2 - (~b) ^ 2)) + (1 / ((~m + 1) * (~b * ~c - ~a * ~d) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative((~a + ~b * sin(~e + ~f * ~x)) ^ (~m + 1) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * Simp(((~a * (~m + 1) * (~b * ~c - ~a * ~d) * (~A + ~C) + ~d * (~A * (~b) ^ 2 + (~a) ^ 2 * ~C) * (~m + ~n + 2)) - (~c * (~A * (~b) ^ 2 + (~a) ^ 2 * ~C) + ~b * (~m + 1) * (~b * ~c - ~a * ~d) * (~A + ~C)) * sin(~e + ~f * ~x)) - ~d * (~A * (~b) ^ 2 + (~a) ^ 2 * ~C) * (~m + ~n + 3) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (NeQ((~c) ^ 2 - (~d) ^ 2, 0) && (LtQ(~m, -1) && (EqQ(~a, 0) && (IntegerQ(~m) && Not(IntegerQ(~n))) || Not(IntegerQ(2 * ~n) && (LtQ(~n, -1) && (IntegerQ(~n) && Not(IntegerQ(~m)) || EqQ(~a, 0)))))))))
    @apply_utils Antiderivative((~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / ((~a + ~(b') * sin(~(e') + ~(f') * ~x)) * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x))), ~x) => ((~C * ~x) / (~b * ~d) + (((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C) / (~b * (~b * ~c - ~a * ~d))) * Antiderivative(1 / (~a + ~b * sin(~e + ~f * ~x)), ~x)) - ((((~c) ^ 2 * ~C - ~B * ~c * ~d) + ~A * (~d) ^ 2) / (~d * (~b * ~c - ~a * ~d))) * Antiderivative(1 / (~c + ~d * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / ((~a + ~(b') * sin(~(e') + ~(f') * ~x)) * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x))), ~x) => ((~C * ~x) / (~b * ~d) + ((~A * (~b) ^ 2 + (~a) ^ 2 * ~C) / (~b * (~b * ~c - ~a * ~d))) * Antiderivative(1 / (~a + ~b * sin(~e + ~f * ~x)), ~x)) - (((~c) ^ 2 * ~C + ~A * (~d) ^ 2) / (~d * (~b * ~c - ~a * ~d))) * Antiderivative(1 / (~c + ~d * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / (sqrt(~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x))), ~x) => (~C / (~b * ~d)) * Antiderivative(sqrt(~a + ~b * sin(~e + ~f * ~x)), ~x) - (1 / (~b * ~d)) * Antiderivative(Simp((~a * ~c * ~C - ~A * ~b * ~d) + ((~b * ~c * ~C - ~b * ~B * ~d) + ~a * ~C * ~d) * sin(~e + ~f * ~x), ~x) / (sqrt(~a + ~b * sin(~e + ~f * ~x)) * (~c + ~d * sin(~e + ~f * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / (sqrt(~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x))), ~x) => (~C / (~b * ~d)) * Antiderivative(sqrt(~a + ~b * sin(~e + ~f * ~x)), ~x) - (1 / (~b * ~d)) * Antiderivative(Simp((~a * ~c * ~C - ~A * ~b * ~d) + (~b * ~c * ~C + ~a * ~C * ~d) * sin(~e + ~f * ~x), ~x) / (sqrt(~a + ~b * sin(~e + ~f * ~x)) * (~c + ~d * sin(~e + ~f * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / (sqrt(~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) * sqrt(~c + ~(d') * sin(~(e') + ~(f') * ~x))), ~x) => (-(~C) * cos(~e + ~f * ~x) * sqrt(~c + ~d * sin(~e + ~f * ~x))) / (~d * ~f * sqrt(~a + ~b * sin(~e + ~f * ~x))) + (1 / (2 * ~d)) * Antiderivative((1 / ((~a + ~b * sin(~e + ~f * ~x)) ^ (3 / 2) * sqrt(~c + ~d * sin(~e + ~f * ~x)))) * Simp(((2 * ~a * ~A * ~d - ~C * (~b * ~c - ~a * ~d)) - 2 * (~a * ~c * ~C - ~d * (~A * ~b + ~a * ~B)) * sin(~e + ~f * ~x)) + (2 * ~b * ~B * ~d - ~C * (~b * ~c + ~a * ~d)) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2) / (sqrt(~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) * sqrt(~c + ~(d') * sin(~(e') + ~(f') * ~x))), ~x) => (-(~C) * cos(~e + ~f * ~x) * sqrt(~c + ~d * sin(~e + ~f * ~x))) / (~d * ~f * sqrt(~a + ~b * sin(~e + ~f * ~x))) + (1 / (2 * ~d)) * Antiderivative((1 / ((~a + ~b * sin(~e + ~f * ~x)) ^ (3 / 2) * sqrt(~c + ~d * sin(~e + ~f * ~x)))) * Simp(((2 * ~a * ~A * ~d - ~C * (~b * ~c - ~a * ~d)) - 2 * (~a * ~c * ~C - ~A * ~b * ~d) * sin(~e + ~f * ~x)) - ~C * (~b * ~c + ~a * ~d) * sin(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative(((~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2)) / (~a + ~(b') * sin(~(e') + ~(f') * ~x)), ~x) => ((~b * ~B - ~a * ~C) / (~b) ^ 2) * Antiderivative((~d * sin(~e + ~f * ~x)) ^ ~n, ~x) + (~C / (~b * ~d)) * Antiderivative((~d * sin(~e + ~f * ~x)) ^ (~n + 1), ~x) + (((~A * (~b) ^ 2 - ~a * ~b * ~B) + (~a) ^ 2 * ~C) / (~b) ^ 2) * Antiderivative((~d * sin(~e + ~f * ~x)) ^ ~n / (~a + ~b * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~A, ~B, ~C, ~n], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(((~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2)) / (~a + ~(b') * sin(~(e') + ~(f') * ~x)), ~x) => ((-(~a) * ~C) / (~b) ^ 2) * Antiderivative((~d * sin(~e + ~f * ~x)) ^ ~n, ~x) + (~C / (~b * ~d)) * Antiderivative((~d * sin(~e + ~f * ~x)) ^ (~n + 1), ~x) + ((~A * (~b) ^ 2 + (~a) ^ 2 * ~C) / (~b) ^ 2) * Antiderivative((~d * sin(~e + ~f * ~x)) ^ ~n / (~a + ~b * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~A, ~C, ~n], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => Unintegrable((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * (~A + ~B * sin(~e + ~f * ~x) + ~C * sin(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(a') + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => Unintegrable((~a + ~b * sin(~e + ~f * ~x)) ^ ~m * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * (~A + ~C * sin(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m, ~n], ~x) && (NeQ(~b * ~c - ~a * ~d, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && NeQ((~c) ^ 2 - (~d) ^ 2, 0)))
    @apply_utils Antiderivative((~(b') * sin(~(e') + ~(f') * ~x) ^ ~p) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * sin(~(e') + ~(f') * ~x) + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => ((~b * sin(~e + ~f * ~x) ^ ~p) ^ ~m / (~b * sin(~e + ~f * ~x)) ^ (~m * ~p)) * Antiderivative((~b * sin(~e + ~f * ~x)) ^ (~m * ~p) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * (~A + ~B * sin(~e + ~f * ~x) + ~C * sin(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m, ~n, ~p], ~x) && Not(IntegerQ(~m))
    @apply_utils Antiderivative((~(b') * cos(~(e') + ~(f') * ~x) ^ ~p) ^ ~m * (~(c') + ~(d') * cos(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(B') * cos(~(e') + ~(f') * ~x) + ~(C') * cos(~(e') + ~(f') * ~x) ^ 2), ~x) => ((~b * cos(~e + ~f * ~x) ^ ~p) ^ ~m / (~b * cos(~e + ~f * ~x)) ^ (~m * ~p)) * Antiderivative((~b * cos(~e + ~f * ~x)) ^ (~m * ~p) * (~c + ~d * cos(~e + ~f * ~x)) ^ ~n * (~A + ~B * cos(~e + ~f * ~x) + ~C * cos(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~b, ~c, ~d, ~e, ~f, ~A, ~B, ~C, ~m, ~n, ~p], ~x) && Not(IntegerQ(~m))
    @apply_utils Antiderivative((~(b') * sin(~(e') + ~(f') * ~x) ^ ~p) ^ ~m * (~(c') + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * sin(~(e') + ~(f') * ~x) ^ 2), ~x) => ((~b * sin(~e + ~f * ~x) ^ ~p) ^ ~m / (~b * sin(~e + ~f * ~x)) ^ (~m * ~p)) * Antiderivative((~b * sin(~e + ~f * ~x)) ^ (~m * ~p) * (~c + ~d * sin(~e + ~f * ~x)) ^ ~n * (~A + ~C * sin(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m, ~n, ~p], ~x) && Not(IntegerQ(~m))
    @apply_utils Antiderivative((~(b') * cos(~(e') + ~(f') * ~x) ^ ~p) ^ ~m * (~(c') + ~(d') * cos(~(e') + ~(f') * ~x)) ^ ~(n') * (~(A') + ~(C') * cos(~(e') + ~(f') * ~x) ^ 2), ~x) => ((~b * cos(~e + ~f * ~x) ^ ~p) ^ ~m / (~b * cos(~e + ~f * ~x)) ^ (~m * ~p)) * Antiderivative((~b * cos(~e + ~f * ~x)) ^ (~m * ~p) * (~c + ~d * cos(~e + ~f * ~x)) ^ ~n * (~A + ~C * cos(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~b, ~c, ~d, ~e, ~f, ~A, ~C, ~m, ~n, ~p], ~x) && Not(IntegerQ(~m))
end

max_stars_repo_path: src/rules/4 Trig functions/4.1 Sine/4.1.4.2 (a+b sin)^m (c+d sin)^n (A+B sin+C sin^2).jl


text:
include("euler/euler.jl")
using .Calculus: triangular_numbers
using BenchmarkTools
BenchmarkTools.DEFAULT_PARAMETERS.samples = 100

function compute(path::String)::Int
    triangles = triangular_numbers(20)
    chars = Dict(Char(Int('A') + i) => i + 1 for i ∈ 0:25)
    triangle_words = 0
    for word ∈ split(replace(read(path, String), "\"" => ""), ",")
        value = sum(chars[letter] for letter ∈ word)
        if value ∈ triangles triangle_words += 1 end
    end
    return triangle_words
end

compute("problems/0042/p042_words.txt")

@benchmark compute("problems/0042/p042_words.txt")

ext: jl

max_stars_repo_name: Dynortice/Project-Euler

max_issues_repo_name: Dynortice/Project-Euler

max_forks_repo_name: Dynortice/Project-Euler


text:
function intlog2(N::I) where {I <: Integer}
    # This version may be slightly faster when vectorized?
    # u = 0x4330000000000000 + N
    # d = reinterpret(Float64,u) - 4503599627370496.0
    # u = (reinterpret(Int64, d) >> 52) - 1023
    # This version is easier to read and understand how it works,
    # and probably faster when evaluated serially
    u = 8sizeof(I) - 1 - leading_zeros(N)
    Base.unsafe_trunc(I, u)
end
intlog2(::Type{T}) where {T} = intlog2(sizeof(T))
ispow2(x::Integer) = (x & (x - 1)) == zero(x)
nextpow2(W) = vleft_bitshift(one(W), (8sizeof(W) - leading_zeros(W-1)))
prevpow2(W) = vleft_bitshift(one(W), (8sizeof(W) - leading_zeros(W)-1))
    # W -= 1
    # W |= W >> 1
    # W |= W >> 2
    # W |= W >> 4
    # W |= W >> 8
    # W |= W >> 16
    # W + 1

@generated function T_shift(::Type{T}) where {T}
    intlog2(sizeof(T))
end
@generated function pick_vector_width(::Type{T} = Float64) where {T}
    shift = T_shift(T)
    max(1, REGISTER_SIZE >>> shift)
end
@generated function pick_vector_width_shift(::Type{T} = Float64) where {T}
    shift = T_shift(T)
    W = max(1, REGISTER_SIZE >>> shift)
    Wshift = intlog2(W)
    W, Wshift
end
function downadjust_W_and_Wshift(N, W, Wshift)
    N > W && return W, Wshift
    TwoN = N << 1
    while W >= TwoN
        W >>>= 1
        Wshift -= 1
    end
    W, Wshift
end
function pick_vector_width_shift(N::Integer, ::Type{T} = Float64) where {T}
    W, Wshift = pick_vector_width_shift(T)
    downadjust_W_and_Wshift(N, W, Wshift)
end
function pick_vector_width(N::Integer, ::Type{T} = Float64) where {T}
    W = pick_vector_width(T)
    first(downadjust_W_and_Wshift(N, W, 0))
end
function pick_vector_width_shift(N::Integer, size_T::Integer)
    W = max(1, REGISTER_SIZE ÷ size_T)
    Wshift = intlog2(W)
    downadjust_W_and_Wshift(N, W, Wshift)
end
function pick_vector_width(N::Integer, size_T::Integer)
    W = max(1, REGISTER_SIZE ÷ size_T)
    first(downadjust_W_and_Wshift(N, W, 0))
end

pick_vector_width(::Symbol, T) = pick_vector_width(T)
pick_vector_width_shift(::Symbol, T) = pick_vector_width_shift(T)

@generated pick_vector_width(::Val{N}, ::Type{T} = Float64) where {N,T} = pick_vector_width(N, T)

@generated pick_vector_width_val(::Type{T} = Float64) where {T} = Val{pick_vector_width(T)}()
pick_vector_width_val(::Type{Bool}) = Val{16}()
@generated pick_vector_width_val(::Val{N}, ::Type{T} = Float64) where {N,T} = Val{pick_vector_width(Val(N), T)}()

@generated function pick_vector_width_val(vargs...)
    sT = 1
    has_bool = false
    for v ∈ vargs
        T = v.parameters[1]
        if T === Bool
            has_bool = true#; sT = min(sT, sTv)
        elseif !SIMD_NATIVE_INTEGERS && T <: Integer
            sT = REGISTER_SIZE
        else
            # sT = min(sT, sizeof(T))
            sT = max(sT, sizeof(T))
        end
    end
    W = REGISTER_SIZE ÷ sT
    W = max(ifelse(has_bool, 8, 1), W)
    Val{W}()
end
@generated function adjust_W(::Val{N}, ::Val{W}) where {N,W}
    W1 = first(downadjust_W_and_Wshift(N, W, 0))
    Val{W1}()
end
pick_vector_width_val(::Val{N}, vargs...) where {N} = adjust_W(Val{N}(), pick_vector_width_val(vargs...))

@inline Base.@pure vadd(a::Int64, b::Int64) = llvmcall("%res = add nsw i64 %0, %1\nret i64 %res", Int64, Tuple{Int64,Int64}, a, b)
@inline Base.@pure vsub(a::Int64, b::Int64) = llvmcall("%res = sub nsw i64 %0, %1\nret i64 %res", Int64, Tuple{Int64,Int64}, a, b)
@inline Base.@pure vmul(a::Int64, b::Int64) = llvmcall("%res = mul nsw i64 %0, %1\nret i64 %res", Int64, Tuple{Int64,Int64}, a, b)
@inline Base.@pure vadd(a::Int32, b::Int32) = llvmcall("%res = add nsw i32 %0, %1\nret i32 %res", Int32, Tuple{Int32,Int32}, a, b)
@inline Base.@pure vsub(a::Int32, b::Int32) = llvmcall("%res = sub nsw i32 %0, %1\nret i32 %res", Int32, Tuple{Int32,Int32}, a, b)
@inline Base.@pure vmul(a::Int32, b::Int32) = llvmcall("%res = mul nsw i32 %0, %1\nret i32 %res", Int32, Tuple{Int32,Int32}, a, b)

@inline Base.@pure vleft_bitshift(a::Int64, b::Int64) = llvmcall("%res = shl nsw i64 %0, %1\nret i64 %res", Int64, Tuple{Int64,Int64}, a, b)
@inline Base.@pure vleft_bitshift(a::Int32, b::Int32) = llvmcall("%res = shl nsw i32 %0, %1\nret i32 %res", Int32, Tuple{Int32,Int32}, a, b)

# @inline Base.@pure vright_bitshift(a::Int64, b::Int64) = llvmcall("%res = ashr nsw i64 %0, %1\nret i64 %res", Int64, Tuple{Int64,Int64}, a, b)
# @inline Base.@pure vright_bitshift(a::Int32, b::Int32) = llvmcall("%res = ashr nsw i32 %0, %1\nret i32 %res", Int32, Tuple{Int32,Int32}, a, b)

@inline vadd(::Static{i}, j) where {i} = vadd(i, j)
@inline vadd(i, ::Static{j}) where {j} = vadd(i, j)
@inline vsub(::Static{i}, j) where {i} = vsub(i, j)
@inline vsub(i, ::Static{j}) where {j} = vsub(i, j)

@inline staticmul(::Val{W}, i) where {W} = vmul(Static(W), i)
@inline staticmuladd(::Val{W}, b, c) where {W} = vadd(vmul(Static(W), b), c)
@inline valmul(::Val{W}, i) where {W} = vmul(W, i)
@inline valadd(::Val{W}, i) where {W} = vadd(W, i)
@inline valsub(::Val{W}, i) where {W} = vsub(W, i)
@inline valsub(i, ::Val{W}) where {W} = vsub(i, W)
@inline valrem(::Val{W}, i) where {W} = i & (W - 1)
@inline valmuladd(::Val{W}, b, c) where {W} = vadd(vmul(W, b), c)
@inline valmulsub(::Val{W}, b, c) where {W} = vsub(vmul(W, b), c)
@inline valmul(::Val{W}, i::T) where {W,T<:Integer} = vmul((W % T), i)
@inline valadd(::Val{W}, i::T) where {W,T<:Integer} = vadd((W % T), i)
@inline valsub(::Val{W}, i::T) where {W,T<:Integer} = vsub((W % T), i)
@inline valrem(::Val{W}, i::T) where {W,T<:Integer} = i & ((W % T) - one(T))
@inline valmuladd(::Val{W}, b::T, c::T) where {W,T<:Integer} = vadd(vmul(W % T, b), c)
@inline valmulsub(::Val{W}, b::T, c::T) where {W,T<:Integer} = vsub(vmul(W % T, b), c)

@generated pick_vector(::Type{T}) where {T} = Vec{pick_vector_width(T),T}
pick_vector(N, T) = Vec{pick_vector_width(N, T),T}
@generated pick_vector(::Val{N}, ::Type{T}) where {N, T} =  pick_vector(N, T)

@inline _MM(::Val{W}) where {W} = _MM{W}(0)
@inline _MM(::Val{W}, i) where {W} = _MM{W}(i)
@inline _MM{W}(a::LazyStaticMul) where {W} = _MM{W}(extract_data(a))
@inline gep(ptr::Ptr, i::_MM) = gep(ptr, i.i)

@inline staticm1(i::_MM{W,I}) where {W,I} = _MM{W}(vsub(i.i, one(I)))
@inline staticp1(i::_MM{W,I}) where {W,I} = _MM{W}(vadd(i.i, one(I)))
@inline vadd(i::_MM{W}, j::Integer) where {W} = _MM{W}(vadd(i.i, j))
@inline vadd(i::Integer, j::_MM{W}) where {W} = _MM{W}(vadd(i, j.i))
@inline vadd(i::_MM{W}, ::Static{j}) where {W,j} = _MM{W}(vadd(i.i, j))
@inline vadd(::Static{i}, j::_MM{W}) where {W,i} = _MM{W}(vadd(i, j.i))
@inline vsub(i::_MM{W}, j::Integer) where {W} = _MM{W}(vsub(i.i, j))
@inline vsub(i::_MM{W}, ::Static{j}) where {W,j} = _MM{W}(vsub(i.i, j))
@inline vmulnp(i, j) = vmul(i,j)
@inline vmulnp(i, j::_MM{W}) where {W} = _MM{W}(vmul(i, j.i))
@inline vmuladdnp(a, b, c) = vadd(vmul(a,b), c)
@inline vmuladdnp(a, b::_MM{W}, c) where {W} = vadd(_MM{W}(vmul(a,b.i)), c)
@inline vmuladdnp(a, b::_MM{W}, c::_MM{W}) where {W} = vadd(vmul(a,b), c)
@inline vmuladdnp(a, b::_MM{W}, c::SVec) where {W} = vadd(vmul(a,b), c)
@inline vmuladdnp(a, b::_MM{W}, c::_Vec) where {W} = vadd(vmul(a,b), c)
@inline Base.:(+)(i::_MM{W}, j::Integer) where {W} = _MM{W}(vadd(i.i, j))
@inline Base.:(+)(i::Integer, j::_MM{W}) where {W} = _MM{W}(vadd(i, j.i))
@inline Base.:(+)(i::_MM{W}, ::Static{j}) where {W,j} = _MM{W}(vadd(i.i, j))
@inline Base.:(+)(::Static{i}, j::_MM{W}) where {W,i} = _MM{W}(vadd(i, j.i))
# @inline Base.:(+)(i::_MM{W}, j::_MM{W}) where {W} = _MM{W}(i.i + j.i)
@inline Base.:(-)(i::_MM{W}, j::Integer) where {W} = _MM{W}(vsub(i.i, j))
# @inline Base.:(-)(i::Integer, j::_MM{W}) where {W} = _MM{W}(i - j.i)
@inline Base.:(-)(i::_MM{W}, ::Static{j}) where {W,j} = _MM{W}(vsub(i.i, j))
# @inline Base.:(-)(::Static{i}, j::_MM{W}) where {W,i} = _MM{W}(i - j.i)
# @inline Base.:(-)(i::_MM{W}, j::_MM{W}) where {W} = _MM{W}(i.i - j.i)
# @inline Base.:(*)(i::_MM{W}, j) where {W} = _MM{W}(i.i * j)
# @inline Base.:(*)(i, j::_MM{W}) where {W} = _MM{W}(i * j.i)
# @inline Base.:(*)(i::_MM{W}, ::Static{j}) where {W,j} = _MM{W}(i.i * j)
# @inline Base.:(*)(::Static{i}, j::_MM{W}) where {W,i} = _MM{W}(i * j.i)
# @inline Base.:(*)(i::_MM{W}, j::_MM{W}) where {W} = _MM{W}(i.i * j.i)
@inline scalar_less(i, j) = i < j
@inline scalar_less(i::_MM, j::Integer) = i.i < j
@inline scalar_less(i::Integer, j::_MM) = i < j.i
@inline scalar_less(i::_MM, ::Static{j}) where {j} = i.i < j
@inline scalar_less(::Static{i}, j::_MM) where {i} = i < j.i
@inline scalar_less(i::_MM, j::_MM) = i.i < j.i
@inline scalar_greater(i, j) = i > j
@inline scalar_greater(i::_MM, j::Integer) = i.i > j
@inline scalar_greater(i::Integer, j::_MM) = i > j.i
@inline scalar_greater(i::_MM, ::Static{j}) where {j} = i.i > j
@inline scalar_greater(::Static{i}, j::_MM) where {i} = i > j.i
@inline scalar_greater(i::_MM, j::_MM) = i.i > j.i
@inline scalar_equal(i, j) = i == j
@inline scalar_equal(i::_MM, j::Integer) = i.i == j
@inline scalar_equal(i::Integer, j::_MM) = i == j.i
@inline scalar_equal(i::_MM, ::Static{j}) where {j} = i.i == j
@inline scalar_equal(::Static{i}, j::_MM) where {i} = i == j.i
@inline scalar_equal(i::_MM, j::_MM) = i.i == j.i
@inline scalar_notequal(i, j) = i != j
@inline scalar_notequal(i::_MM, j::Integer) = i.i != j
@inline scalar_notequal(i::Integer, j::_MM) = i != j.i
@inline scalar_notequal(i::_MM, ::Static{j}) where {j} = i.i != j
@inline scalar_notequal(::Static{i}, j::_MM) where {i} = i != j.i
@inline scalar_notequal(i::_MM, j::_MM) = i.i != j.i

@inline extract_data(i::_MM) = i.i

for T ∈ [Float32,Float64,Int8,Int16,Int32,Int64,UInt8,UInt16,UInt32,UInt64]#, Float16]
    maxW = pick_vector_width(T)
    typ = llvmtype(T)
    for log2W ∈ 0:intlog2(maxW)
        W = 1 << log2W
        instrs = "ret <$W x $typ> zeroinitializer"
        @eval @inline vzero(::Val{$W}, ::Type{$T}) = SVec(llvmcall($instrs, Vec{$W,$T}, Tuple{}, ))
        vtyp = "<$W x $typ>"
        instrs = """
        %ie = insertelement $vtyp undef, $typ %0, i32 0
        %v = shufflevector $vtyp %ie, $vtyp undef, <$W x i32> zeroinitializer
        ret $vtyp %v
        """
        @eval @inline vbroadcast(::Val{$W}, s::$T) = SVec(llvmcall($instrs, Vec{$W,$T}, Tuple{$T}, s))
    end
end

# @inline _vload(ptr::Ptr{T}, i::Integer) where {T} = vload(ptr + vmul(sizeof(T), i))
# @inline _vload(ptr::Ptr, v::SVec{<:Any,<:Integer}) = vload(ptr, v.data)
# @inline _vload(ptr::Ptr, v::Vec{<:Any,<:Integer}) = vload(ptr, v)
# @inline _vload(ptr::Ptr{T}, i::_MM{W}) where {W,T} = vload(Val{W}(), ptr + vmul(sizeof(T), i.i))
# @inline _vload(ptr::AbstractPointer, i) = _vload(ptr.ptr, offset(ptr, i))
# @inline vload(ptr::AbstractPointer{T}, i::Tuple) where {T} = _vload(ptr.ptr, offset(ptr, i))


text:
module Brainfuck
    include("lexandparse.jl")
    include("interpret.jl")

    export brainfuck
end


text:
module FEOperators

using Gridap
using Gridap.Helpers

using LinearAlgebra
using SparseArrays

import Gridap: apply
export apply!
export FEOperator
export FESolver
export LinearFEOperator
export LinearFESolver
export NonLinearFEOperator
export NonLinearFESolver
import Gridap: solve
import Gridap: solve!
import Gridap: jacobian
import Gridap: jacobian!
import Gridap: residual
import Gridap: residual!
import Gridap.NonLinearSolvers: create_in_domain
import Gridap.FESpaces: TrialFESpace
import Gridap.FESpaces: TestFESpace
import Gridap.LinearSolvers: LinearSolver

# We use duck typing in this module for the following types:

"""
Arguments annotated with this type have to implement the following queries:

free_dofs(::FEFunctionLike)

"""
const FEFunctionLike = Any

"""
Arguments annotated with this type have to implement the following queries:

FEFunction(::FESpaceLike, free_vals)

FEBasis(::FESpaceLike)

zero(::FESpaceLike)

"""
const FESpaceLike = Any

"""
Arguments annotated with this type have to implement the following queries:

assemble(::AssemblerLike, cellmat)

assemble(::AssemblerLike, cellvec)

assemble!(A,::AssemblerLike, cellmat)

assemble!(b,::AssemblerLike, cellvec)

"""
const AssemblerLike = Any

abstract type FEOperator end

function apply(::FEOperator,::FEFunctionLike)::AbstractVector
  @abstractmethod
end

function jacobian(::FEOperator,::FEFunctionLike)::AbstractMatrix
  @abstractmethod
end

function apply!(::AbstractVector,::FEOperator,::FEFunctionLike)
  @abstractmethod
end

function jacobian!(::AbstractMatrix,::FEOperator,::FEFunctionLike)
  @abstractmethod
end

function TrialFESpace(::FEOperator)::FESpaceLike
  @abstractmethod
end

function TestFESpace(::FEOperator)::FESpaceLike
  @abstractmethod
end

function residual(op::FEOperator,uh::FEFunctionLike)
  apply(op,uh)
end

function residual!(b::AbstractVector,op::FEOperator,uh::FEFunctionLike)
  apply!(b,op,uh)
end

abstract type FESolver end

function solve!(uh::FEFunctionLike,::FESolver,::FEOperator)::Tuple{FEFunctionLike,Any}
  @abstractmethod
end

function solve!(uh::FEFunctionLike,::FESolver,::FEOperator,::Any)::FEFunction
  @abstractmethod
end

"""
Solve that allocates, and sets initial guess to zero
and returns the solution
"""
function solve(nls::FESolver,op::FEOperator)
  U = TrialFESpace(op)
  uh = zero(U)
  vh, cache = solve!(uh,nls,op)
  vh
end

"""
Struct representing the non-linear algebraic problem
associated with a FEOperator
"""
struct NonLinearOpFromFEOp <: NonLinearOperator
  feop::FEOperator
end

function residual!(b::AbstractVector,op::NonLinearOpFromFEOp,x::AbstractVector)
  U = TrialFESpace(op.feop)
  uh = FEFunctionForEval(U,x)
  apply!(b,op.feop,uh)
end

function jacobian!(A::AbstractMatrix,op::NonLinearOpFromFEOp,x::AbstractVector)
  U = TrialFESpace(op.feop)
  uh = FEFunctionForEval(U,x)
  jacobian!(A,op.feop,uh)
end

function jacobian(op::NonLinearOpFromFEOp,x::AbstractVector)
  U = TrialFESpace(op.feop)
  uh = FEFunctionForEval(U,x)
  jacobian(op.feop,uh)
end

function create_in_domain(op::NonLinearOpFromFEOp)
  U = TrialFESpace(op.feop)
  zh = zero(U)
  free_dofs(zh)
end

"""
Struct representing a linear FE Operator
"""
struct LinearFEOperator{M,V} <:FEOperator
  mat::M
  vec::V
  trialfesp::FESpaceLike
  testfesp::FESpaceLike
end

function LinearFEOperator(
  testfesp::FESpaceLike,
  trialfesp::FESpaceLike,
  assem::AssemblerLike,
  terms::Vararg{<:AffineFETerm})

  v = FEBasis(testfesp)
  u = FEBasis(trialfesp)

  uhd = zero(trialfesp)

  cms = setup_cell_matrix(v,u,terms...)
  cvs = setup_cell_vector(v,uhd,terms...)

  mat = assemble(assem,cms...)
  vec = assemble(assem,cvs...)

  LinearFEOperator(mat,vec,trialfesp,testfesp)

end

function LinearFEOperator(
  testfesp::FESpaceLike,
  trialfesp::FESpaceLike,
  terms::Vararg{<:AffineFETerm})

  assem = SparseMatrixAssembler(testfesp,trialfesp)
  LinearFEOperator(testfesp,trialfesp,assem,terms...)
end

function LinearFEOperator(
  ::Type{M},
  testfesp::FESpaceLike,
  trialfesp::FESpaceLike,
  terms::Vararg{<:AffineFETerm}) where {M}

  assem = SparseMatrixAssembler(M,testfesp,trialfesp)
  LinearFEOperator(testfesp,trialfesp,assem,terms...)
end

function LinearFEOperator(
  biform::Function,
  liform::Function,
  testfesp::FESpaceLike,
  trialfesp::FESpaceLike,
  assem::AssemblerLike,
  trian::Triangulation{Z},
  quad::CellQuadrature{Z}) where Z

  term = AffineFETerm(biform,liform,trian,quad)

  LinearFEOperator(testfesp,trialfesp,assem,term)

end

TrialFESpace(op::LinearFEOperator) = op.trialfesp

TestFESpace(op::LinearFEOperator) = op.testfesp

function apply(o::LinearFEOperator,uh::FEFunctionLike)
  vals = free_dofs(uh)
  o.mat * vals - o.vec
end

function apply!(b::Vector,o::LinearFEOperator,uh::FEFunctionLike)
  vals = free_dofs(uh)
  mul!(b,o.mat,vals)
  broadcast!(-,b,b,o.vec)
end

jacobian(o::LinearFEOperator,::FEFunctionLike) = o.mat

function jacobian!(mat::AbstractMatrix, o::LinearFEOperator, ::FEFunctionLike)
  @assert mat === o.mat
end

"""
The solver that solves a LinearFEOperator
"""
struct LinearFESolver <: FESolver
  ls::LinearSolver
end

function solve!(::FEFunctionLike,::LinearFESolver,::FEOperator)
  @unreachable
end

function solve!(::FEFunctionLike,::LinearFESolver,::FEOperator,::Any)
  @unreachable
end

function solve!(uh::FEFunctionLike,s::LinearFESolver,o::LinearFEOperator)
  x = free_dofs(uh)
  A = o.mat
  b = o.vec
  ss = symbolic_setup(s.ls,A)
  ns = numerical_setup(ss,A)
  solve!(x,ns,b)
  U = TrialFESpace(o)
  FEFunction(U,x), ns
end

function solve!(uh::FEFunctionLike,s::LinearFESolver,o::LinearFEOperator,ns::NumericalSetup)
  x = free_dofs(uh)
  A = o.mat
  b = o.vec
  solve!(x,ns,b)
  U = TrialFESpace(o)
  FEFunction(U,x)
end

function solve(op::LinearFEOperator)
  ls = LUSolver()
  solver = LinearFESolver(ls)
  solve(solver,op)
end

"""
Struct representing a nonlinear FE Operator
"""
struct NonLinearFEOperator <:FEOperator
  testfesp::FESpaceLike
  trialfesp::FESpaceLike
  assem::AssemblerLike
  terms::NTuple{N,FETerm} where N
end

function NonLinearFEOperator(
  testfesp::FESpaceLike,
  trialfesp::FESpaceLike,
  assem::AssemblerLike,
  terms::Vararg{<:FETerm})
  NonLinearFEOperator(testfesp,trialfesp,assem,terms)
end

function NonLinearFEOperator(
  testfesp::FESpaceLike,
  trialfesp::FESpaceLike,
  terms::Vararg{<:FETerm})
  assem = SparseMatrixAssembler(testfesp,trialfesp)
  NonLinearFEOperator(testfesp,trialfesp,assem,terms)
end

function NonLinearFEOperator(
  ::Type{M},
  testfesp::FESpaceLike,
  trialfesp::FESpaceLike,
  terms::Vararg{<:FETerm}) where {M}

  assem = SparseMatrixAssembler(M,testfesp,trialfesp)
  NonLinearFEOperator(testfesp,trialfesp,assem,terms...)
end

function NonLinearFEOperator(
  res::Function,
  jac::Function,
  testfesp::FESpaceLike,
  trialfesp::FESpaceLike,
  assem::AssemblerLike,
  trian::Triangulation,
  quad::CellQuadrature)

  term = NonLinearFETerm(res,jac,trian,quad)

  NonLinearFEOperator(testfesp,trialfesp,assem,term)

end

TrialFESpace(op::NonLinearFEOperator) = op.trialfesp

TestFESpace(op::NonLinearFEOperator) = op.testfesp

function apply(op::NonLinearFEOperator,uh::FEFunctionLike)
  cellvec = _cellvec(op,uh)
  assemble(op.assem, cellvec...)
end

function apply!(b::AbstractVector,op::NonLinearFEOperator,uh::FEFunctionLike)
  cellvec = _cellvec(op,uh)
  assemble!(b,op.assem, cellvec...)
end

function jacobian(op::NonLinearFEOperator,uh::FEFunctionLike)
  cellmat = _cellmat(op,uh)
  assemble(op.assem, cellmat...)
end

function jacobian!(mat::AbstractMatrix,op::NonLinearFEOperator,uh::FEFunctionLike)
  cellmat = _cellmat(op,uh)
  assemble!(mat,op.assem, cellmat...)
end

function _cellvec(op,uh)
  v = FEBasis(op.testfesp)
  setup_cell_residual(uh,v,op.terms...)
end

function _cellmat(op,uh)
  v = FEBasis(op.testfesp)
  du = FEBasis(op.trialfesp)
  setup_cell_jacobian(uh,v,du,op.terms...)
end

"""
A general NonLinearFESolver
"""
struct NonLinearFESolver <: FESolver
  nls::NonLinearSolver
end

function solve!(uh::FEFunctionLike,nls::NonLinearFESolver,op::FEOperator)
  nlop = NonLinearOpFromFEOp(op)
  x = free_dofs(uh)
  cache = solve!(x,nls.nls,nlop)
  U = TrialFESpace(op)
  vh = FEFunction(U,x)
  vh, cache
end

function solve!(uh::FEFunctionLike,nls::NonLinearFESolver,op::FEOperator,cache::Any)
  nlop = NonLinearOpFromFEOp(op)
  x = free_dofs(uh)
  solve!(x,nls.nls,nlop,cache)
  U = TrialFESpace(op)
  FEFunction(U,x)
end

# Pretty printing

import Base: show

function show(io::IO,self::FEOperator)
  print(io,"$(nameof(typeof(self))) object")
end

function show(io::IO,::MIME"text/plain",self::FEOperator)
  show(io,self)
end

function show(io::IO,self::FESolver)
  print(io,"$(nameof(typeof(self))) object")
end

function show(io::IO,::MIME"text/plain",self::FESolver)
  show(io,self)
end

end # module FEOperators


text:
# Use
#    @warnpcfail precompile(args...)
# if you want to be warned when a precompile directive fails
macro warnpcfail(ex::Expr)
    modl = __module__
    file = __source__.file === nothing ? "?" : String(__source__.file)
    line = __source__.line
    quote
        $(esc(ex)) || @warn """precompile directive
     $($(Expr(:quote, ex)))
 failed. Please report an issue in $($modl) (after checking for duplicates) or remove this directive.""" _file=$file _line=$line
    end
end

function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    Base.precompile(Tuple{typeof(RecipesBase.apply_recipe),AbstractDict{Symbol, Any},AbstractMatrix{T} where T})
    Base.precompile(Tuple{typeof(RecipesBase.apply_recipe),AbstractDict{Symbol, Any},AbstractVector{T} where T,AbstractVector{T} where T,Function})
    Base.precompile(Tuple{typeof(RecipesBase.apply_recipe),AbstractDict{Symbol, Any},Function,Number,Number})
    Base.precompile(Tuple{typeof(RecipesBase.apply_recipe),AbstractDict{Symbol, Any},GroupBy,Any})
    Base.precompile(Tuple{typeof(RecipesBase.apply_recipe),AbstractDict{Symbol, Any},Type{SliceIt},Any,Any,Any})
    Base.precompile(Tuple{typeof(RecipesBase.apply_recipe),AbstractDict{Symbol, Any},Vector{Function},Number,Number})
    Base.precompile(Tuple{typeof(_apply_type_recipe),Any,AbstractArray,Any})
    Base.precompile(Tuple{typeof(_apply_type_recipe),Any,Surface,Any})
    Base.precompile(Tuple{typeof(_compute_xyz),Vector{Float64},Function,Nothing,Bool})
    Base.precompile(Tuple{typeof(_extract_group_attributes),Vector{String},Vector{Float64}})
    Base.precompile(Tuple{typeof(_map_funcs),Function,StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}}})
    Base.precompile(Tuple{typeof(_process_ribbon),Tuple{LinRange{Float64}, LinRange{Float64}},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_process_seriesrecipe),Any,Any})
    Base.precompile(Tuple{typeof(_process_seriesrecipes!),Any,Any})
    Base.precompile(Tuple{typeof(_scaled_adapted_grid),Function,Symbol,Symbol,Float64,Irrational{:π}})
    Base.precompile(Tuple{typeof(_series_data_vector),Int64,Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Matrix{Float64},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Surface{Matrix{Int64}},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Vector{AbstractVector{Float64}},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Vector{Function},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Vector{Int64},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Vector{Real},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Vector{String},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Vector{Union{Missing, Int64}},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Vector{Vector{Float64}},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(_series_data_vector),Vector{Vector{T} where T},Dict{Symbol, Any}})
    Base.precompile(Tuple{typeof(recipe_pipeline!),Any,Any,Any})
    Base.precompile(Tuple{typeof(unzip),Vector{Tuple{Float64, Float64}}})
    Base.precompile(Tuple{typeof(unzip),Vector{Tuple{Int64, Int64}}})
    Base.precompile(Tuple{typeof(unzip),Vector{Tuple{Int64, Real}}})
    Base.precompile(Tuple{typeof(unzip),Vector{Tuple{Vector{Float64}, Vector{Float64}}}})
end


text:
export WebhooksUpdate

"""
Sent when a [`DiscordChannel`](@ref)'s [`Webhook`](@ref)s are updated.
"""
struct WebhooksUpdate <: AbstractEvent
    guild_id::Snowflake
    channel_id::Snowflake
end
@boilerplate WebhooksUpdate :constructors :docs :mock


text:
import gmsh
using JSON

gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 1)

# set a full onelab db
gmsh.onelab.set("""
{ "onelab":{
  "creator":"My app",
  "version":"1.3",
  "parameters":[
    { "type":"number", "name":"number 1", "values":[ 1 ]  },
    { "type":"string", "name":"string 1", "values":[ "hello" ]  }
  ] }
}
""")

# set a list of parameters
gmsh.onelab.set("""
[
  { "type":"number", "name":"number 2", "values":[ 3.141592 ],
    "attributes":{ "Highlight":"Red" }  },
  { "type":"string", "name":"string 2", "values":[ "hello again" ]  }
]
""")

# set a single parameter
gmsh.onelab.set("""
{ "type":"number", "name":"check 1", "values":[ 0 ], "choices":[0, 1]  }
""")

# get the full parameter, store it as a Julia dict, and change an attribute
p = JSON.parse(gmsh.onelab.get("check 1"))
p["attributes"] = "Highlight" => "Blue"
gmsh.onelab.set(JSON.json(p))

# shorter way to just change the value, without json overhead
gmsh.onelab.setNumber("check 1", [1.0]) # FIXME Julia requires a float here
gmsh.onelab.setString("string 1", ["goodbye"])

# remove a parameter
gmsh.onelab.clear("string 2")

gmsh.fltk.run()

gmsh.finalize()

max_stars_repo_name: Poofee/fastFEM

max_issues_repo_name: Christophe-Foyer/pyFEA

max_forks_repo_name: Christophe-Foyer/pyFEA


text:
struct Progress
    dl_total :: curl_off_t
    dl_now   :: curl_off_t
    ul_total :: curl_off_t
    ul_now   :: curl_off_t
end

mutable struct Easy
    handle   :: Ptr{Cvoid}
    progress :: Channel{Progress}
    buffers  :: Channel{Vector{UInt8}}
    req_hdrs :: Ptr{curl_slist_t}
    res_hdrs :: Vector{String}
    code     :: CURLcode
    errbuf   :: Vector{UInt8}
end

function Easy()
    easy = Easy(
        curl_easy_init(),
        Channel{Progress}(Inf),
        Channel{Vector{UInt8}}(Inf),
        C_NULL,
        String[],
        typemax(CURLcode),
        zeros(UInt8, CURL_ERROR_SIZE),
    )
    finalizer(easy) do easy
        curl_easy_cleanup(easy.handle)
        curl_slist_free_all(easy.req_hdrs)
    end
    add_callbacks(easy)
    set_defaults(easy)
    return easy
end

# request options

function set_defaults(easy::Easy)
    # curl options
    curl_easy_setopt(easy.handle, CURLOPT_TCP_FASTOPEN, true) # failure ok, unsupported
    @check curl_easy_setopt(easy.handle, CURLOPT_NOSIGNAL, true)
    @check curl_easy_setopt(easy.handle, CURLOPT_FOLLOWLOCATION, true)
    @check curl_easy_setopt(easy.handle, CURLOPT_AUTOREFERER, true)
    @check curl_easy_setopt(easy.handle, CURLOPT_MAXREDIRS, 10)
    @check curl_easy_setopt(easy.handle, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL)
    @check curl_easy_setopt(easy.handle, CURLOPT_USERAGENT, USER_AGENT)

    # tell curl where to find HTTPS certs
    certs_file = normpath(Sys.BINDIR, "..", "share", "julia", "cert.pem")
    @check curl_easy_setopt(easy.handle, CURLOPT_CAINFO, certs_file)
end

function set_url(easy::Easy, url::Union{String, SubString{String}})
    # TODO: ideally, Clang would generate Cstring signatures
    Base.unsafe_convert(Cstring, url) # error checking
    @check curl_easy_setopt(easy.handle, CURLOPT_URL, url)
end
set_url(easy::Easy, url::AbstractString) = set_url(easy, String(url))

function add_header(easy::Easy, hdr::Union{String, SubString{String}})
    # TODO: ideally, Clang would generate Cstring signatures
    Base.unsafe_convert(Cstring, hdr) # error checking
    easy.req_hdrs = curl_slist_append(easy.req_hdrs, hdr)
    @check curl_easy_setopt(easy.handle, CURLOPT_HTTPHEADER, easy.req_hdrs)
end

add_header(easy::Easy, hdr::AbstractString) = add_header(easy, string(hdr)::String)
add_header(easy::Easy, key::AbstractString, val::AbstractString) =
    add_header(easy, isempty(val) ? "$key;" : "$key: $val")
add_header(easy::Easy, key::AbstractString, val::Nothing) =
    add_header(easy, "$key:")
add_header(easy::Easy, pair::Pair) = add_header(easy, pair...)

function enable_progress(easy::Easy, on::Bool)
    @check curl_easy_setopt(easy.handle, CURLOPT_NOPROGRESS, !on)
end

# response info

function get_effective_url(easy::Easy)
    url_ref = Ref{Ptr{Cchar}}()
    @check curl_easy_getinfo(easy.handle, CURLINFO_EFFECTIVE_URL, url_ref)
    return unsafe_string(url_ref[])
end

function get_response_code(easy::Easy)
    code_ref = Ref{Clong}()
    @check curl_easy_getinfo(easy.handle, CURLINFO_RESPONSE_CODE, code_ref)
    return Int(code_ref[])
end

function get_response_headers(easy::Easy)
    headers = Pair{String,String}[]
    response = isempty(easy.res_hdrs) ? "" : easy.res_hdrs[1]
    for hdr in easy.res_hdrs
        if occursin(r"^\s*$", hdr)
            # ignore
        elseif (m = match(r"^(HTTP/\d+(?:.\d+)?\s+\d+\b.*?)\s*$", hdr)) !== nothing
            response = m.captures[1]
            empty!(headers)
        elseif (m = match(r"^(\S[^:]*?)\s*:\s*(.*?)\s*$", hdr)) !== nothing
            push!(headers, lowercase(m.captures[1]) => m.captures[2])
        else
            url = get_effective_url(easy)
            status = get_response_code(easy)
            @warn "malformed HTTP header" url status header=hdr
        end
    end
    return response, headers
end

# callbacks

function header_callback(
    data   :: Ptr{Cchar},
    size   :: Csize_t,
    count  :: Csize_t,
    easy_p :: Ptr{Cvoid},
)::Csize_t
    easy = unsafe_pointer_to_objref(easy_p)::Easy
    n = size * count
    hdr = unsafe_string(data, n)
    push!(easy.res_hdrs, hdr)
    return n
end

function write_callback(
    data   :: Ptr{Cchar},
    size   :: Csize_t,
    count  :: Csize_t,
    easy_p :: Ptr{Cvoid},
)::Csize_t
    easy = unsafe_pointer_to_objref(easy_p)::Easy
    n = size * count
    buf = Array{UInt8}(undef, n)
    ccall(:memcpy, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), buf, data, n)
    put!(easy.buffers, buf)
    return n
end

function progress_callback(
    easy_p   :: Ptr{Cvoid},
    dl_total :: curl_off_t,
    dl_now   :: curl_off_t,
    ul_total :: curl_off_t,
    ul_now   :: curl_off_t,
)::Cint
    easy = unsafe_pointer_to_objref(easy_p)::Easy
    put!(easy.progress, Progress(dl_total, dl_now, ul_total, ul_now))
    return 0
end

function add_callbacks(easy::Easy)
    # pointer to easy object
    easy_p = pointer_from_objref(easy)
    @check curl_easy_setopt(easy.handle, CURLOPT_PRIVATE, easy_p)

    # pointer to error buffer
    errbuf_p = pointer(easy.errbuf)
    @check curl_easy_setopt(easy.handle, CURLOPT_ERRORBUFFER, errbuf_p)

    # set header callback
    header_cb = @cfunction(header_callback,
        Csize_t, (Ptr{Cchar}, Csize_t, Csize_t, Ptr{Cvoid}))
    @check curl_easy_setopt(easy.handle, CURLOPT_HEADERFUNCTION, header_cb)
    @check curl_easy_setopt(easy.handle, CURLOPT_HEADERDATA, easy_p)

    # set write callback
    write_cb = @cfunction(write_callback,
        Csize_t, (Ptr{Cchar}, Csize_t, Csize_t, Ptr{Cvoid}))
    @check curl_easy_setopt(easy.handle, CURLOPT_WRITEFUNCTION, write_cb)
    @check curl_easy_setopt(easy.handle, CURLOPT_WRITEDATA, easy_p)

    # set progress callbacks
    progress_cb = @cfunction(progress_callback,
        Cint, (Ptr{Cvoid}, curl_off_t, curl_off_t, curl_off_t, curl_off_t))
    @check curl_easy_setopt(easy.handle, CURLOPT_XFERINFOFUNCTION, progress_cb)
    @check curl_easy_setopt(easy.handle, CURLOPT_XFERINFODATA, easy_p)
end


text:
"""
    divergence(f)
"""
divergence(f) = Operation(tr)(∇(f))

function evaluate!(cache,::Broadcasting{typeof(divergence)},f)
  Broadcasting(Operation(tr))(Broadcasting(∇)(f))
end

function symmetric_gradient end

"""
    symmetric_gradient(f)
"""
symmetric_gradient(f) = Operation(symmetric_part)(gradient(f))

function evaluate!(cache,::Broadcasting{typeof(symmetric_gradient)},f)
  Broadcasting(Operation(symmetric_part))(Broadcasting(∇)(f))
end

"""
    const ε = symmetric_gradient

Alias for the symmetric gradient
"""
const ε = symmetric_gradient

"""
    curl(f)
"""
curl(f) = Operation(grad2curl)(∇(f))

function evaluate!(cache,::Broadcasting{typeof(curl)},f)
  Broadcasting(Operation(grad2curl))(Broadcasting(∇)(f))
end

"""
    grad2curl(∇f)
"""
@inline function grad2curl(∇u::TensorValue{2})
  ∇u[1,2] - ∇u[2,1]
end

@inline function grad2curl(∇u::TensorValue{3})
  c1 = ∇u[2,3] - ∇u[3,2]
  c2 = ∇u[3,1] - ∇u[1,3]
  c3 = ∇u[1,2] - ∇u[2,1]
  VectorValue(c1,c2,c3)
end

function laplacian end

"""
    const Δ = laplacian

Alias for the `laplacian` function
"""
const Δ = laplacian

"""
    laplacian(f)
"""
function laplacian(f)
  # g = gradient(f)
  # divergence(g)
  tr(∇∇(f))
end

"""
    ∇⋅f

Equivalent to

    divergence(f)
"""
dot(::typeof(∇),f::Field) = divergence(f)
dot(::typeof(∇),f::Function) = divergence(f)

function (*)(::typeof(∇),f::Field)
  msg = "Syntax ∇*f has been removed, use ∇⋅f (\\nabla \\cdot f) instead"
  error(msg)
end

function (*)(::typeof(∇),f::Function)
  msg = "Syntax ∇*f has been removed, use ∇⋅f (\\nabla \\cdot f) instead"
  error(msg)
end

"""
    outer(∇,f)

Equivalent to

    gradient(f)
"""
outer(::typeof(∇),f::Field) = gradient(f)
outer(::typeof(∇),f::Function) = gradient(f)

"""
    outer(f,∇)

Equivalent to

    transpose(gradient(f))
"""
outer(f::Field,::typeof(∇)) = transpose(gradient(f))
outer(f::Function,::typeof(∇)) = transpose(gradient(f))

"""
    cross(∇,f)

Equivalent to

    curl(f)
"""
cross(::typeof(∇),f::Field) = curl(f)
cross(::typeof(∇),f::Function) = curl(f)

_extract_grad_diag(x::TensorValue) = diag(x)
_extract_grad_diag(x) = @notimplemented

function Base.broadcasted(::typeof(*),::typeof(∇),f)
  g = ∇(f)
  Operation(_extract_grad_diag)(g)
end

function Base.broadcasted(::typeof(*),::typeof(∇),f::Function)
  Base.broadcasted(*,∇,GenericField(f))
end

struct ShiftedNabla{N,T}
  v::VectorValue{N,T}
end

(+)(::typeof(∇),v::VectorValue) = ShiftedNabla(v)
(+)(v::VectorValue,::typeof(∇)) = ShiftedNabla(v)
(-)(::typeof(∇),v::VectorValue) = ShiftedNabla(-v)

function (s::ShiftedNabla)(f)
  Operation((a,b)->a+s.v⊗b)(gradient(f),f)
end

(s::ShiftedNabla)(f::Function) = s(GenericField(f))

function evaluate!(cache,k::Broadcasting{<:ShiftedNabla},f)
  s = k.f
  g = Broadcasting(∇)(f)
  Broadcasting(Operation((a,b)->a+s.v⊗b))(g,f)
end

dot(s::ShiftedNabla,f) = Operation(tr)(s(f))
outer(s::ShiftedNabla,f) = s(f)
outer(f,s::ShiftedNabla) = transpose(gradient(f))
cross(s::ShiftedNabla,f) = Operation(grad2curl)(s(f))

dot(s::ShiftedNabla,f::Function) = dot(s,GenericField(f))
outer(s::ShiftedNabla,f::Function) = outer(s,GenericField(f))
outer(f::Function,s::ShiftedNabla) = outer(GenericField(f),s)
cross(s::ShiftedNabla,f::Function) = cross(s,GenericField(f))

function Base.broadcasted(::typeof(*),s::ShiftedNabla,f)
  g = s(f)
  Operation(_extract_grad_diag)(g)
end

function Base.broadcasted(::typeof(*),s::ShiftedNabla,f::Function)
  Base.broadcasted(*,s,GenericField(f))
end


text:
module Tiling

# -----------
# Tile object
# -----------

export Tile

"""
    Tile{size, names, T}

A [`Tile`](@ref) represents a part of a multidimensional tensor that is
contiguous and aligned to the tensor's dimensions.

Note that the dimensions of this [`Tile`](@ref) are named. Similar to a
[`NamedTuple`](@ref), the names are stored as a type parameter `names`.

A [`Tile`](@ref) contains several fields:
- `index`: A [`NamedTuple`](@ref) that represents the "first" multidimensional
           index of the parent tensor that this tile contains.
- `base`: The part of the `index` that depends on runtime values, such as the
          `threadIdx`.
- `offset`: The part of the `index` that is known at compile-time.
- `size`: A [`NamedTuple`](@ref) representing the size of the tile along each
          dimension.

You can also project a [`Tile`](@ref) (i.e. drop certain dimensions) by
accessing a special "field" of which the name is derived from the dimensions
you intend to keep.

For example, to drop the `K` dimension of a tile containing `M`, `N` and `K`
dimensions, you can use the syntax `tile.MN`.
"""
struct Tile{size, names, T}
    base::NamedTuple{names, T}
    offset::NamedTuple{names, T}
end

@inline _size(tile::Tile{size, names, T}) where {size, names, T} = size
@inline _names(tile::Tile{size, names, T}) where {size, names, T} = names

"""
    Tile(; kw_args...)

Creates a new [`Tile`](@ref) of the given `size`, with zero `base` and
`offset`. The `size` for each dimension must be specified by a keyword
argument.

# Example
```julia
GemmKernels.Tiling.Tile(M = 24, N = 16, K = 4)
```
"""
Tile(; kw_args...) = Tile((; kw_args...))

"""
    Tile(size::NamedTuple{names, T})

Creates a new [`Tile`](@ref) of the given `size`, with zero `base` and
`offset`.

# Arguments
- `size`: A `NamedTuple` representing the size of the [`Tile`](@ref).

# Example
```julia
GemmKernels.Tiling.Tile((M = 24, N = 16, K = 4))
```
"""
@inline Tile(size::NamedTuple{names, T}) where {names, T} = Tile{size, names, T}(map(x -> 0, size), map(x -> 0, size))

# ------------
# Pretty print
# ------------

function Base.show(io::IO, tile::Tile{size, names, T}) where {size, names, T}
    print(io, "base:   ", tile.base, '\n')
    print(io, "offset: ", tile.offset, '\n')
    print(io, "size:   ", tile.size)
end

# --------------------------
# Projection & transposition
# --------------------------

@inline _projection_impl(base::NamedTuple{names, T}, offset::NamedTuple{names, T}, size::NamedTuple{names, T}) where {names, T} = Tile{size, names, T}(base, offset)

@generated function _getproperty_impl(tile::Tile{size, names, T}, ::Val{sym}) where {names, T, sym, size}
    if sym == :base || sym == :offset
        # fields
        return :(getfield(tile, sym))
    elseif sym == :size
        # size
        return size
    elseif sym == :index
        # index: sum of base and offset
        return :(map(+, getfield(tile, :base), getfield(tile, :offset)))
    else
        # tile projection
        sym_str = String(sym)
        names = ntuple(i -> Symbol(sym_str[i]), length(sym_str))
        return :( _projection_impl(NamedTuple{$names}(getfield(tile, :base)),
                                   NamedTuple{$names}(getfield(tile, :offset)),
                                   NamedTuple{$names}(size)) )
    end
end

@generated function Base.transpose(tile::Tile{size, names, T}) where {names, T, size}
    new_names = reverse(names)
    return :( _projection_impl(NamedTuple{$new_names}(tile.base), NamedTuple{$new_names}(tile.offset), NamedTuple{$new_names}(size)) )
end

@inline Base.getproperty(tile::Tile{size, names, T}, sym::Symbol) where {names, T, size} = _getproperty_impl(tile, Val(sym))

# -------------
# Linearisation
# -------------

export linearise

"""
    linearise(coord, dims)

Convert a multidimensional coordinate to a linear index with respect to a
tensor with dimensions `dims`.

# Arguments
- `coord`: The coordinate (base, offset, or index) to linearise.
- `dims`: The dimensions of the parent tensor.
"""
@inline function linearise(coord, dims)
    ind = Tuple(coord) .+ 1
    @inbounds return LinearIndices(Tuple(dims))[ind...]
end

# -----------
# Translation
# -----------

export translate_base, translate_offset

"""
    translate_base(tile, offset)

Translate (i.e. move) a [`Tile`](@ref) by a constant `offset`.
The `offset` is added to the [`Tile`](@ref)'s base.

# Arguments
- `tile`: The [`Tile`](@ref) to translate.
- `offset`: The `offset` in each dimension.
"""
function translate_base end

"""
    translate_offset(tile, offset)

Translate (i.e. move) a [`Tile`](@ref) by a constant `offset`.
The `offset` is added to the [`Tile`](@ref)'s base.

# Arguments
- `tile`: The [`Tile`](@ref) to translate.
- `offset`: The `offset` in each dimension.
"""
function translate_offset end

@inline function translate_base(tile::Tile{size, names, T}, offset::NamedTuple{names, T}) where {names, T, size}
    new_base = map(+, tile.base, offset)
    return Tile{size, names, T}(new_base, tile.offset)
end

@inline translate_base(tile::Tile{size, names, T}, offset::Tuple) where {names, T, size} = translate_base(tile, NamedTuple{names}(offset))

@inline function translate_offset(tile::Tile{size, names, T}, offset::NamedTuple{names, T}) where {names, T, size}
    new_offset = map(+, tile.offset, offset)
    return Tile{size, names, T}(tile.base, new_offset)
end

@inline translate_offset(tile::Tile{size, names, T}, offset::Tuple) where {names, T, size} = translate_offset(tile, NamedTuple{names}(offset))

# -------------
# TileIterators
# -------------

export TileIterator

"""
    TileIterator{names, T, N, R}

A [`TileIterator`](@ref) represents an iterator over a set of [`Tile`](@ref)s.

See also: [`subdivide`](@ref), [`parallellise`](@ref).
"""
struct TileIterator{tile_size, parent_size, names, T, S, col_major}
    parent::Tile{parent_size, names, T}
    subtile_indices::S
    idx::Int32
    step::Int32
end

# ----------------
# Parallellisation
# ----------------

export parallellise, subdivide

"""
    parallellise(tile, tiling_size, idx, size)

Split the given `tile` in subtiles of size `tiling_size` across a group of
cooperating entities (e.g. warps, threads, ...).

Unlike [`subdivide`](@ref), the `tile` need not be completely covered by
`count` tiles of size `tiling_size`. If that's not the case, the subtiles
are evenly parallellised across all cooperating entities.

Returns a [`TileIterator`](@ref) that iterates over the [`Tile`](@ref)s of
the calling entity.

# Arguments
- `tile`: The [`Tile`](@ref) to parallellise.
- `tiling_size`: A `NamedTuple` indicating the size of a subtile along each dimension.
- `idx`: The identity of the calling entity.
- `count`: The number of cooperating entities.
"""
@inline function parallellise(tile::Tile{size, names, T}, tiling_size::Tile{tile_sz, names, T}, idx, count, col_major::Bool=true) where {names, T, size, tile_sz}
    # Transpose
    tile = col_major ? tile : transpose(tile)
    tiling_size = col_major ? tiling_size : transpose(tiling_size)

    # Number of tiles along each dimension
    num_tiles = map(div, Tuple(_size(tile)), Tuple(_size(tiling_size)))

    parent = tile
    subtile_indices = CartesianIndices(num_tiles)
    step = count

    return TileIterator{_size(tiling_size), _size(tile), _names(tile), T, typeof(subtile_indices), col_major}(parent, subtile_indices, convert(Int32, idx), convert(Int32, step))
end

"""
    subdivide(tile, tiling_size, idx, count)

Split the given `tile` in subtiles of size `tiling_size` across a group of
`count` cooperating entities (e.g. warps, threads, ...).

The given `tile` must be completely covered by `count` tiles of size
`tiling_size`.

Returns the [`Tile`](@ref) that the calling entity is responsible for.

# Arguments
- `tile`: The [`Tile`](@ref) to subdivide.
- `tiling_size`: A `NamedTuple` indicating the size of a subtile along each dimension.
- `idx`: The identity of the calling entity.
- `count`: The number of cooperating entities.
"""
@inline function subdivide(tile::Tile{size, names, T}, tiling_size::Tile{tile_sz, names, T}, idx, count) where {names, T, size, tile_sz}
    return iterate(parallellise(tile, tiling_size, idx, count))[1]
end

@inline function Base.iterate(it::TileIterator{tile_size, parent_size, names, T, S, col_major}, state = 1) where {tile_size, parent_size, names, T, S, col_major}
    if state > length(it.subtile_indices)
        return nothing
    end

    # Calculate base and offset in number of tiles
    @inbounds base   = Tuple(it.parent.base)   .+ (Tuple(it.subtile_indices[it.idx]) .- 1) .* Tuple(tile_size)
    @inbounds offset = Tuple(it.parent.offset) .+ (Tuple(it.subtile_indices[state])  .- 1) .* Tuple(tile_size)

    # Create tile
    tile = Tile{tile_size, names, T}(NamedTuple{names, T}(base), NamedTuple{names, T}(offset))

    # Transpose
    tile = col_major ? tile : transpose(tile)

    return (tile, state + it.step)
end

end


text:
using Clang.cindex
using Clang.wrap_c

JULIAHOME=EnvHash()["JULIAHOME"]

clang_includes = map(x->joinpath(JULIAHOME, x), [
  "deps/llvm-3.2/build/Release/lib/clang/3.2/include",
  "deps/llvm-3.2/include",
  "deps/llvm-3.2/include",
  "deps/llvm-3.2/build/include/",
  "deps/llvm-3.2/include/"
  ])
clang_extraargs = ["-D", "__STDC_LIMIT_MACROS", "-D", "__STDC_CONSTANT_MACROS"]

wrap_hdrs = map( x-> joinpath("/usr/include/openssl", x), [ "md5.h", "hmac.h", "sha.h", "evp.h" ])

#begin println("$th, $h"); (contains(wrap_hdrs, h) && (th == h)) end
wc = wrap_c.init(".", "../src/crypto_common_h.jl", clang_includes, clang_extraargs, (th, h) -> false, h -> "libcrypto", h -> "../src/crypto_" * replace(last(split(h, "/")), ".", "_")  * ".jl" )
wc.options.wrap_structs = false

wrap_c.wrap_c_headers(wc, wrap_hdrs)

# generate export statements.....
fe = open("../src/crypto_exports_h.jl", "w+")
println(fe, "#   Generating exports")

gen_files = map( x-> "../src/crypto_" * x * "_h.jl", [ "common", "md5", "hmac", "sha", "evp"  ])

for gf in gen_files
    fc = open(gf, "r")
    genjl = split(readall(fc), "\n")
    close(fc)

    for e in genjl
        m = match(r"^\s*\@c\s+[\w\:\{\}\_]+\s+(\w+)", e)
        if (m != nothing)
        #    println (m.captures[1])
            @printf fe "export %s\n"  m.captures[1]
        else
            m = match(r"^\s*\@ctypedef\s+(\w+)", e)
            if (m != nothing)
            #    println(m.captures[1])
                @printf fe "export %s\n"  m.captures[1]
            else
                m = match(r"^\s*const\s+(\w+)", e)
                if (m != nothing)
            #        println(m.captures[1])
                    @printf fe "export %s\n"  m.captures[1]
                end
            end
        end
    end
end

function is_valid_c_macro(s)
    for pfx in ["MD5", "SHA", "HMAC", "EVP", "NID_"]
        if beginswith(s, pfx)
            return true
        end
    end
    return false
end

ign_defs = [
    "MD5_LONG",
    "SHA_LONG",
    "SHA_LONG64",

    # May have to manualy support the below later....
    "EVP_PKEY_NULL_method",
    "EVP_PKEY_DSA_method",
    "EVP_PKEY_ECDSA_method",
    "EVP_PKEY_RSA_method",
    "EVP_PKEY_RSA_ASN1_OCTET_STRING_method",

    # Bug in headers?
    "EVP_PKEY_OP_TYPE_NOGEN"
]

f = open("../src/crypto_defines_h.jl", "w+")
println(f, "#   Generating #define constants")

is_defined_set = Set(String, 0)

for fn in ["md5", "hmac", "sha", "evp"]
    hashdefs = split(readall(`gcc -E -dD -P /usr/include/openssl/$(fn).h`), "\n")
    for e in hashdefs
        m = match(r"^\s*#define\s+(\w+)\s+(.+)", e)
        if (m != nothing)
            if is_valid_c_macro(m.captures[1]) && !contains(ign_defs, m.captures[1]) && !contains(is_defined_set, m.captures[1])
                @printf f "const %-30s = %s\n"  m.captures[1]  m.captures[2]
                @printf fe "export %s\n"  m.captures[1]
                add!(is_defined_set, m.captures[1])
            end
        end
    end
end

close(f)
close(fe)


text:
todisplay = VERSION <= VersionNumber("1.2") ? true : false

using CAGD
using SparseArrays
using LinearAlgebraicRepresentation
Lar = LinearAlgebraicRepresentation

if todisplay
	using ViewerGL
	GL = ViewerGL
	include("../examples/3d/views.jl")
end

V1, (VV,EV,FV,CV) = Lar.simplex(3, true)
tetra1 = V1, EV, FV, CV
V2 = [
    0.0 0.5 0.1 0.1
    0.0 0.1 0.5 0.1
    0.0 0.1 0.1 0.5
]
tetra2 = V2, EV, FV, CV
twotetra = Lar.Struct([ tetra1, tetra2 ])
V,EV,FV,CV = Lar.struct2lar(twotetra)
model = CAGD.Model(V);
CAGD.addModelCells!(model, 1, convert(Lar.ChainOp, Lar.coboundary_0(EV::Lar.Cells)))
CAGD.addModelCells!(model, 2, Lar.coboundary_1(V, FV::Lar.Cells, EV::Lar.Cells))

# Spatial Arrangement
split_model = CAGD.facesplitting(model)

if todisplay  displayModel(split_model)  end

congr_model = CAGD.mergeModelVertices(split_model, signed_merge=true)

if todisplay  displayModel(congr_model)  end

gift_model = deepcopy(congr_model)
FCcycles, bicon_comps = CAGD.tgw(congr_model, 3)
CAGD.addModelCells!(gift_model, 3, convert(Lar.ChainOp, FCcycles'))

if todisplay  viewExplode(gift_model)  end

externals = [bc[CAGD.getExternalBoundary(congr_model, 3, FCcycles, bc)] for bc in bicon_comps]
internals = [setdiff(bicon_comps[i], externals[i]) for i = 1 : length(externals)]
assembled_model = deepcopy(congr_model)
## To Fix
FC = FCcycles[:, internals...]
JK = ones(Int8, length(externals))
FC = [FCcycles * SparseArrays.sparse(externals, JK, JK, size(FCcycles, 2), 1) FC]
CAGD.addModelCells!(assembled_model, 3, convert(Lar.ChainOp, FC'))

if todisplay  viewExplode(assembled_model)  end


text:
module SpeedyWeather

    # STRUCTURE
    import Parameters: @with_kw, @unpack

    # NUMERICS
    import FastGaussQuadrature: gausslegendre
    import AssociatedLegendrePolynomials
    import FFTW: rfft, irfft
    import LinearAlgebra: dot

    # INPUT OUTPUT
    import Dates: DateTime
    import Printf: @sprintf
    import NetCDF: NetCDF, NcFile, NcDim, NcVar
    import BitInformation: round, round!

    export run_speedy,
        Parameters, GenLogisticCoefs,
        GeoSpectral, Boundaries, Constants, Geometry,
        PrognosticVariables, DiagnosticVariables,
        fourier, fourier_inverse,
        legendre, legendre_inverse,
        spectral, gridded

    include("utility_functions.jl")
    include("parameter_structs.jl")
    include("parameters.jl")
    include("constants.jl")
    include("geometry.jl")
    include("spectral_transform.jl")
    include("legendre.jl")
    include("fourier.jl")
    include("boundaries.jl")
    include("diagnostics.jl")
    include("prognostic_variables.jl")
    include("diagnostic_variables.jl")
    include("geopotential.jl")
    include("horizontal_diffusion.jl")
    include("implicit.jl")
    include("tendencies.jl")
    include("feedback.jl")
    include("output.jl")
    include("time_integration.jl")
    include("run_speedy.jl")
end


text:
using Test
using LinearAlgebra: UniformScaling
using MeshCat
using GeometryBasics
using CoordinateTransformations
using Colors
using MeshIO, FileIO
using Rotations

include("util.jl")

@testset "MeshCat" begin
    include("video_rendering.jl")
    include("paths.jl")
    include("visualizer.jl")
    include("notebook.jl")
    include("scenes.jl")
    include("wait.jl")
end

module ModuleTest
    # Test for any https://github.com/JuliaLang/julia/issues/21653
    # related issues when MeshCat is included in another module
    using MeshCat
end


text:
@testset begin "Connectivities"
  c = connect((1,2,3), Triangle)
  @test indices(c) == (1,2,3)
  @test polytopetype(c) == Triangle
  @test materialize(c, P2[(0,0),(1,0),(0,1)]) == Triangle(P2(0,0), P2(1,0), P2(0,1))

  # tuple from other collections
  c = connect(Tuple([1,2,3]), Triangle)
  @test indices(c) == (1,2,3)
  @test polytopetype(c) == Triangle
  @test materialize(c, P2[(0,0),(1,0),(0,1)]) == Triangle(P2(0,0), P2(1,0), P2(0,1))
end


text:
# Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.

multiple_3_5(x) = ((x % 3) == 0) || ((x % 5) == 0)

∑ = 0
for i in 1:1000-1
    global ∑ += multiple_3_5(i) ? i : 0
end
print(∑)

max_stars_repo_name: pedvide/project-euler

max_issues_repo_name: pedvide/project-euler

max_forks_repo_name: pedvide/project-euler


text:
using Base.Test
using DataFrames

let
    filename = Pkg.dir("DataFrames", "test", "data", "sample_data.csv")

    ds = DataStream(filename)
    next_df = start(ds)
    (df, next_df) = next(ds, next_df)
    @assert done(ds, next_df) == false
    (df, next_df) = next(ds, next_df)
    @assert done(ds, next_df) == false
    (df, next_df) = next(ds, next_df)
    @assert done(ds, next_df) == true

    filename = Pkg.dir("DataFrames", "test", "data", "big_data.csv")

    ds = DataStream(filename, 100)
    next_df = start(ds)
    (df, next_df) = next(ds, next_df)
    @assert done(ds, next_df) == false

    ds = DataStream(filename, 5)

    for minibatch in ds
        @assert isa(minibatch, DataFrame)
    end

    means = colmeans(ds)
    @assert abs(means[1, 4] - (-0.005686449)) < 10e-4
    @assert abs(means[1, 5] - 19.01197) < 10e-4

    vars = colvars(ds)
    @assert abs(vars[1, 4] - 0.98048) < 10e-4
    @assert abs(vars[1, 5] - 0.989416) < 10e-4

    (mins, maxs) = colranges(ds)
    @assert abs(mins[1, 4] - (-4.33635)) < 10e-4
    @assert abs(mins[1, 5] - 15.6219) < 10e-4
    @assert abs(maxs[1, 4] - 3.86857) < 10e-4
    @assert abs(maxs[1, 5] - 22.574) < 10e-4

    covariances = cov(ds)
    for i in 1:ncol(covariances)
        if isna(covariances[i, i])
            @assert isna(vars[1, i])
        else
            @assert abs(covariances[i, i] - vars[1, i]) < 10e-4
        end
    end
    @assert abs(covariances[4, 4] - 0.980479916) < 10e-4
    @assert abs(covariances[4, 5] - 0.009823644) < 10e-4
    @assert abs(covariances[5, 4] - 0.009823644) < 10e-4
    @assert abs(covariances[5, 5] - 0.989415811) < 10e-4

    correlations = cor(ds)
    for i in ncol(correlations)
        for j in ncol(correlations)
            true_value = covariances[i, j] / sqrt(covariances[i, i] * covariances[j, j])
            if isna(true_value)
                @assert isna(correlations[i, j])
            else
                @assert abs(correlations[i, j] - true_value) < 10e-4
            end
        end
    end

    # Deal with different delimiters
    filename = Pkg.dir("DataFrames", "test", "data", "sample_data.csv")
    ds = DataStream(filename)
    for row in ds
        @assert nrow(row) <= 1
    end

    filename = Pkg.dir("DataFrames", "test", "data", "sample_data.tsv")
    ds = DataStream(filename)
    for row in ds
        @assert nrow(row) <= 1
    end

    filename = Pkg.dir("DataFrames", "test", "data", "sample_data.wsv")
    ds = DataStream(filename)
    for row in ds
        @assert nrow(row) <= 1
    end

    # DataFrame to DataStream conversion
    df = DataFrame(quote A = 1:25 end)

    ds = DataStream(df, 5)

    for mini in ds
        @assert nrow(mini) <= 5
    end

    colmeans(ds)
end


text:
using Iris
using Test

@testset "DielectricFunctions" begin
        ε = @test_nowarn Iris.Common.DielectricFunctions.PiecewiseConstant(1)
        @test ε(Point(0,0)) ≈ complex(1,0)^2
        ε = @test_nowarn Iris.Common.DielectricFunctions.PiecewiseConstant(1,1)
        @test ε(Point(0,0)) ≈ complex(1,1)^2
        ε = @test_nowarn Iris.Common.DielectricFunctions.PiecewiseConstant(1+.2im)
        @test ε(Point(0,0)) ≈ complex(1,.2)^2
        @test_nowarn ε.n1 = .1
        @test ε(Point(0,0)) ≈ complex(.1,.2)^2
        @test_nowarn ε.n₁ = .2
        @test ε(Point(0,0)) ≈ complex(.2,.2)^2
        @test_nowarn ε.n2 = .3
        @test ε(Point(0,0)) ≈ complex(.2,.3)^2
        @test_nowarn ε.n₂ = .4
        @test ε(Point(0,1000)) ≈ complex(.2,.4)^2
        @test_nowarn ε.ε = complex(2,4)^2
        @test ε(Point(0,1000)) ≈ complex(2,4)^2
        @test ε.n1 ≈ 2
        @test ε.n₁ ≈ 2
        @test ε.n2 ≈ 4
        @test ε.n₂ ≈ 4
end


text:
include(joinpath(pwd(), "src/models/miniature_golf.jl"))
include(joinpath(pwd(), "src/constraints/contact.jl"))
include(joinpath(pwd(), "src/constraints/visualize.jl"))

# Horizon
T = 41

tf = 2.0
h = tf / (T-1)

# Bounds
_uu = Inf * ones(model.m)
_ul = -Inf * ones(model.m)
_ul[model.nu .+ (1:m_contact)] .= 0.0

ul, uu = control_bounds(model, T, _ul, _uu)

# Initial and final states
px_init = [0.66; 0.0; softplus(0.66)]
px_goal = [0.66; -3.0; softplus(0.66)]

q1 = [q_res1; px_init]
qT = [q_res2; px_goal]

x1 = [q1; q1]

xl, xu = state_bounds(model, T, [model.qL; model.qL], [model.qU; model.qU],
	x1 = x1)

# Objective
q_ref = linear_interp(q1, qT, T)
x_ref = configuration_to_state(q_ref)
set_configuration!(mvis, q_init)
set_configuration!(state, q_init)
u_ref = [h * Array(RigidBodyDynamics.dynamics_bias(state));
	zeros(model.m - model.nu)]

Qq = Diagonal([10.0 * ones(7); 1.0 * ones(3)])
Q = cat(0.5 * Qq, 0.5 * Qq, dims = (1, 2))
QT = cat(0.5 * Qq, Diagonal([10.0 * ones(7); 1000.0 * ones(3)]), dims = (1, 2))
R = Diagonal([1.0e-1 * ones(model.nu)..., zeros(model.m - model.nu)...])

obj_tracking = quadratic_tracking_objective(
    [t < T ? Q : QT for t = 1:T],
    [R for t = 1:T-1],
    [x_ref[t] for t = 1:T],
    [u_ref for t = 1:T]
    )
obj_penalty = PenaltyObjective(1000.0, model.m)
obj = MultiObjective([obj_tracking, obj_penalty])

# Constraints
con_contact = contact_constraints(model, T)

# Problem
prob = problem(model,
               obj,
               T,
               h = h,
               xl = xl,
               xu = xu,
               ul = ul,
               uu = uu,
               con = con_contact
               )

# Trajectory initialization
X0 = deepcopy(x_ref)
U0 = [[u_ref[1:model.nu]; 1.0e-5 * rand(model.m - model.nu)] for t = 1:T-1] # random controls

# Pack trajectories into vector
Z0 = pack(X0, U0, prob)

@time Z̄ = solve(prob, copy(Z0),
	c_tol = 1.0e-3, tol = 1.0e-3, max_iter = 1000)

check_slack(Z̄, prob)
X̄, Ū = unpack(Z̄, prob)

# [ϕ_func(model,X̄[t]) for t = 1:T]
# x_nom = [X̄[t][1] for t = 1:T]
# z_nom = [X̄[t][2] for t = 1:T]
# u_nom = [Ū[t][model.idx_u] for t = 1:T-1]
# λ_nom = [Ū[t][model.idx_λ[1]] for t = 1:T-1]
# b_nom = [Ū[t][model.idx_b] for t = 1:T-1]
# ψ_nom = [Ū[t][model.idx_ψ[1]] for t = 1:T-1]
# η_nom = [Ū[t][model.idx_η] for t = 1:T-1]

# plot(hcat(u_nom...)')
# plot(hcat(λ_nom...)', linetype=:steppost)
# plot(hcat(b_nom...)',linetype=:steppost)
# plot(hcat(ψ_nom...)',linetype=:steppost)
# plot(hcat(η_nom...)',linetype=:steppost)
# plot(hcat(U_nom...)',linetype=:steppost)

visualize!(mvis, model, state_to_configuration(X̄), Δt = h)

max_stars_repo_name: zacmanchester/DirectMotionPlanning

max_issues_repo_name: zacmanchester/DirectMotionPlanning

max_forks_repo_name: zacmanchester/DirectMotionPlanning


text:
using LiterateOrg
tangle_package(joinpath(dirname(@__FILE__), "..", "src", "Sellmeier.org"), "Sellmeier")


text:
using Documenter, DataTables

makedocs(
	modules=[DataTables],
    sitename="DataTables.jl",
    analytics="UA-132838790-1",
	pages=[
        "Introduction" => "index.md"
    ]
)

deploydocs(
    repo="github.com/queryverse/DataTables.jl.git"
)


text:
"""
    LazyRow(s::StructArray, i)

A lazy representation of `s[i]`. `LazyRow(s, i)` does not materialize the `i`th
row but returns a lazy wrapper around it on which `getproperty` does the correct
thing. This is useful when the row has many fields only some of which are
necessary. It also allows changing columns in place.

See [`LazyRows`](@ref) to get an iterator of `LazyRow`s.

# Examples

```julia-repl
julia> t = StructArray((a = [1, 2], b = ["x", "y"]));

julia> LazyRow(t, 2).a
2

julia> LazyRow(t, 2).a = 123
123

julia> t
2-element StructArray(::Array{Int64,1}, ::Array{String,1}) with eltype NamedTuple{(:a, :b),Tuple{Int64,String}}:
 (a = 1, b = "x")
 (a = 123, b = "y")
```
"""
struct LazyRow{T, N, C, I}
    columns::StructArray{T, N, C, I} # a `Columns` object
    index::I
end

for typ in [:Symbol, :Int]
    @eval begin
        @inline Base.@propagate_inbounds function Base.getproperty(c::LazyRow, nm::$typ)
            return getproperty(getfield(c, 1), nm)[getfield(c, 2)]
        end
        @inline Base.@propagate_inbounds function Base.setproperty!(c::LazyRow, nm::$typ, val)
            getproperty(getfield(c, 1), nm)[getfield(c, 2)] = val
        end
    end
end
Base.propertynames(c::LazyRow) = propertynames(getfield(c, 1))

function Base.show(io::IO, c::LazyRow)
    print(io, "LazyRow")
    columns, index = getfield(c, 1), getfield(c, 2)
    tup = StructArray(components(columns))[index]
    show(io, tup)
end

@inline Base.@propagate_inbounds component(l::LazyRow, key) = getproperty(l, key)

staticschema(::Type{<:LazyRow{T}}) where {T} = staticschema(T)
buildfromschema(f, ::Type{<:LazyRow{T}}) where {T} = buildfromschema(f, T)
iscompatible(::Type{<:LazyRow{R}}, ::Type{S}) where {R, S<:StructArray} = iscompatible(R, S)

(s::ArrayInitializer)(::Type{<:LazyRow{T}}, d) where {T} = buildfromschema(typ -> s(typ, d), T)

maybe_convert_elt(::Type{T}, vals::LazyRow) where T = vals

"""
    LazyRows(s::StructArray)

An iterator of [`LazyRow`](@ref)s of `s`.

# Examples

```julia-repl
julia> map(t -> t.b ^ t.a, LazyRows(t))
2-element Array{String,1}:
 "x"
 "yy"
```
"""
struct LazyRows{T, N, C, I} <: AbstractArray{LazyRow{T, N, C, I}, N}
    columns::StructArray{T, N, C, I}
end
Base.parent(v::LazyRows) = getfield(v, 1)
components(v::LazyRows) = components(parent(v))

component(v::LazyRows, key) = component(parent(v), key)

staticschema(::Type{LazyRows{T, N, C, I}}) where {T, N, C, I} = staticschema(C)
createinstance(::Type{<:LazyRows{T}}, args...) where {T} = LazyRows(StructArray{T}(args))

Base.getproperty(v::LazyRows, key::Symbol) = component(v, key)
Base.getproperty(v::LazyRows, key::Int) = component(v, key)
Base.propertynames(v::LazyRows) = propertynames(parent(v))

Base.size(v::LazyRows) = size(parent(v))
Base.getindex(v::LazyRows{<:Any, <:Any, <:Any, Int}, i::Int) = LazyRow(parent(v), i)
Base.getindex(v::LazyRows{<:Any, <:Any, <:Any, CartesianIndex{N}}, i::Vararg{Int, N}) where {N} = LazyRow(parent(v), CartesianIndex(i))

index_type(::Type{LazyRows{T, N, C, I}}) where {T, N, C, I} = I
function Base.IndexStyle(::Type{L}) where {L<:LazyRows}
    index_type(L) === Int ? IndexLinear() : IndexCartesian()
end

function Base.showarg(io::IO, s::LazyRows{T}, toplevel) where T
    print(io, "LazyRows")
    showfields(io, Tuple(components(s)))
    toplevel && print(io, " with eltype LazyRow{", T, "}")
end


text:
"""
Return default marking value based on `PNTD`. Has meaning of empty, as in `zero`.
"""
function default_marking end
default_marking(::PNTD) where {PNTD <: PnmlType} = PTMarking(zero(Integer))
default_marking(::Type{PNTD}) where {PNTD <: PnmlType} = PTMarking(zero(Integer))
default_marking(::PNTD) where {PNTD <: AbstractContinuousCore} = PTMarking(zero(Float64))
default_marking(::Type{PNTD}) where {PNTD <: AbstractContinuousCore} = PTMarking(zero(Float64))
default_marking(pntd::PNTD) where {PNTD <: AbstractHLCore} = HLMarking(default_term(pntd))

#-------------------
"""
Number-valued label of [`Place`](@ref).
See [`PTNet`](@ref), [`ContinuousNet`](@ref).

$(TYPEDEF)
$(TYPEDFIELDS)

# Examples

```jldoctest
julia> using PNML

julia> m = PNML.PTMarking();

julia> m()
0

julia> m = PNML.PTMarking(1);

julia> m()
1

julia> m = PNML.PTMarking(12.34);

julia> m()
12.34
```
"""
struct PTMarking{N<:Number} <: Annotation
    value::N
    com::ObjectCommon
    # PTMarking does not use ObjectCommon.graphics,
    # but rather, TokenGraphics in ObjectCommon.tools.
end
PTMarking() = PTMarking(zero(Int))
PTMarking(value) = PTMarking(value, ObjectCommon())

"""
Evaluate a [`PTMarking`](@ref) instance.
"""
(mark::PTMarking)() = mark.value

#-------------------
"""
Label a Place in a High-level Petri Net Graph.
See [`AbstractHLCore`](#ref).

$(TYPEDEF)
$(TYPEDFIELDS)

# Examples

```jldoctest
julia> using PNML: HLMarking, PnmlDict, Term

julia> m = HLMarking("the text", Term(:term, PnmlDict(:value=>3)));

julia> m()
3
```
"""
struct HLMarking{TermType} <: HLAnnotation
    text::Maybe{String}
    term::Maybe{TermType} # is the expected structure content
    com::ObjectCommon
    #TODO check that there is a text or structure (or both)
end

HLMarking() = HLMarking(nothing, Term())
HLMarking(s::AbstractString) = HLMarking(s, Term())
HLMarking(t::AbstractTerm) = HLMarking(nothing, t, ObjectCommon())
HLMarking(s::AbstractString, t::AbstractTerm) = HLMarking(s, t, ObjectCommon())

"""
Evaluate a [`HLMarking`](@ref) instance.
Returns a value of the same sort as its `Place`.
#TODO How to ensure sort type?
"""
(hlm::HLMarking)() = _evaluate(hlm.term)

"""
Inscriptions, Markings, Conditions evaluate a value that may be a scalar of a Term functor.
"""
function _evaluate end
_evaluate(x::Term) = x()
_evaluate(x::Bool) = x
_evaluate(x::Number) = x


text:
"""
    ModelFactory

A collection of functions to generate the feedback networks and baseline models
used in evaluations and examples.
"""
module ModelFactory
using Reexport

include("Flatten.jl")
@reexport using .Flatten

include("LRNs.jl")
@reexport using .LRNs

include("LeNet5.jl")
@reexport using .LeNet5

include("Spoerer2017.jl")
@reexport using .Spoerer2017

end # module ModelFactory


text:
module MountainCar

using Random

const vel_limit = (-0.07, 0.07)
const pos_limit = (-1.2, 0.5)
const pos_initial_range = (-0.6, 0.4)

mutable struct State
    pos::Float64
    vel::Float64
    State() = new(0.0, 0.0)
    State(rng::AbstractRNG) = new(rand(rng)*(pos_initial_range[2] - pos_initial_range[1]) + pos_initial_range[1], 0)
end

function start(;rng = Random.GLOBAL_RNG)
    return State(rng)
end

function step!(state::State, action; kwargs...) # -> agent_state, reward, terminal
    # println(clamp(agent_state.vel + action*0.001 - 0.0025*cos(3*agent_state.pos), vel_limit...))
    state.vel = clamp(state.vel + (action - 1)*0.001 - 0.0025*cos(3*state.pos), vel_limit...)
    state.pos = clamp(state.pos + state.vel, pos_limit...)
    return state, get_reward(state), is_terminal(state)
end

function step(state::State, action; kwargs...)
    new_state = copy(state)
    return step!(new_agent_state, action; kwargs...)
end

function get_reward(state) # -> determines if the agent_state is terminal
    if state.pos >= pos_limit[2]
        return 0
    end
    return -1
end

function is_terminal(state) # -> determines if the agent_state is terminal
    return state.pos >= pos_limit[2]
end

function normalized_features(state)
    return [(state.pos - pos_limit[1])/(pos_limit[2] - pos_limit[1]), (state.vel - vel_limit[1])/(vel_limit[2] - vel_limit[1])]
end

end

max_stars_repo_name: mkschleg/JuliaRL

max_issues_repo_name: mkschleg/JuliaRL

max_forks_repo_name: mkschleg/JuliaRL