repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sxhya/roots | src/experiments/GCMExperiments.kt | 1 | 10797 | import java.util.ArrayList
import java.util.Arrays
class GCMExperiments {
companion object {
private fun convertGCMtoAwt(gcm: IntegerMatrix): IntegerMatrix {
val n = gcm.height()
assert(n == gcm.width())
val result = IntegerMatrix(Array((n * n - n) / 2) { LongArray(n) })
var counter = 0
for (i in 0 until n)
for (j in i + 1 until n) {
result.myCoo[counter][i] = gcm.myCoo[j][i]
result.myCoo[counter][j] = -gcm.myCoo[i][j]
counter++
}
return result
}
private fun gcmexperiment(name: String, gcm: Array<LongArray>) {
val oddColumns = ArrayList<Int>()
val evenColumns = ArrayList<Int>()
val cm = IntegerMatrix(gcm)
assert(cm.width() == cm.height())
for (i in 0 until cm.width()) {
var even = true
for (j in 0 until cm.height())
if (cm.myCoo[j][i] % 2 != 0L)
even = false
(if (even) evenColumns else oddColumns).add(i)
}
val p = IntArray(cm.width())
var c = 0
for (oc in oddColumns) p[c++] = oc
for (oc in evenColumns) p[c++] = oc
// o, e, o --> p = 0, 2 | 1
val gcm2 = Array(cm.height()) { LongArray(cm.width()) }
for (i in 0 until cm.height()) {
for (j in 0 until cm.width())
gcm2[i][j] = gcm[p[i]][p[j]]
}
val awt = convertGCMtoAwt(IntegerMatrix(gcm2))
val computer = IntegerMatrix.SNFComputer(awt)
computer.doComputeSNF()
val n = oddColumns.size
val m = evenColumns.size
print("\nExample #$name: ")
println("Odd: $n; Even: $m;")
println("\nSmith normal form: \n" + Arrays.toString(computer.s.getDiagonalEntries()))
val nn = oddColumns.size + evenColumns.size
assert(nn == Math.min(awt.width(), awt.height()))
for (i in 0 until nn) {
val entry = Math.abs(computer.s.myCoo[i][i])
val parity = computer.isEven[i]
if (parity) {
if (entry == 0L) {
print("K_2^{MW}(F); ")
} else if (entry == 2L) {
print("K_2^{MW}/<{u^2, v}>; ")
} else {
print("K_2^{MW}/" + entry / 2 + "<{u^2, v}>; ")
}
} else {
if (entry == 0L) {
print("K_2(F);")
} else if (entry != 1L) {
print("K_2(F) / " + entry + "K_2(F); ")
}
}
}
println()
println("\nQ matrix: \n" + computer.q)
println("\nPA matrix: \n" + computer.p.mul(awt))
println("Indices: " + Arrays.toString(p))
}
fun doAllGCMExperiments() {
gcmexperiment("27", arrayOf(longArrayOf(2, -1, 0),
longArrayOf(-3, 2, -2),
longArrayOf(0, -1, 2)))
gcmexperiment("40", arrayOf(longArrayOf(2, -1, -2),
longArrayOf(-1, 2, -2),
longArrayOf(-2, -2, 2)))
gcmexperiment("55", arrayOf(longArrayOf(2, -1, -2),
longArrayOf(-2, 2, -2),
longArrayOf(-2, -1, 2)))
gcmexperiment("59", arrayOf(longArrayOf(2, -1, -2),
longArrayOf(-2, 2, -2),
longArrayOf(-2, -2, 2)))
gcmexperiment("63", arrayOf(longArrayOf(2, -2, -3),
longArrayOf(-1, 2, -2),
longArrayOf(-1, -2, 2)))
gcmexperiment("67", arrayOf(longArrayOf(2, -2, -4),
longArrayOf(-1, 2, -2),
longArrayOf(-1, -2, 2)))
gcmexperiment("81", arrayOf(longArrayOf(2, -2, -3),
longArrayOf(-2, 2, -2),
longArrayOf(-1, -2, 2)))
gcmexperiment("82", arrayOf(longArrayOf(2, -2, -4),
longArrayOf(-2, 2, -2),
longArrayOf(-1, -2, 2)))
gcmexperiment("88", arrayOf(longArrayOf(2, -2, -1),
longArrayOf(-2, 2, -1),
longArrayOf(-4, -3, 2)))
gcmexperiment("90", arrayOf(longArrayOf(2, -1, -2),
longArrayOf(-4, 2, -4),
longArrayOf(-2, -1, 2)))
gcmexperiment("103", arrayOf(longArrayOf(2, -2, 0),
longArrayOf(-2, 2, -1),
longArrayOf(0, -1, 2)))
gcmexperiment("106", arrayOf(longArrayOf(2, -2, 0),
longArrayOf(-2, 2, -2),
longArrayOf(0, -1, 2)))
gcmexperiment("110", arrayOf(longArrayOf(2, -1, 0),
longArrayOf(-4, 2, -2),
longArrayOf(0, -1, 2)))
gcmexperiment("113", arrayOf(longArrayOf(2, -2, 0),
longArrayOf(-2, 2, -1),
longArrayOf(0, -3, 2)))
gcmexperiment("114", arrayOf(longArrayOf(2, -2, 0),
longArrayOf(-2, 2, -3),
longArrayOf(0, -1, 2)))
gcmexperiment("116", arrayOf(longArrayOf(2, -1, 0),
longArrayOf(-4, 2, -2),
longArrayOf(0, -2, 2)))
gcmexperiment("119", arrayOf(longArrayOf(2, -1, 0),
longArrayOf(-3, 2, -4),
longArrayOf(0, -1, 2)))
gcmexperiment("122", arrayOf(longArrayOf(2, -1, 0),
longArrayOf(-4, 2, -4),
longArrayOf(0, -1, 2)))
gcmexperiment("128", arrayOf(longArrayOf(2, -1, -1, 0),
longArrayOf(-1, 2, -1, 0),
longArrayOf(-1, -1, 2, -2),
longArrayOf(0, 0, -1, 2)))
gcmexperiment("135", arrayOf(longArrayOf(2, -1, 0, -1),
longArrayOf(-1, 2, -2, 0),
longArrayOf(0, -1, 2, -1),
longArrayOf(-1, 0, -2, 2)))
gcmexperiment("143", arrayOf(longArrayOf(2, -1, 0, -2),
longArrayOf(-1, 2, -1, 0),
longArrayOf(0, -2, 2, -2),
longArrayOf(-1, 0, -1, 2)))
gcmexperiment("144", arrayOf(longArrayOf(2, -1, 0, -2),
longArrayOf(-1, 2, -2, 0),
longArrayOf(0, -1, 2, -2),
longArrayOf(-1, 0, -1, 2)))
gcmexperiment("146", arrayOf(longArrayOf(2, -1, 0, -2),
longArrayOf(-2, 2, -2, 0),
longArrayOf(0, -1, 2, -2),
longArrayOf(-1, 0, -1, 2)))
gcmexperiment("147", arrayOf(longArrayOf(2, -1, 0, -2),
longArrayOf(-2, 2, -1, 0),
longArrayOf(0, -2, 2, -2),
longArrayOf(-1, 0, -1, 2)))
gcmexperiment("148", arrayOf(longArrayOf(2, -2, 0, -2),
longArrayOf(-1, 2, -1, 0),
longArrayOf(0, -2, 2, -2),
longArrayOf(-1, 0, -1, 2)))
gcmexperiment("156", arrayOf(longArrayOf(2, 0, 0, -1),
longArrayOf(0, 2, 0, -1),
longArrayOf(0, 0, 2, -1),
longArrayOf(-2, -2, -2, 2)))
gcmexperiment("162", arrayOf(longArrayOf(2, -1, 0, 0),
longArrayOf(-1, 2, -1, 0),
longArrayOf(0, -2, 2, -2),
longArrayOf(0, 0, -1, 2)))
gcmexperiment("168", arrayOf(longArrayOf(2, -1, 0, 0),
longArrayOf(-2, 2, -1, 0),
longArrayOf(0, -1, 2, -3),
longArrayOf(0, 0, -1, 2)))
gcmexperiment("174", arrayOf(longArrayOf(2, -1, 0, 0),
longArrayOf(-2, 2, -2, 0),
longArrayOf(0, -1, 2, -2),
longArrayOf(0, 0, -1, 2)))
gcmexperiment("179", arrayOf(longArrayOf(2, -1, -1, 0, 0),
longArrayOf(-1, 2, 0, -1, 0),
longArrayOf(-1, 0, 2, -1, 0),
longArrayOf(0, -1, -1, 2, -2),
longArrayOf(0, 0, 0, -1, 2)))
gcmexperiment("197", arrayOf(longArrayOf(2, -1, 0, 0, 0),
longArrayOf(-1, 2, -1, 0, 0),
longArrayOf(0, -2, 2, -1, 0),
longArrayOf(0, 0, -1, 2, -2),
longArrayOf(0, 0, 0, -1, 2)))
gcmexperiment("215", arrayOf(longArrayOf(2, -1, 0, 0, 0, 0),
longArrayOf(-1, 2, -1, 0, 0, 0),
longArrayOf(0, -2, 2, -1, 0, 0),
longArrayOf(0, 0, -1, 2, -1, 0),
longArrayOf(0, 0, 0, -1, 2, -2),
longArrayOf(0, 0, 0, 0, -1, 2)))
}
}
}
| apache-2.0 | 2398077660f3a469ba7097978e8229d1 | 44.75 | 97 | 0.346115 | 4.604264 | false | false | false | false |
mvaldez/kotlin-examples | src/i_introduction/_3_Default_Arguments/DefaultAndNamedParams.kt | 1 | 918 | package i_introduction._3_Default_Arguments
import util.TODO
import util.doc2
fun todoTask3(): Nothing = TODO(
"""
Task 3.
Several overloads of 'JavaCode3.foo()' can be replaced with one function in Kotlin.
Change the declaration of the function 'foo' in a way that makes the code using 'foo' compile.
You have to add parameters and replace 'todoTask3()' with a real body.
Uncomment the commented code and make it compile.
""",
documentation = doc2(),
references = { name: String -> JavaCode3().foo(name); foo(name) })
fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String {
return (if(toUpperCase) name.toUpperCase() else name).plus(number)
}
fun task3(): String {
return (foo("a") +
foo("b", number = 1) +
foo("c", toUpperCase = true) +
foo(name = "d", number = 2, toUpperCase = true))
}
| mit | 4b48a6e28072264a9f86e542251af285 | 34.307692 | 102 | 0.630719 | 3.939914 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_vertex_program.kt | 1 | 22932 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val ARB_vertex_program = "ARBVertexProgram".nativeClassGL("ARB_vertex_program", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
Unextended OpenGL mandates a certain set of configurable per-vertex computations defining vertex transformation, texture coordinate generation and
transformation, and lighting. Several extensions have added further per-vertex computations to OpenGL. For example, extensions have defined new texture
coordinate generation modes (${ARB_texture_cube_map.link}, ${registryLinkTo("NV", "texgen_reflection")}, ${registryLinkTo("NV", "texgen_emboss")}),
new vertex transformation modes (${ARB_vertex_blend.link}, ${registryLinkTo("EXT", "vertex_weighting")}), new lighting modes (OpenGL 1.2's separate
specular and rescale normal functionality), several modes for fog distance generation (${registryLinkTo("NV", "fog_distance")}), and eye-distance point
size attenuation (${ARB_point_parameters.link}).
Each such extension adds a small set of relatively inflexible per-vertex computations.
This inflexibility is in contrast to the typical flexibility provided by the underlying programmable floating point engines (whether micro-coded vertex
engines, DSPs, or CPUs) that are traditionally used to implement OpenGL's per-vertex computations. The purpose of this extension is to expose to the
OpenGL application writer a significant degree of per-vertex programmability for computing vertex parameters.
For the purposes of discussing this extension, a vertex program is a sequence of floating-point 4-component vector operations that determines how a set
of program parameters (defined outside of OpenGL's GL11#Begin()/GL11#End() pair) and an input set of per-vertex parameters are transformed to a set of
per-vertex result parameters.
The per-vertex computations for standard OpenGL given a particular set of lighting and texture coordinate generation modes (along with any state for
extensions defining per-vertex computations) is, in essence, a vertex program. However, the sequence of operations is defined implicitly by the current
OpenGL state settings rather than defined explicitly as a sequence of instructions.
This extension provides an explicit mechanism for defining vertex program instruction sequences for application-defined vertex programs. In order to
define such vertex programs, this extension defines a vertex programming model including a floating-point 4-component vector instruction set and a
relatively large set of floating-point 4-component registers.
The extension's vertex programming model is designed for efficient hardware implementation and to support a wide variety of vertex programs. By design,
the entire set of existing vertex programs defined by existing OpenGL per-vertex computation extensions can be implemented using the extension's vertex
programming model.
"""
IntConstant(
"""
Accepted by the {@code cap} parameter of Disable, Enable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of ProgramStringARB, BindProgramARB, ProgramEnvParameter4[df][v]ARB, ProgramLocalParameter4[df][v]ARB,
GetProgramEnvParameter[df]vARB, GetProgramLocalParameter[df]vARB, GetProgramivARB, and GetProgramStringARB.
""",
"VERTEX_PROGRAM_ARB"..0x8620
)
IntConstant(
"""
Accepted by the {@code cap} parameter of Disable, Enable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev.
""",
"VERTEX_PROGRAM_POINT_SIZE_ARB"..0x8642,
"VERTEX_PROGRAM_TWO_SIDE_ARB"..0x8643,
"COLOR_SUM_ARB"..0x8458
)
IntConstant(
"Accepted by the {@code format} parameter of ProgramStringARB.",
"PROGRAM_FORMAT_ASCII_ARB"..0x8875
)
IntConstant(
"Accepted by the {@code pname} parameter of GetVertexAttrib[dfi]vARB.",
"VERTEX_ATTRIB_ARRAY_ENABLED_ARB"..0x8622,
"VERTEX_ATTRIB_ARRAY_SIZE_ARB"..0x8623,
"VERTEX_ATTRIB_ARRAY_STRIDE_ARB"..0x8624,
"VERTEX_ATTRIB_ARRAY_TYPE_ARB"..0x8625,
"VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB"..0x886A,
"CURRENT_VERTEX_ATTRIB_ARB"..0x8626
)
IntConstant(
"Accepted by the {@code pname} parameter of GetVertexAttribPointervARB.",
"VERTEX_ATTRIB_ARRAY_POINTER_ARB"..0x8645
)
val PARAMS = IntConstant(
"Accepted by the {@code pname} parameter of GetProgramivARB.",
"PROGRAM_LENGTH_ARB"..0x8627,
"PROGRAM_FORMAT_ARB"..0x8876,
"PROGRAM_BINDING_ARB"..0x8677,
"PROGRAM_INSTRUCTIONS_ARB"..0x88A0,
"MAX_PROGRAM_INSTRUCTIONS_ARB"..0x88A1,
"PROGRAM_NATIVE_INSTRUCTIONS_ARB"..0x88A2,
"MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB"..0x88A3,
"PROGRAM_TEMPORARIES_ARB"..0x88A4,
"MAX_PROGRAM_TEMPORARIES_ARB"..0x88A5,
"PROGRAM_NATIVE_TEMPORARIES_ARB"..0x88A6,
"MAX_PROGRAM_NATIVE_TEMPORARIES_ARB"..0x88A7,
"PROGRAM_PARAMETERS_ARB"..0x88A8,
"MAX_PROGRAM_PARAMETERS_ARB"..0x88A9,
"PROGRAM_NATIVE_PARAMETERS_ARB"..0x88AA,
"MAX_PROGRAM_NATIVE_PARAMETERS_ARB"..0x88AB,
"PROGRAM_ATTRIBS_ARB"..0x88AC,
"MAX_PROGRAM_ATTRIBS_ARB"..0x88AD,
"PROGRAM_NATIVE_ATTRIBS_ARB"..0x88AE,
"MAX_PROGRAM_NATIVE_ATTRIBS_ARB"..0x88AF,
"PROGRAM_ADDRESS_REGISTERS_ARB"..0x88B0,
"MAX_PROGRAM_ADDRESS_REGISTERS_ARB"..0x88B1,
"PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB"..0x88B2,
"MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB"..0x88B3,
"MAX_PROGRAM_LOCAL_PARAMETERS_ARB"..0x88B4,
"MAX_PROGRAM_ENV_PARAMETERS_ARB"..0x88B5,
"PROGRAM_UNDER_NATIVE_LIMITS_ARB"..0x88B6
).javaDocLinks
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramStringARB.",
"PROGRAM_STRING_ARB"..0x8628
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"PROGRAM_ERROR_POSITION_ARB"..0x864B,
"CURRENT_MATRIX_ARB"..0x8641,
"TRANSPOSE_CURRENT_MATRIX_ARB"..0x88B7,
"CURRENT_MATRIX_STACK_DEPTH_ARB"..0x8640,
"MAX_VERTEX_ATTRIBS_ARB"..0x8869,
"MAX_PROGRAM_MATRICES_ARB"..0x862F,
"MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB"..0x862E
)
IntConstant(
"Accepted by the {@code name} parameter of GetString.",
"PROGRAM_ERROR_STRING_ARB"..0x8874
)
IntConstant(
"Accepted by the {@code mode} parameter of MatrixMode.",
"MATRIX0_ARB"..0x88C0,
"MATRIX1_ARB"..0x88C1,
"MATRIX2_ARB"..0x88C2,
"MATRIX3_ARB"..0x88C3,
"MATRIX4_ARB"..0x88C4,
"MATRIX5_ARB"..0x88C5,
"MATRIX6_ARB"..0x88C6,
"MATRIX7_ARB"..0x88C7,
"MATRIX8_ARB"..0x88C8,
"MATRIX9_ARB"..0x88C9,
"MATRIX10_ARB"..0x88CA,
"MATRIX11_ARB"..0x88CB,
"MATRIX12_ARB"..0x88CC,
"MATRIX13_ARB"..0x88CD,
"MATRIX14_ARB"..0x88CE,
"MATRIX15_ARB"..0x88CF,
"MATRIX16_ARB"..0x88D0,
"MATRIX17_ARB"..0x88D1,
"MATRIX18_ARB"..0x88D2,
"MATRIX19_ARB"..0x88D3,
"MATRIX20_ARB"..0x88D4,
"MATRIX21_ARB"..0x88D5,
"MATRIX22_ARB"..0x88D6,
"MATRIX23_ARB"..0x88D7,
"MATRIX24_ARB"..0x88D8,
"MATRIX25_ARB"..0x88D9,
"MATRIX26_ARB"..0x88DA,
"MATRIX27_ARB"..0x88DB,
"MATRIX28_ARB"..0x88DC,
"MATRIX29_ARB"..0x88DD,
"MATRIX30_ARB"..0x88DE,
"MATRIX31_ARB"..0x88DF
)
val VA_INDEX = GLuint.IN("index", "the vertex attribute index")
val VA_X = "the {@code x} attribute component"
val VA_Y = "the {@code y} attribute component"
val VA_Z = "the {@code z} attribute component"
val VA_W = "the {@code w} attribute component"
void("VertexAttrib1sARB", "Short version of #VertexAttrib1fARB()", VA_INDEX, GLshort.IN("x", VA_X))
void(
"VertexAttrib1fARB",
"Specifies the {@code x} component of the current vertex attribute numbered {@code index}. Components {@code y} and {@code z} are set to 0 and {@code w} to 1.",
VA_INDEX, GLfloat.IN("x", VA_X)
)
void("VertexAttrib1dARB", "Double version of #VertexAttrib1fARB()", VA_INDEX, GLdouble.IN("x", VA_X))
void("VertexAttrib2sARB", "Short version of #VertexAttrib2fARB()", VA_INDEX, GLshort.IN("x", VA_X), GLshort.IN("y", VA_Y))
void(
"VertexAttrib2fARB",
"Specifies the {@code x} and {@code y} components of the current vertex attribute numbered {@code index}. Component {@code z} is set to 0 and {@code w} to 1.",
VA_INDEX,
GLfloat.IN("x", VA_X),
GLfloat.IN("y", VA_Y)
)
void("VertexAttrib2dARB", "Double version of #VertexAttrib2fARB()", VA_INDEX, GLdouble.IN("x", VA_X), GLdouble.IN("y", VA_Y))
void("VertexAttrib3sARB", "Short version of #VertexAttrib3fARB()", VA_INDEX, GLshort.IN("x", VA_X), GLshort.IN("y", VA_Y), GLshort.IN("z", VA_Z))
void(
"VertexAttrib3fARB",
"Specifies the {@code x}, {@code y} and {@code z} components of the current vertex attribute numbered {@code index}. Component {@code w} is set to 1.",
VA_INDEX,
GLfloat.IN("x", VA_X),
GLfloat.IN("y", VA_Y),
GLfloat.IN("z", VA_Z)
)
void("VertexAttrib3dARB", "Double version of #VertexAttrib3fARB()", VA_INDEX, GLdouble.IN("x", VA_X), GLdouble.IN("y", VA_Y), GLdouble.IN("z", VA_Z))
void("VertexAttrib4sARB", "Short version of #VertexAttrib4fARB()", VA_INDEX, GLshort.IN("x", VA_X), GLshort.IN("y", VA_Y), GLshort.IN("z", VA_Z), GLshort.IN("w", VA_W))
void(
"VertexAttrib4fARB",
"Specifies the current vertex attribute numbered {@code index}.",
VA_INDEX,
GLfloat.IN("x", VA_X),
GLfloat.IN("y", VA_Y),
GLfloat.IN("z", VA_Z),
GLfloat.IN("w", VA_W)
)
void("VertexAttrib4dARB", "Double version of #VertexAttrib4fARB()", VA_INDEX, GLdouble.IN("x", VA_X), GLdouble.IN("y", VA_Y), GLdouble.IN("z", VA_Z), GLdouble.IN("w", VA_W))
void("VertexAttrib4NubARB", "Fixed-point unsigned byte version of #VertexAttrib4fARB()", VA_INDEX, GLubyte.IN("x", VA_X), GLubyte.IN("y", VA_Y), GLubyte.IN("z", VA_Z), GLubyte.IN("w", VA_W))
val VA_V = "a buffer from which to read the attribute value"
void("VertexAttrib1svARB", "Pointer version of #VertexAttrib1sARB()", VA_INDEX, Check(1)..const..GLshort_p.IN("v", VA_V))
void("VertexAttrib1fvARB", "Pointer version of #VertexAttrib1fARB()", VA_INDEX, Check(1)..const..GLfloat_p.IN("v", VA_V))
void("VertexAttrib1dvARB", "Pointer version of #VertexAttrib1dARB()", VA_INDEX, Check(1)..const..GLdouble_p.IN("v", VA_V))
void("VertexAttrib2svARB", "Pointer version of #VertexAttrib2sARB()", VA_INDEX, Check(2)..const..GLshort_p.IN("v", VA_V))
void("VertexAttrib2fvARB", "Pointer version of #VertexAttrib2fARB()", VA_INDEX, Check(2)..const..GLfloat_p.IN("v", VA_V))
void("VertexAttrib2dvARB", "Pointer version of #VertexAttrib2dARB()", VA_INDEX, Check(2)..const..GLdouble_p.IN("v", VA_V))
void("VertexAttrib3svARB", "Pointer version of #VertexAttrib3sARB()", VA_INDEX, Check(3)..const..GLshort_p.IN("v", VA_V))
void("VertexAttrib3fvARB", "Pointer version of #VertexAttrib3fARB()", VA_INDEX, Check(3)..const..GLfloat_p.IN("v", VA_V))
void("VertexAttrib3dvARB", "Pointer version of #VertexAttrib3dARB()", VA_INDEX, Check(3)..const..GLdouble_p.IN("v", VA_V))
void("VertexAttrib4fvARB", "Pointer version of #VertexAttrib4fARB()", VA_INDEX, Check(4)..const..GLfloat_p.IN("v", VA_V))
void("VertexAttrib4bvARB", "Byte version of #VertexAttrib4fvARB()", VA_INDEX, Check(4)..const..GLbyte_p.IN("v", VA_V))
void("VertexAttrib4svARB", "Pointer version of #VertexAttrib4sARB()", VA_INDEX, Check(4)..const..GLshort_p.IN("v", VA_V))
void("VertexAttrib4ivARB", "Integer version of #VertexAttrib4fvARB()", VA_INDEX, Check(4)..const..GLint_p.IN("v", VA_V))
void("VertexAttrib4ubvARB", "Unsigned byte version of #VertexAttrib4fvARB()", VA_INDEX, Check(4)..const..GLubyte_p.IN("v", VA_V))
void("VertexAttrib4usvARB", "Unsigned short version of #VertexAttrib4fvARB()", VA_INDEX, Check(4)..const..GLushort_p.IN("v", VA_V))
void("VertexAttrib4uivARB", "Unsigned integer version of #VertexAttrib4fvARB()", VA_INDEX, Check(4)..const..GLuint_p.IN("v", VA_V))
void("VertexAttrib4dvARB", "Pointer version of #VertexAttrib4dARB()", VA_INDEX, Check(4)..const..GLdouble_p.IN("v", VA_V))
void("VertexAttrib4NbvARB", "Fixed-point version of #VertexAttrib4bvARB()", VA_INDEX, Check(4)..const..GLbyte_p.IN("v", VA_V))
void("VertexAttrib4NsvARB", "Fixed-point version of #VertexAttrib4svARB()", VA_INDEX, Check(4)..const..GLshort_p.IN("v", VA_V))
void("VertexAttrib4NivARB", "Fixed-point version of #VertexAttrib4ivARB()", VA_INDEX, Check(4)..const..GLint_p.IN("v", VA_V))
void("VertexAttrib4NubvARB", "Fixed-point unsigned version of #VertexAttrib4bvARB()", VA_INDEX, Check(4)..const..GLubyte_p.IN("v", VA_V))
void("VertexAttrib4NusvARB", "Fixed-point unsigned version of #VertexAttrib4svARB()", VA_INDEX, Check(4)..const..GLushort_p.IN("v", VA_V))
void("VertexAttrib4NuivARB", "Fixed-point unsigned version of #VertexAttrib4ivARB()", VA_INDEX, Check(4)..const..GLuint_p.IN("v", VA_V))
void(
"VertexAttribPointerARB",
"Specifies the location and organization of a vertex attribute array.",
VA_INDEX,
GLint.IN("size", "the vertex attribute number of components", "1 2 3 4"),
GLenum.IN(
"type",
"the data type of the values stored in the array",
"GL11#BYTE GL11#SHORT GL11#INT GL11#UNSIGNED_BYTE GL11#UNSIGNED_SHORT GL11#UNSIGNED_INT GL30#HALF_FLOAT NVHalfFloat#HALF_FLOAT_NV GL11#FLOAT GL11#DOUBLE"
),
GLboolean.IN("normalized", "if GL11#TRUE, fixed-point types are normalized when converted to floating-point"),
GLsizei.IN("stride", "the vertex stride in bytes. If specified as zero, then array elements are stored sequentially"),
ARRAY_BUFFER..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..const..void_p.IN("pointer", "the vertex attribute array data")
)
void(
"EnableVertexAttribArrayARB",
"Enables an individual generic vertex attribute array.",
VA_INDEX
)
void(
"DisableVertexAttribArrayARB",
"Disables an individual generic vertex attribute array.",
VA_INDEX
)
val TARGET = GLenum.IN("target", "the program target", "#VERTEX_PROGRAM_ARB ARBFragmentProgram#FRAGMENT_PROGRAM_ARB")
void(
"ProgramStringARB",
"""
Updates the program string for the current program object for {@code target}.
When a program string is loaded, it is interpreted according to syntactic and semantic rules corresponding to the program target specified by
{@code target}. If a program violates the syntactic or semantic restrictions of the program target, ProgramStringARB generates the error
GL11#INVALID_OPERATION.
Additionally, ProgramString will update the program error position (#PROGRAM_ERROR_POSITION_ARB) and error string (#PROGRAM_ERROR_STRING_ARB). If a
program fails to load, the value of the program error position is set to the ubyte offset into the specified program string indicating where the first
program error was detected. If the program fails to load because of a semantic restriction that is not detected until the program is fully scanned, the
error position is set to the value of {@code len}. If a program loads successfully, the error position is set to the value negative one. The
implementation-dependent program error string contains one or more error or warning messages. If a program loads succesfully, the error string may
either contain warning messages or be empty.
""",
TARGET,
GLenum.IN("format", "the format of the program string", "#PROGRAM_FORMAT_ASCII_ARB"),
AutoSize("string")..GLsizei.IN("len", "the length of the program string, excluding the null-terminator"),
const..void_p.IN("string", "an array of bytes representing the program string being loaded")
)
void(
"BindProgramARB",
"""
Creates a named program object by binding an unused program object name to a valid program target. Also can be used to bind an existing program object
to a program target.
""",
TARGET,
GLuint.IN(
"program",
"""
the program object to bind. If {@code program} is zero, the default program object for {@code target} is bound. If {@code program} is the name of
an existing program object whose associated program target is {@code target}, the named program object is bound.
"""
)
)
void(
"DeleteProgramsARB",
"Deletes program objects.",
AutoSize("programs")..GLsizei.IN("n", "the number of program object to delete"),
const..GLuint_p.IN("programs", "an array of {@code n} program objects to be deleted")
)
void(
"GenProgramsARB",
"""
Returns {@code n} currently unused program names in {@code programs}. These names are marked as used, for the purposes of GenProgramsARB only, but
objects are created only when they are first bound using #BindProgramARB().
""",
AutoSize("programs")..GLsizei.IN("n", "the number of program names to genereate"),
ReturnParam..GLuint_p.OUT("programs", "an array in which to return the generated program names")
)
val VP_INDEX = GLuint.IN("index", "the environment parameter index")
val VP_X = "the {@code x} parameter component"
val VP_Y = "the {@code y} parameter component"
val VP_Z = "the {@code z} parameter component"
val VP_W = "the {@code w} parameter component"
val VP_V = "a buffer from which to read the parameter value"
void("ProgramEnvParameter4dARB", "Double version of #ProgramEnvParameter4fARB().", TARGET, VP_INDEX, GLdouble.IN("x", VP_X), GLdouble.IN("y", VP_Y), GLdouble.IN("z", VP_Z), GLdouble.IN("w", VP_W))
void("ProgramEnvParameter4dvARB", "Pointer version of #ProgramEnvParameter4dARB()", TARGET, VP_INDEX, Check(4)..const..GLdouble_p.IN("params", VP_V))
void(
"ProgramEnvParameter4fARB",
"Updates the values of the program environment parameter numbered {@code index} for the specified program target {@code target}.",
TARGET,
VP_INDEX,
GLfloat.IN("x", VP_X),
GLfloat.IN("y", VP_Y),
GLfloat.IN("z", VP_Z),
GLfloat.IN("w", VP_W)
)
void("ProgramEnvParameter4fvARB", "Pointer version of #ProgramEnvParameter4fARB().", TARGET, VP_INDEX, Check(4)..const..GLfloat_p.IN("params", VP_V))
void("ProgramLocalParameter4dARB", "Double version of #ProgramLocalParameter4fARB().", TARGET, VP_INDEX, GLdouble.IN("x", VP_X), GLdouble.IN("y", VP_Y), GLdouble.IN("z", VP_Z), GLdouble.IN("w", VP_W))
void("ProgramLocalParameter4dvARB", "Pointer version of #ProgramLocalParameter4dARB().", TARGET, VP_INDEX, Check(4)..const..GLdouble_p.IN("params", VP_V))
void(
"ProgramLocalParameter4fARB",
"Updates the values of the program local parameter numbered {@code index} for the specified program target {@code target}.",
TARGET,
VP_INDEX,
GLfloat.IN("x", VP_X),
GLfloat.IN("y", VP_Y),
GLfloat.IN("z", VP_Z),
GLfloat.IN("w", VP_W)
)
void("ProgramLocalParameter4fvARB", "Pointer version of #ProgramLocalParameter4fARB().", TARGET, VP_INDEX, Check(4)..const..GLfloat_p.IN("params", VP_V))
void(
"GetProgramEnvParameterfvARB",
"""
Obtain the current value for the program environment parameter numbered {@code index} for the specified program target {@code target}, and places the
information in the array {@code params}.
""",
TARGET,
VP_INDEX,
Check(4)..GLfloat_p.OUT("params", "a buffer in which to place the current parameter value")
)
void(
"GetProgramEnvParameterdvARB",
"Double version of #GetProgramEnvParameterfvARB().",
TARGET,
VP_INDEX,
Check(4)..GLdouble_p.OUT("params", "a buffer in which to place the current parameter value")
)
void(
"GetProgramLocalParameterfvARB",
"""
Obtain the current value for the program local parameter numbered {@code index} for the specified program target {@code target}, and places the
information in the array {@code params}.
""",
TARGET,
VP_INDEX,
Check(4)..GLfloat_p.OUT("params", "a buffer in which to place the current parameter value")
)
void(
"GetProgramLocalParameterdvARB",
"Double version of #GetProgramLocalParameterfvARB().",
TARGET,
VP_INDEX,
Check(4)..GLdouble_p.OUT("params", "a buffer in which to place the current parameter value")
)
void(
"GetProgramivARB",
"""
Obtains program state for the program target {@code target}, writing the state into the array given by {@code params}. GetProgramivARB can be used to
determine the properties of the currently bound program object or implementation limits for {@code target}.
""",
TARGET,
GLenum.IN("pname", "the parameter to query", PARAMS),
ReturnParam..Check(1)..GLint_p.OUT("params", "an array in which to place the parameter value")
)
void(
"GetProgramStringARB",
"""
Obtains the program string for the program object bound to {@code target} and places the information in the array {@code string}.
{@code n} ubytes are returned into the array program where {@code n} is the length of the program in ubytes, as returned by #GetProgramivARB() when
{@code pname} is #PROGRAM_LENGTH_ARB. The program string is always returned using the format given when the program string was specified.
""",
TARGET,
GLenum.IN("pname", "the parameter to query", "#PROGRAM_STRING_ARB"),
Check("glGetProgramiARB(target, GL_PROGRAM_LENGTH_ARB)", debug = true)..void_p.OUT("string", "an array in which to place the program string")
)
void(
"GetVertexAttribfvARB",
"""
Obtains the vertex attribute state named by {@code pname} for the vertex attribute numbered {@code index} and places the information in the array
{@code params}.
""",
VA_INDEX,
GLenum.IN("pname", "the parameter to query", "#CURRENT_VERTEX_ATTRIB_ARB"),
Check(4)..GLfloat_p.OUT("params", "an array in which to place the parameter value")
)
void(
"GetVertexAttribdvARB",
"Double version of #GetVertexAttribfvARB().",
VA_INDEX,
GLenum.IN("pname", "the parameter to query", "#CURRENT_VERTEX_ATTRIB_ARB"),
Check(4)..GLdouble_p.OUT("params", "an array in which to place the parameter value")
)
void(
"GetVertexAttribivARB",
"Integer version of #GetVertexAttribfvARB().",
VA_INDEX,
GLenum.IN(
"pname",
"the parameter to query",
"""
#VERTEX_ATTRIB_ARRAY_ENABLED_ARB #VERTEX_ATTRIB_ARRAY_SIZE_ARB #VERTEX_ATTRIB_ARRAY_STRIDE_ARB #VERTEX_ATTRIB_ARRAY_TYPE_ARB
#VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB #CURRENT_VERTEX_ATTRIB_ARB
"""
),
ReturnParam..Check(1)..GLint_p.OUT("params", "an array in which to place the parameter value")
)
void(
"GetVertexAttribPointervARB",
"Obtains the pointer named {@code pname} for vertex attribute numbered {@code index} and places the information in the array {@code pointer}.",
VA_INDEX,
GLenum.IN("pname", "the parameter to query", "#VERTEX_ATTRIB_ARRAY_POINTER_ARB"),
ReturnParam..Check(1)..void_pp.OUT("pointer", "an array in which to place the vertex attribute array pointer")
)
GLboolean(
"IsProgramARB",
"""
Returns GL11#TRUE if {@code program} is the name of a program object. If {@code program} is zero or is a non-zero value that is not the name of a
program object, or if an error condition occurs, IsProgramARB returns GL11#FALSE. A name returned by #GenProgramsARB(), but not yet bound, is not the
name of a program object.
""",
GLuint.IN("program", "the program name")
)
} | bsd-3-clause | 04ec105bea26ee7689ff280a1a7f5b08 | 43.186898 | 201 | 0.722309 | 3.271793 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/syncadapter/SyncInitiator.kt | 1 | 5511 | /*
* Copyright (C) 2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.syncadapter
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.PowerManager
import android.os.SystemClock
import org.andstatus.app.MyAction
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.os.NonUiThreadExecutor
import org.andstatus.app.service.ConnectionRequired
import org.andstatus.app.service.MyServiceManager
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.UriUtils
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Periodic syncing doesn't work reliably, when a device is in a Doze mode, so we need
* additional way(s) to check if syncing is needed.
*/
class SyncInitiator : BroadcastReceiver() {
// Testing Doze: https://developer.android.com/training/monitoring-device-state/doze-standby.html#testing_doze
override fun onReceive(context: Context, intent: Intent?) {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager ?
MyLog.v(this
) {
("onReceive "
+ if (pm == null || pm.isDeviceIdleMode) " idle" else " " + UriUtils.getConnectionState(context))
}
if (pm == null || pm.isDeviceIdleMode) return
initializeApp(context)
}
private fun initializeApp(context: Context) {
MyContextHolder.myContextHolder
.initialize(context, this)
.whenSuccessAsync({ myContext: MyContext -> checkConnectionState(myContext) }, NonUiThreadExecutor.INSTANCE)
}
private fun checkConnectionState(myContext: MyContext) {
if (!syncIfNeeded(myContext)) {
Timer().schedule(object : TimerTask() {
override fun run() {
syncIfNeeded(myContext)
}
}, getRandomDelayMillis(5))
}
}
private fun syncIfNeeded(myContext: MyContext): Boolean {
if (!MyServiceManager.isServiceAvailable()) {
MyLog.v(this) { "syncIfNeeded Service is unavailable" }
return false
}
val connectionState = UriUtils.getConnectionState(myContext.context)
MyLog.v(this) { "syncIfNeeded " + UriUtils.getConnectionState(myContext.context) }
if (!ConnectionRequired.SYNC.isConnectionStateOk(connectionState)) return false
for (myAccount in myContext.accounts.accountsToSync()) {
if (myContext.timelines.toAutoSyncForAccount(myAccount).isNotEmpty()) {
myAccount.requestSync()
}
}
return true
}
companion object {
private val BROADCAST_RECEIVER: SyncInitiator = SyncInitiator()
fun tryToSync(context: Context) {
BROADCAST_RECEIVER.initializeApp(context)
}
private fun getRandomDelayMillis(minSeconds: Int): Long {
return TimeUnit.SECONDS.toMillis((minSeconds + Random().nextInt(minSeconds * 4)).toLong())
}
fun register(myContext: MyContext) {
scheduleRepeatingAlarm(myContext)
registerBroadcastReceiver(myContext)
}
private fun scheduleRepeatingAlarm(myContext: MyContext) {
val minSyncIntervalMillis = myContext.accounts.minSyncIntervalMillis()
if (minSyncIntervalMillis > 0) {
val alarmManager = myContext.context.getSystemService(AlarmManager::class.java)
if (alarmManager == null) {
MyLog.w(SyncInitiator::class.java, "No AlarmManager ???")
return
}
val randomDelay = getRandomDelayMillis(30)
MyLog.d(SyncInitiator::class.java, "Scheduling repeating alarm in "
+ TimeUnit.MILLISECONDS.toSeconds(randomDelay) + " seconds")
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + randomDelay,
minSyncIntervalMillis,
PendingIntent.getBroadcast(myContext.context, 0, MyAction.SYNC.newIntent(), 0)
)
}
}
private fun registerBroadcastReceiver(myContext: MyContext?) {
if (myContext != null && myContext.accounts.hasSyncedAutomatically()) myContext.context
.registerReceiver(BROADCAST_RECEIVER, IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED))
}
fun unregister(myContext: MyContext?) {
try {
myContext?.context?.unregisterReceiver(BROADCAST_RECEIVER)
} catch (e: IllegalArgumentException) {
MyLog.ignored(BROADCAST_RECEIVER, e)
}
}
}
}
| apache-2.0 | ed58bf35503053f8b63fa834b04a35f8 | 40.126866 | 124 | 0.659046 | 4.859788 | false | false | false | false |
EventFahrplan/EventFahrplan | app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListViewModelFactory.kt | 1 | 1016 | package nerd.tuxmobil.fahrplan.congress.favorites
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import info.metadude.android.eventfahrplan.commons.logging.Logging
import nerd.tuxmobil.fahrplan.congress.repositories.AppExecutionContext
import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository
import nerd.tuxmobil.fahrplan.congress.sharing.JsonSessionFormat
import nerd.tuxmobil.fahrplan.congress.sharing.SimpleSessionFormat
class StarredListViewModelFactory(
private val appRepository: AppRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val logging = Logging.get()
@Suppress("UNCHECKED_CAST")
return StarredListViewModel(
repository = appRepository,
executionContext = AppExecutionContext,
logging = logging,
simpleSessionFormat = SimpleSessionFormat(),
jsonSessionFormat = JsonSessionFormat()
) as T
}
}
| apache-2.0 | c87663ef2539a6b13973f69199250245 | 34.034483 | 71 | 0.754921 | 5.054726 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | base/src/main/kotlin/com/commonsense/android/kotlin/base/extensions/IntExtensions.kt | 1 | 1302 | @file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.base.extensions
import com.commonsense.android.kotlin.base.algorithms.*
import kotlin.math.*
/**
* Created by Kasper Tvede on 13-09-2017.
*/
/**
* Gets this int negative, if it is already negative, returns that.
*/
inline val Int.negative: Int
get() = minOf(this, -this)
/**
* if this int is not 0 => returns true. false otherwise
*/
inline val Int.isNotZero: Boolean
get() = !isZero
/**
* if this int is 0 => returns true. false otherwise
*/
inline val Int.isZero: Boolean
get() = this == 0
/**
*
*/
inline val Int.isEven: Boolean
get() = abs(this % 2) == 0
/**
*
*/
inline val Int.isOdd: Boolean
get() = !isEven
/**
* tells if we are in a range, or above / below it (equal => in range).
* @receiver Int
* @param from Int from this value (inclusive)
* @param to Int to this value (inclusive)
* @return Comparing
*/
inline fun Int.compareToRange(from: Int, to: Int): Comparing {
//make it a bit more "defined" behavior.
if (from > to) {
return Comparing.LessThan
}
return when {
this in (from..to) -> Comparing.Equal
this > to -> Comparing.LargerThan
else -> Comparing.LessThan
}
}
| mit | 9943219a1ea6ab42c80b4597293ddd06 | 20.344262 | 77 | 0.640553 | 3.557377 | false | false | false | false |
nick-ellis/Totems | app/src/main/java/me/nickellis/towers/sample/adapter/SimpleRecyclerAdapter.kt | 1 | 1696 | package me.nickellis.towers.sample.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import me.nickellis.towers.sample.ktx.isValidIndexOf
import kotlin.math.min
abstract class SimpleRecyclerAdapter<T>(
private val context: Context,
@LayoutRes private val itemLayout: Int,
items: Collection<T>
) : RecyclerView.Adapter<SimpleViewHolder>() {
private val items: MutableList<T> = items.toMutableList()
init {
notifyDataSetChanged()
}
abstract fun onBind(item: T, holder: SimpleViewHolder, position: Int)
fun remove(item: T): Boolean {
return removeItemAt(items.indexOfFirst { it == item })
}
fun removeItemAt(index: Int): Boolean {
if (index.isValidIndexOf(items)) {
items.removeAt(index)
notifyItemRemoved(index)
return true
}
return false
}
fun add(item: T): SimpleRecyclerAdapter<T> {
return addItemAt(items.size, item)
}
fun addItemAt(index: Int, item: T): SimpleRecyclerAdapter<T> {
val adjusted = min(items.size, index)
items.add(adjusted, item)
notifyItemInserted(adjusted)
return this
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder {
val view = LayoutInflater.from(context).inflate(itemLayout, null, false)
return SimpleViewHolder(view)
}
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: SimpleViewHolder, position: Int) {
onBind(items[position], holder, position)
}
}
class SimpleViewHolder(v: View) : RecyclerView.ViewHolder(v) | apache-2.0 | 8f2c7fa0e1ca88c39fcb6409b673de97 | 25.936508 | 87 | 0.738797 | 4.167076 | false | false | false | false |
wolfbeacon/wolfbeacon-hackalist-api | src/main/kotlin/wolfbeacon/hackalist/util/CoordinateComparator.kt | 1 | 1480 | package wolfbeacon.hackalist.util
import wolfbeacon.hackalist.HackalistHackathon
import java.util.*
class CoordinateComparator(private val lat1: Double, private val lon1: Double) : Comparator<HackalistHackathon> {
private val memoDistances: MutableMap<Long, Double?>
init {
memoDistances = HashMap()
}
override fun compare(h1: HackalistHackathon, h2: HackalistHackathon): Int {
if (!memoDistances.containsKey(h1.id)) {
memoDistances.put(h1.id, distance(h1.latitude, h1.longitude))
}
if (!memoDistances.containsKey(h2.id)) {
memoDistances.put(h2.id, distance(h2.latitude, h2.longitude))
}
return memoDistances[h1.id]!!.compareTo(memoDistances[h2.id]!!)
}
//Refer to http://www.geodatasource.com/
private fun distance(lat2: Double?, lon2: Double?): Double {
if (lat2 == null || lon2 == null) {
return Integer.MAX_VALUE.toDouble()
}
val theta = lon1 - lon2
var dist: Double? = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta))
dist = Math.acos(dist!!)
dist = rad2deg(dist)
dist *= 60.0 * 1.1515
dist *= 1.609344
return dist
}
private fun deg2rad(deg: Double): Double {
return deg * Math.PI / 180.0
}
private fun rad2deg(rad: Double): Double {
return rad * 180 / Math.PI
}
} | gpl-3.0 | 959e6deabcdeb08a28dbdd7f06b87409 | 29.854167 | 156 | 0.622297 | 3.410138 | false | false | false | false |
ligee/kotlin-jupyter | jupyter-lib/shared-compiler/src/main/kotlin/org/jetbrains/kotlinx/jupyter/libraries/LibraryResolutionInfoParser.kt | 1 | 2762 | package org.jetbrains.kotlinx.jupyter.libraries
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionInfo
import org.jetbrains.kotlinx.jupyter.api.libraries.Variable
import org.jetbrains.kotlinx.jupyter.exceptions.ReplLibraryLoadingException
import kotlin.script.experimental.api.ResultWithDiagnostics
import kotlin.script.experimental.api.asSuccess
abstract class LibraryResolutionInfoParser(val name: String, private val parameters: List<Parameter>) {
fun getInfo(args: List<Variable>): LibraryResolutionInfo {
val map = when (val mapResult = substituteArguments(parameters, args)) {
is ResultWithDiagnostics.Success -> mapResult.value
is ResultWithDiagnostics.Failure -> throw ReplLibraryLoadingException(name, mapResult.reports.firstOrNull()?.message)
}
return getInfo(map)
}
abstract fun getInfo(args: Map<String, String>): LibraryResolutionInfo
companion object {
fun make(name: String, parameters: List<Parameter>, getInfo: (Map<String, String>) -> LibraryResolutionInfo): LibraryResolutionInfoParser {
return object : LibraryResolutionInfoParser(name, parameters) {
override fun getInfo(args: Map<String, String>): LibraryResolutionInfo = getInfo(args)
}
}
private fun substituteArguments(parameters: List<Parameter>, arguments: List<Variable>): ResultWithDiagnostics<Map<String, String>> {
val result = mutableMapOf<String, String>()
val possibleParamsNames = parameters.map { it.name }.toHashSet()
var argIndex = 0
for (arg in arguments) {
val param = parameters.getOrNull(argIndex)
?: return diagFailure("Too many arguments for library resolution info: ${arguments.size} got, ${parameters.size} allowed")
if (arg.name.isNotEmpty()) break
result[param.name] = arg.value
argIndex++
}
for (i in argIndex until arguments.size) {
val arg = arguments[i]
if (arg.name.isEmpty()) return diagFailure("Positional arguments in library resolution info shouldn't appear after keyword ones")
if (arg.name !in possibleParamsNames) return diagFailure("There is no such argument: ${arg.name}")
result[arg.name] = arg.value
}
parameters.forEach {
if (!result.containsKey(it.name)) {
if (it is Parameter.Optional) result[it.name] = it.default
else return diagFailure("Parameter ${it.name} is required, but was not specified")
}
}
return result.asSuccess()
}
}
}
| apache-2.0 | c67b474dd58ece92c4fb6a02b360f821 | 44.278689 | 147 | 0.652426 | 4.932143 | false | false | false | false |
saki4510t/libcommon | common/src/main/java/com/serenegiant/widget/MultiDispatchTouchFrameLayout.kt | 1 | 3639 | package com.serenegiant.widget
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.util.SparseBooleanArray
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.FrameLayout
/**
* 通常はViewヒエラルキーの上から順にenableでfocusableなViewの
* dispatchTouchEventを呼び出して最初にtrueを返した子Viewのみが
* イベント処理を行なえるのに対して、重なり合った複数のViewの下側も
* 含めてタッチした位置に存在するViewに対してdispatchTouchEventの
* 呼び出し処理を行うViewGroup
* (同じタッチイベントで複数の子Viewへタッチイベント生成&操作できる)
*/
open class MultiDispatchTouchFrameLayout
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: FrameLayout(context, attrs, defStyleAttr) {
private val mDispatched = SparseBooleanArray()
private val mWorkRect = Rect()
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
return if (onFilterTouchEventForSecurity(ev)) {
var result = false
val children = childCount
for (i in 0 until children) {
val v = getChildAt(i)
val id = v.hashCode()
v.getHitRect(mWorkRect)
if (v.isEnabled && isFocusable
&& mWorkRect.contains(ev.x.toInt(), ev.y.toInt())
&& mDispatched[id, true]) {
// 子Viewが有効&子ViewのhitRect内をタッチ&子Viewがイベントをハンドリングしているとき
// 子Viewのローカル座標系への変換してから子ViewのdispatchTouchEventを呼び出す
val offsetX: Float = scrollX - v.left.toFloat()
val offsetY: Float = scrollY - v.top.toFloat()
ev.offsetLocation(offsetX, offsetY)
val dispatched = v.dispatchTouchEvent(ev)
mDispatched.put(id, dispatched)
result = result or dispatched
// オフセットを元に戻す
ev.offsetLocation(-offsetX, -offsetY)
}
}
val action = ev.actionMasked
if ((!result
|| (action == MotionEvent.ACTION_UP)
|| (action == MotionEvent.ACTION_CANCEL))
&& ev.pointerCount == 1) {
mDispatched.clear()
}
// if (!result) {
// // 子Viewがどれもイベントをハンドリングしなかったときは上位に任せる
// // もしかすると子ViewのdispatchTouchEventが2回呼び出されるかも
// result = super.dispatchTouchEvent(ev)
// }
if (DEBUG) Log.v(TAG, "dispatchTouchEvent:result=$result")
result
} else {
mDispatched.clear()
super.dispatchTouchEvent(ev)
}
}
companion object {
private const val DEBUG = false // set false on production
private val TAG = MultiDispatchTouchFrameLayout::class.java.simpleName
}
init {
// 子クラスへフォーカスを与えないようにする
descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
isFocusable = true
}
} | apache-2.0 | 229d3994ffd046a6053871bd1cd29dc1 | 29.647059 | 83 | 0.73056 | 3.201844 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/receivers/TaskReceiver.kt | 1 | 4308 | package com.habitrpg.android.habitica.receivers
import android.app.Notification
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.extensions.withImmutableFlag
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.helpers.TaskAlarmManager
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.shared.habitica.models.tasks.TaskType
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.shared.habitica.HLogger
import com.habitrpg.shared.habitica.LogLevel
import io.reactivex.rxjava3.functions.Consumer
import javax.inject.Inject
class TaskReceiver : BroadcastReceiver() {
@Inject
lateinit var taskAlarmManager: TaskAlarmManager
@Inject
lateinit var taskRepository: TaskRepository
override fun onReceive(context: Context, intent: Intent) {
HLogger.log(LogLevel.INFO, this::javaClass.name, "onReceive")
HabiticaBaseApplication.userComponent?.inject(this)
val extras = intent.extras
if (extras != null) {
val taskId = extras.getString(TaskAlarmManager.TASK_ID_INTENT_KEY)
// This will set up the next reminders for dailies
if (taskId != null) {
taskAlarmManager.addAlarmForTaskId(taskId)
}
taskRepository.getTask(taskId ?: "")
.firstElement()
.subscribe(
Consumer {
if (it.isUpdatedToday && it.completed) {
return@Consumer
}
createNotification(context, it)
},
ExceptionHandler.rx()
)
}
}
private fun createNotification(context: Context, task: Task) {
val intent = Intent(context, MainActivity::class.java)
HLogger.log(LogLevel.INFO, this::javaClass.name, "Create Notification")
intent.putExtra("notificationIdentifier", "task_reminder")
val pendingIntent = PendingIntent.getActivity(context, System.currentTimeMillis().toInt(), intent, withImmutableFlag(0))
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
var notificationBuilder = NotificationCompat.Builder(context, "default")
.setSmallIcon(R.drawable.ic_gryphon_white)
.setContentTitle(task.text)
.setStyle(
NotificationCompat.BigTextStyle()
.bigText(task.notes)
)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setSound(soundUri)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
notificationBuilder = notificationBuilder.setCategory(Notification.CATEGORY_REMINDER)
}
if (task.type == TaskType.DAILY || task.type == TaskType.TODO) {
val completeIntent = Intent(context, LocalNotificationActionReceiver::class.java).apply {
action = context.getString(R.string.complete_task_action)
putExtra("taskID", task.id)
putExtra("NOTIFICATION_ID", task.id.hashCode())
}
val pendingIntentComplete = PendingIntent.getBroadcast(
context,
task.id.hashCode(),
completeIntent,
withImmutableFlag(PendingIntent.FLAG_UPDATE_CURRENT)
)
notificationBuilder.addAction(0, context.getString(R.string.complete), pendingIntentComplete)
}
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(task.id.hashCode(), notificationBuilder.build())
}
}
| gpl-3.0 | f17119cf04b48c9e6613cbb33f0dbfb6 | 40.653465 | 128 | 0.656685 | 5.068235 | false | false | false | false |
mitallast/netty-queue | src/main/java/org/mitallast/queue/common/events/DefaultEventBus.kt | 1 | 2329 | package org.mitallast.queue.common.events
import io.vavr.collection.HashMultimap
import io.vavr.collection.Multimap
import java.util.concurrent.Executor
import java.util.concurrent.locks.ReentrantLock
@Suppress("UNCHECKED_CAST")
class DefaultEventBus : EventBus {
private val lock = ReentrantLock()
@Volatile private var consumers: Multimap<Class<*>, Listener<(Any) -> Unit>> = HashMultimap.withSet<Any>().empty()
override fun <Event : Any> subscribe(eventClass: Class<Event>, consumer: (Event) -> Unit) {
lock.lock()
try {
consumers = consumers.put(eventClass, Listener(consumer) as Listener<(Any) -> Unit>)
} finally {
lock.unlock()
}
}
override fun <Event : Any> subscribe(eventClass: Class<Event>, consumer: (Event) -> Unit, executor: Executor) {
lock.lock()
try {
consumers = consumers.put(eventClass, Listener(consumer, executor) as Listener<(Any) -> Unit>)
} finally {
lock.unlock()
}
}
override fun <Event : Any> unsubscribe(eventClass: Class<Event>, consumer: (Event) -> Unit) {
lock.lock()
try {
consumers = consumers.remove(eventClass, Listener(consumer) as Listener<(Any) -> Unit>)
} finally {
lock.unlock()
}
}
override fun <Event : Any> trigger(event: Event) {
consumers.get(event.javaClass).forEach { listeners ->
listeners.forEach { listener ->
(listener as Listener<Event>).accept(event)
}
}
}
private class Listener<in Event : Any> constructor(
private val consumer: (Event) -> Unit,
private val executor: Executor? = null) {
fun accept(event: Event) {
if (executor == null) {
consumer.invoke(event)
} else {
executor.execute { consumer.invoke(event) }
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Listener<*>
if (consumer != other.consumer) return false
return true
}
override fun hashCode(): Int {
return consumer.hashCode()
}
}
}
| mit | ddcb41e07e0f5d2b630a45834919fe42 | 31.347222 | 118 | 0.578789 | 4.548828 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Authentication.kt | 1 | 1662 | package com.habitrpg.android.habitica.models.user
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.models.BaseObject
import com.habitrpg.android.habitica.models.auth.LocalAuthentication
import com.habitrpg.android.habitica.models.user.auth.SocialAuthentication
import com.habitrpg.shared.habitica.models.AvatarAuthentication
import io.realm.RealmObject
import io.realm.annotations.RealmClass
@RealmClass(embedded = true)
open class Authentication : RealmObject(), BaseObject, AvatarAuthentication {
fun findFirstSocialEmail(): String? {
for (auth in listOf(googleAuthentication, appleAuthentication, facebookAuthentication)) {
if (auth?.emails?.isNotEmpty() == true) {
return auth.emails.first()
}
}
return null
}
val hasPassword: Boolean
get() = localAuthentication?.hasPassword == true
@SerializedName("local")
override var localAuthentication: LocalAuthentication? = null
@SerializedName("google")
var googleAuthentication: SocialAuthentication? = null
@SerializedName("apple")
var appleAuthentication: SocialAuthentication? = null
@SerializedName("facebook")
var facebookAuthentication: SocialAuthentication? = null
val hasGoogleAuth: Boolean
get() = googleAuthentication?.emails?.isEmpty() != true
val hasAppleAuth: Boolean
get() = appleAuthentication?.emails?.isEmpty() != true
val hasFacebookAuth: Boolean
get() = facebookAuthentication?.emails?.isEmpty() != true
var timestamps: AuthenticationTimestamps? = null
}
| gpl-3.0 | 9a503e87b2ec86761350ef836b01ac51 | 38.536585 | 97 | 0.716005 | 4.902655 | false | false | false | false |
CzBiX/klog | src/main/kotlin/com/czbix/klog/ServerBootstrap.kt | 1 | 2071 | package com.czbix.klog
import com.czbix.klog.http.core.HttpServerHandler
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.http.HttpContentCompressor
import io.netty.handler.codec.http.HttpObjectAggregator
import io.netty.handler.codec.http.HttpServerCodec
import org.apache.logging.log4j.LogManager
import java.io.Closeable
import io.netty.bootstrap.ServerBootstrap as NettyBootstrap
class ServerBootstrap : Closeable {
companion object {
private val logger = LogManager.getLogger(ServerBootstrap::class.java)
}
private val port = 8000
private val bossGroup = NioEventLoopGroup()
private val workerGroup = NioEventLoopGroup()
private lateinit var bootstrap: NettyBootstrap
init {
bootstrap = NettyBootstrap().apply {
localAddress(port)
group(bossGroup, workerGroup)
channel(NioServerSocketChannel::class.java)
option(ChannelOption.TCP_NODELAY, true)
childOption(ChannelOption.SO_KEEPALIVE, true)
childHandler(ServerInitializer())
}
}
fun run() {
use {
val f = bootstrap.bind().sync()
if (f.isSuccess) {
logger.info("Server listening on {}", port)
}
f.channel().closeFuture().sync()
}
}
override fun close() {
bossGroup.shutdownGracefully()
workerGroup.shutdownGracefully()
}
class ServerInitializer : ChannelInitializer<SocketChannel>() {
override fun initChannel(ch: SocketChannel) {
ch.pipeline().apply {
addLast("http", HttpServerCodec())
addLast("compressor", HttpContentCompressor())
addLast("aggregator", HttpObjectAggregator(1024 * 1024))
addLast("http_server", HttpServerHandler())
}
}
}
}
| apache-2.0 | e6e6ec25650143d311edda0871651d11 | 30.861538 | 78 | 0.666828 | 4.850117 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/media/src/test/kotlin/app/ss/media/playback/ui/video/VideoListScreenTest.kt | 1 | 3111 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.media.playback.ui.video
import app.cash.paparazzi.DeviceConfig
import app.cash.paparazzi.Paparazzi
import app.ss.design.compose.extensions.surface.ThemeSurface
import app.ss.models.media.SSVideosInfo
import com.cryart.sabbathschool.test.di.MockModule
import com.cryart.sabbathschool.test.di.mock.QuarterlyMockData
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
@Ignore("Target sdk 33")
class VideoListScreenTest {
@get:Rule
val paparazzi = Paparazzi(
deviceConfig = DeviceConfig.PIXEL_5
)
private lateinit var mockData: QuarterlyMockData
@Before
fun setup() {
mockData = MockModule.provideQuarterlyMockData(
context = paparazzi.context
)
}
@Test
fun video_list_grouped() = launch(
lessonIndex = "en-2022-02-13",
fileName = "videos.json"
)
@Test
fun video_list_grouped_dark() = launch(
lessonIndex = "en-2022-02-13",
fileName = "videos.json",
darkTheme = true
)
@Test
fun video_list_single() = launch(
lessonIndex = "en-2022-02-cq-13",
fileName = "videos_cq.json"
)
@Test
fun video_list_single_dark() = launch(
lessonIndex = "en-2022-02-cq-13",
fileName = "videos_cq.json",
darkTheme = true
)
private fun launch(
lessonIndex: String,
fileName: String,
darkTheme: Boolean = false
) {
val videos = mockData.getVideos(fileName).mapIndexed { index, model ->
SSVideosInfo(
id = "$lessonIndex-$index",
artist = model.artist,
clips = model.clips,
lessonIndex = lessonIndex
)
}
val data = videos.toData(lessonIndex)
paparazzi.snapshot {
ThemeSurface(darkTheme = darkTheme) {
VideoListScreen(videoList = data)
}
}
}
}
| mit | b89cc25a4c018e970ab530ee55864637 | 30.11 | 80 | 0.664417 | 4.27923 | false | true | false | false |
k9mail/k-9 | mail/common/src/main/java/com/fsck/k9/mail/helper/Utf8.kt | 2 | 4722 | /*
* These functions are based on Okio's UTF-8 code.
*
* Copyright (C) 2018 The K-9 Dog Walkers
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fsck.k9.mail.helper
/**
* Encodes this string using UTF-8.
*/
inline fun String.encodeUtf8(beginIndex: Int = 0, endIndex: Int = length, crossinline writeByte: (Byte) -> Unit) {
require(beginIndex >= 0) { "beginIndex < 0: $beginIndex" }
require(endIndex >= beginIndex) { "endIndex < beginIndex: $endIndex < $beginIndex" }
require(endIndex <= length) { "endIndex > length: $endIndex > $length" }
// Transcode a UTF-16 Java String to UTF-8 bytes.
var i = beginIndex
while (i < endIndex) {
val c = this[i].code
if (c < 0x80) {
// Emit a 7-bit character with 1 byte.
writeByte(c.toByte()) // 0xxxxxxx
i++
} else if (c < 0x800) {
// Emit a 11-bit character with 2 bytes.
writeByte((c shr 6 or 0xc0).toByte()) // 110xxxxx
writeByte((c and 0x3f or 0x80).toByte()) // 10xxxxxx
i++
} else if (c < 0xd800 || c > 0xdfff) {
// Emit a 16-bit character with 3 bytes.
writeByte((c shr 12 or 0xe0).toByte()) // 1110xxxx
writeByte((c shr 6 and 0x3f or 0x80).toByte()) // 10xxxxxx
writeByte((c and 0x3f or 0x80).toByte()) // 10xxxxxx
i++
} else {
// c is a surrogate. Make sure it is a high surrogate and that its successor is a low surrogate.
// If not, the UTF-16 is invalid, in which case we emit a replacement character.
val low = if (i + 1 < endIndex) this[i + 1].code else 0
if (c > 0xdbff || low < 0xdc00 || low > 0xdfff) {
writeByte('?'.code.toByte())
i++
continue
}
// UTF-16 high surrogate: 110110xxxxxxxxxx (10 bits)
// UTF-16 low surrogate: 110111yyyyyyyyyy (10 bits)
// Unicode code point: 00010000000000000000 + xxxxxxxxxxyyyyyyyyyy (21 bits)
val codePoint = 0x010000 + (c and 0xd800.inv() shl 10 or (low and 0xdc00.inv()))
// Emit a 21-bit character with 4 bytes.
writeByte((codePoint shr 18 or 0xf0).toByte()) // 11110xxx
writeByte((codePoint shr 12 and 0x3f or 0x80).toByte()) // 10xxxxxx
writeByte((codePoint shr 6 and 0x3f or 0x80).toByte()) // 10xxyyyy
writeByte((codePoint and 0x3f or 0x80).toByte()) // 10yyyyyy
i += 2
}
}
}
/**
* Returns the number of bytes used to encode `string` as UTF-8 when using [Int.encodeUtf8].
*/
fun Int.utf8Size(): Int {
return when {
this < 0x80 -> 1
this < 0x800 -> 2
this < 0xd800 -> 3
this < 0xe000 -> 1
this < 0x10000 -> 3
else -> 4
}
}
/**
* Encodes this code point using UTF-8.
*/
inline fun Int.encodeUtf8(crossinline writeByte: (Byte) -> Unit) {
val codePoint = this
if (codePoint < 0x80) {
// Emit a 7-bit character with 1 byte.
writeByte(codePoint.toByte()) // 0xxxxxxx
} else if (codePoint < 0x800) {
// Emit a 11-bit character with 2 bytes.
writeByte((codePoint shr 6 or 0xc0).toByte()) // 110xxxxx
writeByte((codePoint and 0x3f or 0x80).toByte()) // 10xxxxxx
} else if (codePoint < 0xd800 || codePoint in 0xe000..0x10000) {
// Emit a 16-bit character with 3 bytes.
writeByte((codePoint shr 12 or 0xe0).toByte()) // 1110xxxx
writeByte((codePoint shr 6 and 0x3f or 0x80).toByte()) // 10xxxxxx
writeByte((codePoint and 0x3f or 0x80).toByte()) // 10xxxxxx
} else if (codePoint in 0xd800..0xdfff) {
// codePoint is a surrogate. Emit a replacement character
writeByte('?'.code.toByte())
} else {
// Emit a 21-bit character with 4 bytes.
writeByte((codePoint shr 18 or 0xf0).toByte()) // 11110xxx
writeByte((codePoint shr 12 and 0x3f or 0x80).toByte()) // 10xxxxxx
writeByte((codePoint shr 6 and 0x3f or 0x80).toByte()) // 10xxyyyy
writeByte((codePoint and 0x3f or 0x80).toByte()) // 10yyyyyy
}
}
| apache-2.0 | 647bc17ada86561efe38484f6cc3ab25 | 40.06087 | 114 | 0.598263 | 3.750596 | false | false | false | false |
mightyfrog/Settings-Shortcutter | app/src/main/java/org/mightyfrog/android/settingsshortcutter/ItemAdapter.kt | 1 | 8158 | package org.mightyfrog.android.settingsshortcutter
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.wifi.WifiNetworkSuggestion
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.mightyfrog.android.settingsshortcutter.databinding.VhItemBinding
import java.io.InputStreamReader
/**
* @author Shigehiro Soejima
*/
class ItemAdapter(
private val fragmentManager: FragmentManager,
private val context: Context,
) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {
private val list: List<Item>
init {
val tt = object : TypeToken<List<Item>>() {}.type
list = Gson().fromJson(InputStreamReader(context.resources.openRawResource(R.raw.data)), tt)
list.sortedBy {
it.name
}
}
override fun getItemCount() = list.size
@TargetApi(26)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val binding = VhItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ItemViewHolder(binding)
}
@RequiresApi(33)
override fun onBindViewHolder(vh: ItemViewHolder, position: Int) {
val item = list[position]
vh.bind(item)
vh.itemView.setOnClickListener {
item.api?.let { api ->
if (api <= Build.VERSION.SDK_INT) {
sendIntent(item.constant)
} else {
Toast.makeText(
context,
context.getString(R.string.unsupported, api),
Toast.LENGTH_SHORT
).show()
}
}
}
}
@RequiresApi(33)
@SuppressLint("BatteryLife")
@TargetApi(26)
private fun sendIntent(action: String?) {
action ?: return
val intent = Intent()
intent.action = action
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
when (action) {
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS,
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
Settings.ACTION_MANAGE_WRITE_SETTINGS,
Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE,
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
Settings.ACTION_APP_LOCALE_SETTINGS,
Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS,
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
-> {
val bundle = Bundle().apply {
putString("action", action)
}
PackageChooserDialog.newInstance(bundle)
.show(fragmentManager, PackageChooserDialog::class.java.simpleName)
return
}
Settings.ACTION_APP_USAGE_SETTINGS -> {
val bundle = Bundle().apply {
putString("action", action)
putBoolean("extraPackageName", true)
}
PackageChooserDialog.newInstance(bundle)
.show(fragmentManager, PackageChooserDialog::class.java.simpleName)
return
}
Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS -> {
val adb = Settings.Secure.getInt(
context.contentResolver,
Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
0
)
if (adb != 1) {
Toast.makeText(
context,
"Developer options are not enabled",
Toast.LENGTH_SHORT
).show()
return
}
}
Settings.ACTION_APP_NOTIFICATION_SETTINGS -> {
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
intent.putExtra(
Settings.EXTRA_CHANNEL_ID,
"test_id_1"
) // optional, not working as of Android O DP3
}
Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS -> {
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
intent.putExtra(Settings.EXTRA_CHANNEL_ID, "test_id_1")
}
Settings.ACTION_ADD_ACCOUNT -> {
// https://developers.google.com/android/reference/com/google/android/gms/auth/GoogleAuthUtil.html#GOOGLE_ACCOUNT_TYPE
// intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, arrayOf("com.google"))
}
Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS -> {
intent.putExtra(
Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME,
ComponentName(
context.packageName,
DummyNotificationListener::class.java.name
).flattenToString()
)
}
Settings.ACTION_PROCESS_WIFI_EASY_CONNECT_URI -> {
intent.data = Uri.parse(VALID_WIFI_DPP_QR_CODE)
}
Settings.ACTION_WIFI_ADD_NETWORKS -> { // TODO: fix me
val list = arrayListOf(
WifiNetworkSuggestion.Builder()
.setSsid("test111111")
.build(),
WifiNetworkSuggestion.Builder()
.setSsid("test222222")
.setWpa2Passphrase("test123456")
.build()
)
intent.putParcelableArrayListExtra(Settings.EXTRA_WIFI_NETWORK_LIST, list)
try {
ActivityCompat.startActivityForResult(
context as Activity,
intent,
1,
null
)
} catch (t: Throwable) {
Toast.makeText(context, t.message, Toast.LENGTH_SHORT).show()
}
return
}
Settings.ACTION_VOICE_CONTROL_AIRPLANE_MODE,
Settings.ACTION_SETTINGS_EMBED_DEEP_LINK_ACTIVITY,
Settings.ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE,
Settings.ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE,
Settings.ACTION_MANAGE_SUPERVISOR_RESTRICTED_SETTING,
-> {
Toast.makeText(context, "not implemented", Toast.LENGTH_SHORT).show()
return
}
}
try {
ContextCompat.startActivity(context, intent, null)
} catch (t: Throwable) {
Toast.makeText(context, t.message, Toast.LENGTH_SHORT).show()
}
}
class ItemViewHolder(private val binding: VhItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: Item) {
binding.apply {
name.text = name.context.getString(R.string.name_and_api, item.name, item.api)
desc.text = item.action
}
}
}
companion object {
// https://github.com/AOSP-10/packages_apps_Settings/blob/7e28298e599841790c13bb049ac9aa38291a3b3a/tests/unit/src/com/android/settings/wifi/dpp/WifiDppConfiguratorActivityTest.java
private const val VALID_WIFI_DPP_QR_CODE = ("DPP:I:SN=4774LH2b4044;M:010203040506;K:"
+ "MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;")
}
}
| apache-2.0 | 74385a788fe6131b59c9b508dcc247e1 | 38.410628 | 188 | 0.57698 | 4.801648 | false | false | false | false |
nearbydelta/KoreanAnalyzer | khaiii/src/test/kotlin/kr/bydelta/koala/test/tests.kt | 1 | 2801 | package kr.bydelta.koala.test
import com.sun.jna.NativeLibrary
import com.sun.jna.Platform
import kr.bydelta.koala.Conversion
import kr.bydelta.koala.POS
import kr.bydelta.koala.TagConversionSpek
import kr.bydelta.koala.TaggerSpek
import kr.bydelta.koala.khaiii.*
import org.spekframework.spek2.Spek
val KHAIII_RSC: String by lazy {
NativeLibrary.addSearchPath(if (Platform.isMac()) "libkhaiii.dylib" else "libkhaiii.so", System.getenv("KHAIII_LIB") ?: "")
println("Add path to libkhaiii: ${System.getenv("KHAIII_LIB")}")
val rsc = System.getenv("KHAIII_RSC") ?: ""
println("Set KHAIII_RSC = $rsc")
rsc
}
object KhaiiiTaggerTest : Spek(TaggerSpek(getTagger = { Tagger(KHAIII_RSC) },
tagSentByOrig = {
val khaiii = Khaiii(KHAIII_RSC)
val original = khaiii.analyze(it)
getOriginalTaggerOutput(original, it)
}, tagParaByOrig = { emptyList() },
tagSentByKoala = { str, tagger ->
val tagged = tagger.tagSentence(str)
val tag = tagged.joinToString(" ") { w -> w.joinToString("+") { "${it.surface}/${it.originalTag}" } }
tagged.surfaceString() to tag
}, isSentenceSplitterImplemented = true))
private fun getOriginalTaggerOutput(original: KhaiiiWord?, it: String): Pair<String, String> {
val alignments = it.byteAlignment()
val tag = StringBuffer()
val surface = StringBuffer()
var word = original
while (word != null) {
val alignBegin = word.begin ?: 0
val alignLength = word.length ?: 1
val begin = alignments[alignBegin]
val end = alignments[maxOf(alignBegin + alignLength - 1, 0)] + 1
surface.append(it.substring(begin, end))
var morph = word.morphs
while (morph != null) {
val morphSurface = morph.lex
val oTag = morph.tag
tag.append("$morphSurface/$oTag")
if (morph.next != null) {
tag.append('+')
}
morph = morph.next
}
if (word.next != null) {
surface.append(' ')
tag.append(' ')
}
word = word.next
}
return Pair(surface.toString(), tag.toString())
}
object KhaiiiTagConversionTest : Spek(TagConversionSpek(from = { it.toSejongPOS() },
to = { it.fromSejongPOS() },
getMapping = {
when (it) {
POS.NA -> listOf(Conversion("ZZ"))
POS.NV -> listOf(Conversion("ZV"))
POS.NF -> listOf(Conversion("ZN"))
POS.SW -> listOf(Conversion("SW"), Conversion("SWK", toTagger = false))
POS.XPV, POS.XSM, POS.XSO -> listOf(Conversion("ZZ", toSejong = false))
else -> listOf(Conversion(it.toString()))
}
}))
| gpl-3.0 | 0f67222b4638abe1814101b0922d06dc | 32.746988 | 127 | 0.589432 | 3.690382 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/deeplearning/birnn/BiRNNUtilsSpec.kt | 1 | 3429 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package deeplearning.birnn
import com.kotlinnlp.simplednn.deeplearning.birnn.BiRNNUtils
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
*
*/
class BiRNNUtilsSpec : Spek({
describe("a BiRNNUtils") {
val array1 = listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.8, 0.8, -1.0, -0.7)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.7, -0.8, 0.2, -0.7, 0.7)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.9, 0.9, 0.7, -0.5, 0.5)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, -0.1, 0.5, -0.2, -0.8)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.6, 0.6, 0.8, -0.1, -0.3)))
val array2 = listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, -0.6, -1.0, -0.1, -0.4)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, -0.9, 0.0, 0.8, 0.3)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.3, -0.9, 0.3, 1.0, -0.2)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, 0.2, 0.3, -0.4, -0.6)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.2, 0.5, -0.2, -0.9, 0.4)))
context("sumBidirectionalErrors") {
val result: List<DenseNDArray> = BiRNNUtils.sumBidirectionalErrors(array1, array2)
val expectedResult = listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.2, 1.3, 0.6, -1.9, -0.3)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, -0.6, 0.5, -1.1, 0.1)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(-1.2, 0.0, 1.0, 0.5, 0.3)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, -1.0, 0.5, 0.6, -0.5)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.5, 0.0, -0.2, -0.2, -0.7))
)
it("should return an array of the expected size") {
assertEquals(expectedResult.size, result.size)
}
it("should return an array with elements of the expected shape") {
assertTrue { result.all{ it.shape == Shape(5, 1) } }
}
it("should return an array with elements of same shape of the expected values") {
assertTrue { expectedResult.zip(result).all { (a, b) -> a.shape == b.shape } }
}
it("should return the pre-calculated values") {
assertEquals(expectedResult, result)
}
}
context("splitErrors") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.8, 0.8, -1.0, -0.7, 0.1, -0.6, -1.0, -0.1, -0.4))
val (result1, result2) = BiRNNUtils.splitErrors(array)
val expectedResult1 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.8, 0.8, -1.0, -0.7))
val expectedResult2 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, -0.6, -1.0, -0.1, -0.4))
it("should return the pre-calculated values on ") {
assertTrue { expectedResult1.equals(result1) }
assertTrue { expectedResult2.equals(result2) }
}
}
}
})
| mpl-2.0 | 756d10a73dff27746d2ec9d7d14c6797 | 39.821429 | 116 | 0.653835 | 3.351906 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/scan/details/ThreatDetailsFragment.kt | 1 | 6201 | package org.wordpress.android.ui.jetpack.scan.details
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.ThreatDetailsFragmentBinding
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.jetpack.scan.ScanFragment.Companion.ARG_THREAT_ID
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.OpenThreatActionDialog
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.ShowGetFreeEstimate
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.ShowJetpackSettings
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.ShowUpdatedFixState
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsNavigationEvents.ShowUpdatedScanStateWithMessage
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsViewModel.UiState.Content
import org.wordpress.android.ui.jetpack.scan.details.adapters.ThreatDetailsAdapter
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.viewmodel.observeEvent
import org.wordpress.android.widgets.WPSnackbar
import javax.inject.Inject
class ThreatDetailsFragment : Fragment(R.layout.threat_details_fragment) {
@Inject lateinit var imageManager: ImageManager
@Inject lateinit var uiHelpers: UiHelpers
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var viewModel: ThreatDetailsViewModel
private var threatActionDialog: AlertDialog? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(ThreatDetailsFragmentBinding.bind(view)) {
initDagger()
initAdapter()
initViewModel()
}
}
private fun initDagger() {
(requireActivity().application as WordPress).component().inject(this)
}
private fun ThreatDetailsFragmentBinding.initAdapter() {
recyclerView.adapter = ThreatDetailsAdapter(imageManager, uiHelpers)
}
private fun ThreatDetailsFragmentBinding.initViewModel() {
viewModel = ViewModelProvider(
this@ThreatDetailsFragment,
viewModelFactory
).get(ThreatDetailsViewModel::class.java)
setupObservers()
val threatId = requireActivity().intent.getLongExtra(ARG_THREAT_ID, 0)
viewModel.start(threatId)
}
private fun ThreatDetailsFragmentBinding.setupObservers() {
viewModel.uiState.observe(
viewLifecycleOwner,
{ uiState ->
if (uiState is Content) {
refreshContentScreen(uiState)
}
}
)
viewModel.snackbarEvents.observeEvent(viewLifecycleOwner, { it.showSnackbar() })
viewModel.navigationEvents.observeEvent(
viewLifecycleOwner,
{ events ->
when (events) {
is OpenThreatActionDialog -> showThreatActionDialog(events)
is ShowUpdatedScanStateWithMessage -> {
val site = requireNotNull(requireActivity().intent.extras)
.getSerializable(WordPress.SITE) as SiteModel
ActivityLauncher.viewScanRequestScanState(requireActivity(), site, events.messageRes)
}
is ShowUpdatedFixState -> {
val site = requireNotNull(requireActivity().intent.extras)
.getSerializable(WordPress.SITE) as SiteModel
ActivityLauncher.viewScanRequestFixState(requireActivity(), site, events.threatId)
}
is ShowGetFreeEstimate -> {
ActivityLauncher.openUrlExternal(context, events.url())
}
is ShowJetpackSettings -> ActivityLauncher.openUrlExternal(context, events.url)
}
}
)
}
private fun ThreatDetailsFragmentBinding.refreshContentScreen(content: Content) {
((recyclerView.adapter) as ThreatDetailsAdapter).update(content.items)
}
private fun SnackbarMessageHolder.showSnackbar() {
view?.let {
val snackbar = WPSnackbar.make(
it,
uiHelpers.getTextOfUiString(requireContext(), message),
Snackbar.LENGTH_LONG
)
snackbar.show()
}
}
private fun showThreatActionDialog(holder: OpenThreatActionDialog) {
threatActionDialog = MaterialAlertDialogBuilder(requireActivity())
.setTitle(uiHelpers.getTextOfUiString(requireContext(), holder.title))
.setMessage(uiHelpers.getTextOfUiString(requireContext(), holder.message))
.setPositiveButton(holder.positiveButtonLabel) { _, _ -> holder.okButtonAction.invoke() }
.setNegativeButton(holder.negativeButtonLabel) { _, _ -> threatActionDialog?.dismiss() }
.setCancelable(true)
.create()
threatActionDialog?.show()
}
@Suppress("DEPRECATION")
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (requireActivity().intent.extras?.containsKey(WordPress.SITE) != true) {
throw RuntimeException("ThreatDetailsFragment - missing siteModel extras.")
}
}
override fun onPause() {
super.onPause()
threatActionDialog?.dismiss()
}
}
| gpl-2.0 | 73fc38e1bc9f7d13bddf3da5b1c6f2ec | 43.611511 | 114 | 0.676826 | 5.541555 | false | false | false | false |
hermantai/samples | kotlin/Mastering-Kotlin-master/Chapter12/src/StandardLibraryExmaples.kt | 1 | 1942 | sealed class ProgrammingLanguage(protected val name: String) {
object Kotlin : ProgrammingLanguage("Kotlin")
object Java : ProgrammingLanguage("Java")
object Swift : ProgrammingLanguage("Swift")
override fun toString(): String {
return "$name Programming Language"
}
}
fun main() {
val mutableList = mutableListOf("Kotlin", "Java", "Swift")
val arrayList = arrayListOf("Kotlin", "Java", "Swift")
val array = arrayOf("Kotlin", "Java", "Swift")
val map = mapOf("Kotlin" to 1, "Java" to 2, "Swift" to 3)
val list = listOf("Kotlin", "Java", "Swift", "K")
list.filter { it.startsWith("K") }
.map {
when (it) {
"Kotlin" -> ProgrammingLanguage.Kotlin
else -> null
}
}
.filterNotNull()
.forEach { println(it) }
list.associate { it to it.length }
.forEach {
println("${it.key} has ${it.value} letters")
}
val first = list.first()
println(first)
val last = list.last()
println(last)
list.take(2).forEach { println(it) }
val lastK = list.findLast { it.contains("K") }
val firstK = list.find { it.contains("K") }
println(lastK)
if (list.isNullOrEmpty()) {
// handle empty case
}
val emptyList = emptyList<String>()
val emptyMap = emptyMap<String, Int>()
val emptyArray = emptyArray<String>()
var possiblyNullList: List<String>? = null
var nonNullList = possiblyNullList.orEmpty()
val string: String? = null
if (string.isNullOrBlank()) {
// handle edge cases
}
if (string.isNullOrEmpty()) {
// handle edge cases
}
if (string?.isEmpty() == true) {
// handle empty string
}
if (string?.isNotBlank() == true) {
// handle non-blank string
}
var possiblyNullString: String? = null
var nonNullString = possiblyNullString.orEmpty()
} | apache-2.0 | b56cbba3406174f8e4edbe2ef3706162 | 25.986111 | 62 | 0.583419 | 4.158458 | false | false | false | false |
iMeiji/Daily | app/src/main/java/com/meiji/daily/module/postslist/PostsListActivity.kt | 1 | 1539 | package com.meiji.daily.module.postslist
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.meiji.daily.R
import com.meiji.daily.module.base.BaseActivity
/**
* Created by Meiji on 2017/12/5.
*/
class PostsListActivity : BaseActivity() {
override fun attachLayoutId() = R.layout.container
override fun initViews() {}
override fun initData(savedInstanceState: Bundle?) {
if (intent == null) {
finish()
return
}
val slug = intent.getStringExtra(EXTRA_SLUG)
val title = intent.getStringExtra(EXTRA_NAME)
val postCount = intent.getIntExtra(EXTRA_POSTSCOUNT, 0)
// supportActionBar?.title = title
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.replace(R.id.container, PostsListView.newInstance(slug, title, postCount))
.commit()
}
}
companion object {
private val EXTRA_SLUG = "EXTRA_SLUG"
private val EXTRA_NAME = "EXTRA_NAME"
private val EXTRA_POSTSCOUNT = "EXTRA_POSTSCOUNT"
fun start(context: Context, slug: String, title: String, postsCount: Int) {
val starter = Intent(context, PostsListActivity::class.java)
.putExtra(EXTRA_SLUG, slug)
.putExtra(EXTRA_NAME, title)
.putExtra(EXTRA_POSTSCOUNT, postsCount)
context.startActivity(starter)
}
}
}
| apache-2.0 | dc17e1bae11cad26a9cc54896a0fd68c | 29.176471 | 95 | 0.615335 | 4.526471 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinLineIndentProvider.kt | 5 | 2713 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.formatter
import com.intellij.application.options.CodeStyle
import com.intellij.lang.Language
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
import org.jetbrains.kotlin.idea.formatter.lineIndent.KotlinIndentationAdjuster
import org.jetbrains.kotlin.idea.formatter.lineIndent.KotlinLangLineIndentProvider
class KotlinLineIndentProvider : KotlinLangLineIndentProvider() {
override fun getLineIndent(project: Project, editor: Editor, language: Language?, offset: Int): String? =
if (useFormatter)
null
else
super.getLineIndent(project, editor, language, offset)
override fun indentionSettings(editor: Editor): KotlinIndentationAdjuster = object : KotlinIndentationAdjuster {
val settings = CodeStyle.getSettings(editor)
val commonSettings: KotlinCommonCodeStyleSettings get() = settings.kotlinCommonSettings
val customSettings: KotlinCodeStyleSettings get() = settings.kotlinCustomSettings
override val alignWhenMultilineFunctionParentheses: Boolean
get() = commonSettings.ALIGN_MULTILINE_METHOD_BRACKETS
override val alignWhenMultilineBinaryExpression: Boolean
get() = commonSettings.ALIGN_MULTILINE_BINARY_OPERATION
override val continuationIndentInElvis: Boolean
get() = customSettings.CONTINUATION_INDENT_IN_ELVIS
override val continuationIndentForExpressionBodies: Boolean
get() = customSettings.CONTINUATION_INDENT_FOR_EXPRESSION_BODIES
override val alignMultilineParameters: Boolean
get() = commonSettings.ALIGN_MULTILINE_PARAMETERS
override val alignMultilineParametersInCalls: Boolean
get() = commonSettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS
override val continuationIndentInArgumentLists: Boolean
get() = customSettings.CONTINUATION_INDENT_IN_ARGUMENT_LISTS
override val continuationIndentInParameterLists: Boolean
get() = customSettings.CONTINUATION_INDENT_IN_PARAMETER_LISTS
override val continuationIndentInIfCondition: Boolean
get() = customSettings.CONTINUATION_INDENT_IN_IF_CONDITIONS
override val continuationIndentForChainedCalls: Boolean
get() = customSettings.CONTINUATION_INDENT_FOR_CHAINED_CALLS
}
companion object {
@set:TestOnly
var useFormatter: Boolean = false
}
}
| apache-2.0 | d4b3d2e8b7e99e0a2e4b505488017df1 | 43.47541 | 120 | 0.751935 | 5.090056 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/caches/resolve/JsResolverForModuleFactory.kt | 4 | 5169 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.caches.resolve
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.container.StorageComponentContainer
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.context.ModuleContext
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.frontend.di.createContainerForLazyResolve
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.JsKlibLibraryInfo
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.js.resolve.JsPlatformAnalyzerServices
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.SealedClassInheritorsProvider
import org.jetbrains.kotlin.resolve.TargetEnvironment
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService
import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializationUtil
import org.jetbrains.kotlin.serialization.js.createKotlinJavascriptPackageFragmentProvider
import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils
import kotlin.io.path.Path
import kotlin.io.path.exists
private val LOG = Logger.getInstance(JsResolverForModuleFactory::class.java)
class JsResolverForModuleFactory(
private val targetEnvironment: TargetEnvironment
) : ResolverForModuleFactory() {
override fun <M : ModuleInfo> createResolverForModule(
moduleDescriptor: ModuleDescriptorImpl,
moduleContext: ModuleContext,
moduleContent: ModuleContent<M>,
resolverForProject: ResolverForProject<M>,
languageVersionSettings: LanguageVersionSettings,
sealedInheritorsProvider: SealedClassInheritorsProvider
): ResolverForModule {
val (moduleInfo, syntheticFiles, moduleContentScope) = moduleContent
val project = moduleContext.project
val declarationProviderFactory = DeclarationProviderFactoryService.createDeclarationProviderFactory(
project,
moduleContext.storageManager,
syntheticFiles,
moduleContentScope,
moduleInfo
)
val container = createContainerForLazyResolve(
moduleContext,
declarationProviderFactory,
BindingTraceContext(/* allowSliceRewrite = */ true),
moduleDescriptor.platform!!,
JsPlatformAnalyzerServices,
targetEnvironment,
languageVersionSettings
)
var packageFragmentProvider = container.get<ResolveSession>().packageFragmentProvider
val libraryProviders = createPackageFragmentProvider(moduleInfo, container, moduleContext, moduleDescriptor)
if (libraryProviders.isNotEmpty()) {
packageFragmentProvider = CompositePackageFragmentProvider(
listOf(packageFragmentProvider) + libraryProviders,
"CompositeProvider@JsResolver for $moduleDescriptor"
)
}
return ResolverForModule(packageFragmentProvider, container)
}
}
internal fun <M : ModuleInfo> createPackageFragmentProvider(
moduleInfo: M,
container: StorageComponentContainer,
moduleContext: ModuleContext,
moduleDescriptor: ModuleDescriptorImpl
): List<PackageFragmentProvider> = when (moduleInfo) {
is JsKlibLibraryInfo -> {
listOfNotNull(
JsPlatforms.defaultJsPlatform.idePlatformKind.resolution.createKlibPackageFragmentProvider(
moduleInfo,
moduleContext.storageManager,
container.get(),
moduleDescriptor
)
)
}
is LibraryModuleInfo -> {
moduleInfo.getLibraryRoots()
.flatMap {
if (Path(it).exists()) {
KotlinJavascriptMetadataUtils.loadMetadata(it)
} else {
// TODO can/should we warn a user about a problem in a library root? If so how?
LOG.error("Library $it not found")
emptyList()
}
}
.filter { it.version.isCompatible() }
.map { metadata ->
val (header, packageFragmentProtos) =
KotlinJavascriptSerializationUtil.readModuleAsProto(metadata.body, metadata.version)
createKotlinJavascriptPackageFragmentProvider(
moduleContext.storageManager, moduleDescriptor, header, packageFragmentProtos, metadata.version,
container.get(), LookupTracker.DO_NOTHING
)
}
}
else -> emptyList()
}
| apache-2.0 | 8ac35e4269148f071e6ef78e3790c1f0 | 43.560345 | 158 | 0.72219 | 5.801347 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/diskmap/store/impl/EncryptedFileChannelStore.kt | 1 | 2202 | package com.onyx.diskmap.store.impl
import com.onyx.buffer.BufferPool
import com.onyx.buffer.BufferStream
import com.onyx.buffer.EncryptedBufferStream
import com.onyx.extension.withBuffer
import com.onyx.persistence.context.SchemaContext
/**
* @author Tim Osborn
*
* Encrypted File Channel storage file
*
* @since 2.2.0 Added for encrypted storage support
*/
class EncryptedFileChannelStore(filePath: String, context: SchemaContext, deleteOnClose: Boolean) : FileChannelStore(filePath, context, deleteOnClose) {
/**
* Retrieved encrypted object. This is only for managed entities
*
* @return Decrypted managed entity
* @since 2.2.0
*/
@Suppress("UNCHECKED_CAST")
override fun <T> getObject(position: Long):T {
val size = BufferPool.withIntBuffer {
this.read(it, position)
it.rewind()
it.int
}
BufferPool.allocateAndLimit(size) {
this.read(it, position + Integer.BYTES)
it.rewind()
@Suppress("UNCHECKED_CAST")
return EncryptedBufferStream(it).getObject(context) as T
}
}
/**
* Write a managed entity in an encrypted format
*
* @param value entity to write
* @return Record id of entity
* @since 2.2.0
*/
override fun writeObject(value: Any?): Long {
val stream = EncryptedBufferStream()
stream.putObject(value, context)
stream.flip()
return withBuffer(stream.byteBuffer) { valueBuffer ->
val size = valueBuffer.limit()
val position = this.allocate(size + Integer.BYTES)
BufferPool.withIntBuffer {
it.putInt(size)
it.rewind()
this.write(it, position)
}
this.write(valueBuffer, position + Integer.BYTES)
return@withBuffer position
}
}
/**
* Read an encrypted entity's data
*
* @since 2.2.0
* @return Streamable buffer
*/
override fun readObject(position: Long, size: Int): BufferStream {
val buffer = read(position, size)
return EncryptedBufferStream(buffer!!.byteBuffer)
}
}
| agpl-3.0 | ea4216cfcb4e38bc189d7f13de4ac075 | 27.230769 | 152 | 0.617166 | 4.39521 | false | false | false | false |
pdvrieze/kotlinsql | sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/metadata/impl/ColumnsResultsImpl.kt | 1 | 2812 | /*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.kotlinsql.metadata.impl
import io.github.pdvrieze.kotlinsql.UnmanagedSql
import io.github.pdvrieze.kotlinsql.metadata.ColumnsResults
import io.github.pdvrieze.kotlinsql.metadata.optionalBoolean
import java.sql.ResultSet
@Suppress("unused")
@OptIn(UnmanagedSql::class)
internal class ColumnsResultsImpl @UnmanagedSql constructor(rs: ResultSet) :
DataResultsImpl<ColumnsResults, ColumnsResults.Data>(rs),
ColumnsResults {
//TableMetaResultBase
private val idxColumnDef by lazyColIdx("COLUMN_DEF")
private val idxColumnName by lazyColIdx("COLUMN_NAME")
private val idxColumnSize by lazyColIdx("COLUMN_SIZE")
private val idxDecimalDigits by lazyColIdx("DECIMAL_DIGITS")
private val idxIsAutoIncrement by lazyColIdx("IS_AUTOINCREMENT")
private val idxIsGeneratedColumn by lazyColIdx("IS_GENERATEDCOLUMN")
private val idxNumPrecRadix by lazyColIdx("NUM_PREC_RADIX")
private val idxTableCat by lazyColIdx("TABLE_CAT")
private val idxTableName by lazyColIdx("TABLE_NAME")
private val idxTableSchem by lazyColIdx("TABLE_SCHEM")
override val columnDefault: String? get() = resultSet.getString(idxColumnDef)
override val columnName: String get() = resultSet.getString(idxColumnName)
override val columnSize: Int get() = resultSet.getInt(idxColumnSize)
override val decimalDigits: Int get() = resultSet.getInt(idxDecimalDigits)
override val isAutoIncrement: Boolean? get() = resultSet.optionalBoolean(idxIsAutoIncrement)
override val isGeneratedColumn: Boolean? get() = resultSet.optionalBoolean(idxIsGeneratedColumn)
override val numPrecRadix: Int get() = resultSet.getInt(idxNumPrecRadix)
override val tableCatalog: String? get() = resultSet.getString(idxTableCat)
override val tableName: String get() = resultSet.getString(idxTableName)
override val tableScheme: String? get() = resultSet.getString(idxTableSchem)
@OptIn(ExperimentalStdlibApi::class)
override fun toList(): List<ColumnsResults.Data> = toListImpl { ColumnsResults.Data(it) }
} | apache-2.0 | 34d974b08870b8e77bc699a79bdcb573 | 45.114754 | 100 | 0.768848 | 4.135294 | false | false | false | false |
ktorio/ktor | ktor-http/common/src/io/ktor/http/UrlDecodedParametersBuilder.kt | 1 | 3757 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http
import io.ktor.util.*
internal class UrlDecodedParametersBuilder(
private val encodedParametersBuilder: ParametersBuilder
) : ParametersBuilder {
override fun build(): Parameters = decodeParameters(encodedParametersBuilder)
override val caseInsensitiveName: Boolean = encodedParametersBuilder.caseInsensitiveName
override fun getAll(name: String): List<String>? = encodedParametersBuilder.getAll(name.encodeURLParameter())
?.map { it.decodeURLQueryComponent(plusIsSpace = true) }
override fun contains(name: String): Boolean = encodedParametersBuilder.contains(name.encodeURLParameter())
override fun contains(name: String, value: String): Boolean =
encodedParametersBuilder.contains(name.encodeURLParameter(), value.encodeURLParameterValue())
override fun names(): Set<String> =
encodedParametersBuilder.names().map { it.decodeURLQueryComponent() }.toSet()
override fun isEmpty(): Boolean = encodedParametersBuilder.isEmpty()
override fun entries(): Set<Map.Entry<String, List<String>>> = decodeParameters(encodedParametersBuilder).entries()
override fun set(name: String, value: String) =
encodedParametersBuilder.set(name.encodeURLParameter(), value.encodeURLParameterValue())
override fun get(name: String): String? =
encodedParametersBuilder[name.encodeURLParameter()]?.decodeURLQueryComponent(plusIsSpace = true)
override fun append(name: String, value: String) =
encodedParametersBuilder.append(name.encodeURLParameter(), value.encodeURLParameterValue())
override fun appendAll(stringValues: StringValues) = encodedParametersBuilder.appendAllEncoded(stringValues)
override fun appendAll(name: String, values: Iterable<String>) =
encodedParametersBuilder.appendAll(name.encodeURLParameter(), values.map { it.encodeURLParameterValue() })
override fun appendMissing(stringValues: StringValues) =
encodedParametersBuilder.appendMissing(encodeParameters(stringValues).build())
override fun appendMissing(name: String, values: Iterable<String>) =
encodedParametersBuilder.appendMissing(name.encodeURLParameter(), values.map { it.encodeURLParameterValue() })
override fun remove(name: String) =
encodedParametersBuilder.remove(name.encodeURLParameter())
override fun remove(name: String, value: String): Boolean =
encodedParametersBuilder.remove(name.encodeURLParameter(), value.encodeURLParameterValue())
override fun removeKeysWithNoEntries() = encodedParametersBuilder.removeKeysWithNoEntries()
override fun clear() = encodedParametersBuilder.clear()
}
internal fun decodeParameters(parameters: StringValuesBuilder): Parameters = ParametersBuilder()
.apply { appendAllDecoded(parameters) }
.build()
internal fun encodeParameters(parameters: StringValues): ParametersBuilder = ParametersBuilder()
.apply { appendAllEncoded(parameters) }
private fun StringValuesBuilder.appendAllDecoded(parameters: StringValuesBuilder) {
parameters.names()
.forEach { key ->
val values = parameters.getAll(key) ?: emptyList()
appendAll(
key.decodeURLQueryComponent(),
values.map { it.decodeURLQueryComponent(plusIsSpace = true) }
)
}
}
private fun StringValuesBuilder.appendAllEncoded(parameters: StringValues) {
parameters.names()
.forEach { key ->
val values = parameters.getAll(key) ?: emptyList()
appendAll(key.encodeURLParameter(), values.map { it.encodeURLParameterValue() })
}
}
| apache-2.0 | fca9c44f75f50d0193e74b90e84c0c88 | 42.183908 | 119 | 0.741549 | 4.82285 | false | false | false | false |
ktorio/ktor | ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/FrameParser.kt | 1 | 3633 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.websocket
import java.nio.*
import java.util.concurrent.atomic.*
@Suppress("KDocMissingDocumentation", "UsePropertyAccessSyntax")
public class FrameParser {
private val state = AtomicReference(State.HEADER0)
public var fin: Boolean = false
private set
public var rsv1: Boolean = false
private set
public var rsv2: Boolean = false
private set
public var rsv3: Boolean = false
private set
public var mask: Boolean = false
private set
private var opcode = 0
private var lastOpcode = 0
private var lengthLength = 0
public var length: Long = 0L
private set
public var maskKey: Int? = null
private set
public val frameType: FrameType
get() = FrameType[opcode] ?: throw IllegalStateException("Unsupported opcode ${Integer.toHexString(opcode)}")
public enum class State {
HEADER0,
LENGTH,
MASK_KEY,
BODY
}
public val bodyReady: Boolean
get() = state.get() == State.BODY
public fun bodyComplete() {
if (!state.compareAndSet(State.BODY, State.HEADER0)) {
throw IllegalStateException("It should be state BODY but it is ${state.get()}")
}
// lastOpcode should be never reset!
opcode = 0
length = 0L
lengthLength = 0
maskKey = null
}
public fun frame(bb: ByteBuffer) {
require(bb.order() == ByteOrder.BIG_ENDIAN) { "Buffer order should be BIG_ENDIAN but it is ${bb.order()}" }
while (handleStep(bb)) {
}
}
private fun handleStep(bb: ByteBuffer) = when (state.get()!!) {
State.HEADER0 -> parseHeader1(bb)
State.LENGTH -> parseLength(bb)
State.MASK_KEY -> parseMaskKey(bb)
State.BODY -> false
}
private fun parseHeader1(bb: ByteBuffer): Boolean {
if (bb.remaining() < 2) {
return false
}
val flagsAndOpcode = bb.get().toInt()
val maskAndLength1 = bb.get().toInt()
fin = flagsAndOpcode and 0x80 != 0
rsv1 = flagsAndOpcode and 0x40 != 0
rsv2 = flagsAndOpcode and 0x20 != 0
rsv3 = flagsAndOpcode and 0x10 != 0
opcode = (flagsAndOpcode and 0x0f).let { new -> if (new == 0) lastOpcode else new }
if (!frameType.controlFrame) {
lastOpcode = opcode
}
mask = maskAndLength1 and 0x80 != 0
val length1 = maskAndLength1 and 0x7f
lengthLength = when (length1) {
126 -> 2
127 -> 8
else -> 0
}
length = if (lengthLength == 0) length1.toLong() else 0
when {
lengthLength > 0 -> state.set(State.LENGTH)
mask -> state.set(State.MASK_KEY)
else -> state.set(State.BODY)
}
return true
}
private fun parseLength(bb: ByteBuffer): Boolean {
if (bb.remaining() < lengthLength) {
return false
}
length = when (lengthLength) {
2 -> bb.getShort().toLong() and 0xffff
8 -> bb.getLong()
else -> throw IllegalStateException()
}
val mask = if (mask) State.MASK_KEY else State.BODY
state.set(mask)
return true
}
private fun parseMaskKey(bb: ByteBuffer): Boolean {
if (bb.remaining() < 4) {
return false
}
maskKey = bb.getInt()
state.set(State.BODY)
return true
}
}
| apache-2.0 | 849c09aa03c43f155654e96969b16c7b | 24.95 | 119 | 0.575282 | 4.219512 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-host-common/jvm/src/io/ktor/server/engine/EngineConnectorConfigJvm.kt | 1 | 3106 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.engine
import java.io.*
import java.security.*
/**
* Adds a secure connector to this engine environment
*/
public inline fun ApplicationEngineEnvironmentBuilder.sslConnector(
keyStore: KeyStore,
keyAlias: String,
noinline keyStorePassword: () -> CharArray,
noinline privateKeyPassword: () -> CharArray,
builder: EngineSSLConnectorBuilder.() -> Unit
) {
connectors.add(EngineSSLConnectorBuilder(keyStore, keyAlias, keyStorePassword, privateKeyPassword).apply(builder))
}
/**
* Mutable implementation of EngineSSLConnectorConfig for building connectors programmatically
*/
public class EngineSSLConnectorBuilder(
override var keyStore: KeyStore,
override var keyAlias: String,
override var keyStorePassword: () -> CharArray,
override var privateKeyPassword: () -> CharArray
) : EngineConnectorBuilder(ConnectorType.HTTPS), EngineSSLConnectorConfig {
override var keyStorePath: File? = null
override var trustStore: KeyStore? = null
override var trustStorePath: File? = null
override var port: Int = 443
override var enabledProtocols: List<String>? = null
}
/**
* Represents an SSL connector configuration.
*/
public interface EngineSSLConnectorConfig : EngineConnectorConfig {
/**
* KeyStore where a certificate is stored
*/
public val keyStore: KeyStore
/**
* File where the keystore is located
*/
public val keyStorePath: File?
/**
* TLS key alias
*/
public val keyAlias: String
/**
* Keystore password provider
*/
public val keyStorePassword: () -> CharArray
/**
* Private key password provider
*/
public val privateKeyPassword: () -> CharArray
/**
* Store of trusted certificates for verifying the remote endpoint's certificate.
*
* The engine tries to use [trustStore] first and uses [trustStorePath] as a fallback.
*
* If [trustStore] and [trustStorePath] are both null, the endpoint's certificate will not be verified.
*/
public val trustStore: KeyStore?
/**
* File with trusted certificates (JKS) for verifying the remote endpoint's certificate.
*
* The engine tries to use [trustStore] first and uses [trustStorePath] as a fallback.
*
* If [trustStore] and [trustStorePath] are both null, the endpoint's certificate will not be verified.
*/
public val trustStorePath: File?
/**
* Enabled protocol versions
*/
public val enabledProtocols: List<String>?
}
/**
* Returns new instance of [EngineConnectorConfig] based on [this] with modified port
*/
public actual fun EngineConnectorConfig.withPort(otherPort: Int): EngineConnectorConfig = when (this) {
is EngineSSLConnectorBuilder -> object : EngineSSLConnectorConfig by this {
override val port: Int = otherPort
}
else -> object : EngineConnectorConfig by this {
override val port: Int = otherPort
}
}
| apache-2.0 | e20ea25144b6aff47a9cbc0daee78b60 | 29.45098 | 119 | 0.698004 | 4.594675 | false | true | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionUpdateJob.kt | 1 | 3639 | package eu.kanade.tachiyomi.extension
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.notification.NotificationReceiver
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.extension.api.ExtensionGithubApi
import eu.kanade.tachiyomi.util.system.logcat
import eu.kanade.tachiyomi.util.system.notification
import kotlinx.coroutines.coroutineScope
import logcat.LogPriority
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.concurrent.TimeUnit
class ExtensionUpdateJob(private val context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result = coroutineScope {
val pendingUpdates = try {
ExtensionGithubApi().checkForUpdates(context)
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
return@coroutineScope Result.failure()
}
if (pendingUpdates.isNotEmpty()) {
createUpdateNotification(pendingUpdates.map { it.name })
}
Result.success()
}
private fun createUpdateNotification(names: List<String>) {
NotificationManagerCompat.from(context).apply {
notify(
Notifications.ID_UPDATES_TO_EXTS,
context.notification(Notifications.CHANNEL_EXTENSIONS_UPDATE) {
setContentTitle(
context.resources.getQuantityString(
R.plurals.update_check_notification_ext_updates,
names.size,
names.size
)
)
val extNames = names.joinToString(", ")
setContentText(extNames)
setStyle(NotificationCompat.BigTextStyle().bigText(extNames))
setSmallIcon(R.drawable.ic_extension_24dp)
setContentIntent(NotificationReceiver.openExtensionsPendingActivity(context))
setAutoCancel(true)
}
)
}
}
companion object {
private const val TAG = "ExtensionUpdate"
fun setupTask(context: Context, forceAutoUpdateJob: Boolean? = null) {
val preferences = Injekt.get<PreferencesHelper>()
val autoUpdateJob = forceAutoUpdateJob ?: preferences.automaticExtUpdates().get()
if (autoUpdateJob) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<ExtensionUpdateJob>(
2,
TimeUnit.DAYS,
3,
TimeUnit.HOURS
)
.addTag(TAG)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.REPLACE, request)
} else {
WorkManager.getInstance(context).cancelAllWorkByTag(TAG)
}
}
}
}
| apache-2.0 | 070b96dcf10855d0f78e51985e4923e7 | 37.712766 | 124 | 0.637538 | 5.615741 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterHolder.kt | 2 | 2979 | package eu.kanade.tachiyomi.ui.manga.chapter
import android.text.SpannableStringBuilder
import android.view.View
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import androidx.core.view.isVisible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.databinding.ChaptersItemBinding
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.ui.manga.chapter.base.BaseChapterHolder
import eu.kanade.tachiyomi.util.lang.toRelativeString
import java.util.Date
class ChapterHolder(
view: View,
private val adapter: ChaptersAdapter
) : BaseChapterHolder(view, adapter) {
private val binding = ChaptersItemBinding.bind(view)
init {
binding.download.setOnClickListener {
onDownloadClick(it, bindingAdapterPosition)
}
}
fun bind(item: ChapterItem, manga: Manga) {
val chapter = item.chapter
binding.chapterTitle.text = when (manga.displayMode) {
Manga.CHAPTER_DISPLAY_NUMBER -> {
val number = adapter.decimalFormat.format(chapter.chapter_number.toDouble())
itemView.context.getString(R.string.display_mode_chapter, number)
}
else -> chapter.name
}
// Set correct text color
val chapterTitleColor = when {
chapter.read -> adapter.readColor
chapter.bookmark -> adapter.bookmarkedColor
else -> adapter.unreadColor
}
binding.chapterTitle.setTextColor(chapterTitleColor)
val chapterDescriptionColor = when {
chapter.read -> adapter.readColor
chapter.bookmark -> adapter.bookmarkedColor
else -> adapter.unreadColorSecondary
}
binding.chapterDescription.setTextColor(chapterDescriptionColor)
binding.bookmarkIcon.isVisible = chapter.bookmark
val descriptions = mutableListOf<CharSequence>()
if (chapter.date_upload > 0) {
descriptions.add(Date(chapter.date_upload).toRelativeString(itemView.context, adapter.relativeTime, adapter.dateFormat))
}
if (!chapter.read && chapter.last_page_read > 0) {
val lastPageRead = buildSpannedString {
color(adapter.readColor) {
append(itemView.context.getString(R.string.chapter_progress, chapter.last_page_read + 1))
}
}
descriptions.add(lastPageRead)
}
if (!chapter.scanlator.isNullOrBlank()) {
descriptions.add(chapter.scanlator!!)
}
if (descriptions.isNotEmpty()) {
binding.chapterDescription.text = descriptions.joinTo(SpannableStringBuilder(), " • ")
} else {
binding.chapterDescription.text = ""
}
binding.download.isVisible = item.manga.source != LocalSource.ID
binding.download.setState(item.status, item.progress)
}
}
| apache-2.0 | 2485f5f767e9436efb8777749e436fa6 | 34.86747 | 132 | 0.665435 | 4.703002 | false | false | false | false |
chaojimiaomiao/colorful_wechat | src/main/java/com/rarnu/tophighlight/PublishActivity.kt | 1 | 5054 | package com.rarnu.tophighlight
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import com.rarnu.tophighlight.api.LocalApi
import com.rarnu.tophighlight.api.ThemeINI
import com.rarnu.tophighlight.api.WthApi
import com.rarnu.tophighlight.market.LocalTheme
import com.rarnu.tophighlight.market.UserLoginRegisterActivity
import com.rarnu.tophighlight.ui.CustomToolBar
import com.rarnu.tophighlight.util.UIUtils
import java.io.File
class PublishActivity : AppCompatActivity(), View.OnClickListener {
private val REQUEST_CODE_CHOOSE_IMAGE = 100;
private val REQUEST_CODE_CROP_IMAGE = 101
private val CHOOSE_BIG_PICTURE = 1
override fun onClick(v: View?) {
}
private var ini : ThemeINI?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_publish)
var toolBar = findViewById(R.id.publish_toolbar) as CustomToolBar?
setSupportActionBar(toolBar)
setTitle(R.string.diy_theme)
/*if(getSupportActionBar() != null)
getSupportActionBar()?.setDisplayHomeAsUpEnabled(true)*/
loadTheme()
var publishBtn = findViewById(R.id.btn_publish)
findViewById(R.id.publish_login_btn).setOnClickListener {
startActivity(Intent(this, UserLoginRegisterActivity::class.java))
}
findViewById(R.id.btn_publish).setOnClickListener {
var ret = WthApi.themeUpload(LocalApi.userId, ini?.themeName, "", ini?.listPath?.replace(".png", ".ini"))
Log.e("", "发布结果" + ret)
}
val IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg"//temp file
val imageUri = Uri.parse(IMAGE_FILE_LOCATION)//The Uri to store the big bitmap
findViewById(R.id.publish_back).setOnClickListener {
openGallery()
}
findViewById(R.id.publish_topback).setOnClickListener {
}
findViewById(R.id.publish_bottomback).setOnClickListener {
}
}
private fun loadTheme() {
ini = LocalTheme.themeFlower
var themePreview = findViewById(R.id.vPreview) as ThemePreviewView
themePreview.setThemePreview(ini)
}
private fun openGallery() {
val intent = Intent(Intent.ACTION_PICK, null)
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
startActivityForResult(intent, REQUEST_CODE_CHOOSE_IMAGE)
}
/**
* 裁减图片操作
* @param uri
*/
private fun startCropImage(uri: Uri) {
val intent = Intent("com.android.camera.action.CROP")
intent.setDataAndType(uri, "image/*")
// 使图片处于可裁剪状态
intent.putExtra("crop", "true")
// 裁剪框的比例(根据需要显示的图片比例进行设置)
intent.putExtra("aspectX", 2)
intent.putExtra("aspectY", 3)
// 让裁剪框支持缩放
intent.putExtra("scale", true)
// 裁剪后图片的大小(注意和上面的裁剪比例保持一致)
intent.putExtra("outputX", UIUtils.dip2px(480))
intent.putExtra("outputY", UIUtils.dip2px(720))
// 传递原图路径
val cropFile = File(Environment.getExternalStorageDirectory().toString() + "crop_image.jpg")
var cropImageUri = Uri.fromFile(cropFile)
intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri)
// 设置裁剪区域的形状,默认为矩形,也可设置为原形
//intent.putExtra("circleCrop", true);
// 设置图片的输出格式
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
// return-data=true传递的为缩略图,小米手机默认传递大图,所以会导致onActivityResult调用失败
intent.putExtra("return-data", false)
// 是否需要人脸识别
intent.putExtra("noFaceDetection", true)
startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (intent != null) {
when (requestCode) {
// 将选择的图片进行裁剪
REQUEST_CODE_CHOOSE_IMAGE -> if (intent.data != null) {
var iconUri = intent.data
startCropImage(iconUri)
}
// 将裁剪后的图片进行上传
REQUEST_CODE_CROP_IMAGE -> {
var ret = WthApi.themeUpload(LocalApi.userId, "name", "what", ini?.listPath?.replace(".png", ".ini"))
Log.e("", "ret" +ret)
//
}
else -> {
}
}// 上传图片操作
}
}
}
| gpl-3.0 | b8add51d85f8b7999d4f12a0636896d8 | 33.573529 | 121 | 0.64228 | 4.046472 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/i18n/intentions/TrimKeyIntention.kt | 1 | 1488 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.i18n.intentions
import com.demonwav.mcdev.i18n.lang.gen.psi.I18nEntry
import com.demonwav.mcdev.i18n.lang.gen.psi.I18nTypes
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.util.IncorrectOperationException
class TrimKeyIntention : BaseElementAtCaretIntentionAction() {
override fun getText() = "Trim translation key"
override fun getFamilyName() = "Minecraft"
override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean {
val entry: I18nEntry = when {
element is I18nEntry -> element
element.node.elementType === I18nTypes.KEY && element.parent is I18nEntry -> element.parent as I18nEntry
else -> return false
}
return entry.key != entry.trimmedKey
}
@Throws(IncorrectOperationException::class)
override fun invoke(project: Project, editor: Editor, element: PsiElement) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(element.parent)) {
return
}
val entry = element.parent as I18nEntry
entry.setName(entry.trimmedKey)
}
}
| mit | 9f6b0f89cf54d2c5683d67d71de57bc9 | 32.818182 | 116 | 0.727823 | 4.288184 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/buildsystem/maven/MavenBuildSystem.kt | 1 | 5669 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.buildsystem.maven
import com.demonwav.mcdev.buildsystem.BuildSystem
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.ProjectConfiguration
import com.demonwav.mcdev.platform.bukkit.BukkitTemplate
import com.demonwav.mcdev.platform.bungeecord.BungeeCordTemplate
import com.demonwav.mcdev.platform.sponge.SpongeTemplate
import com.demonwav.mcdev.util.runWriteAction
import com.demonwav.mcdev.util.runWriteTask
import com.intellij.codeInsight.actions.ReformatCodeProcessor
import com.intellij.execution.RunManager
import com.intellij.lang.xml.XMLLanguage
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.PsiManager
import com.intellij.psi.xml.XmlFile
import com.intellij.util.xml.DomManager
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel
import org.jetbrains.idea.maven.execution.MavenRunConfigurationType
import org.jetbrains.idea.maven.execution.MavenRunnerParameters
import org.jetbrains.idea.maven.project.MavenProjectsManager
class MavenBuildSystem : BuildSystem() {
private lateinit var pomFile: VirtualFile
override fun create(project: Project, configuration: ProjectConfiguration, indicator: ProgressIndicator) {
rootDirectory.refresh(false, true)
runWriteTask {
createDirectories()
val text = when (configuration.type) {
PlatformType.BUKKIT, PlatformType.SPIGOT, PlatformType.PAPER ->
BukkitTemplate.applyPomTemplate(project, buildVersion)
PlatformType.BUNGEECORD, PlatformType.WATERFALL -> BungeeCordTemplate.applyPomTemplate(project, buildVersion)
PlatformType.SPONGE -> SpongeTemplate.applyPomTemplate(project, buildVersion)
else -> return@runWriteTask
}
val pomPsi = PsiFileFactory.getInstance(project).createFileFromText(XMLLanguage.INSTANCE, text) ?: return@runWriteTask
pomPsi.name = "pom.xml"
val pomXmlPsi = pomPsi as XmlFile
pomPsi.runWriteAction {
val manager = DomManager.getDomManager(project)
val mavenProjectXml = manager.getFileElement(pomXmlPsi, MavenDomProjectModel::class.java)!!.rootElement
mavenProjectXml.groupId.value = groupId
mavenProjectXml.artifactId.value = artifactId
mavenProjectXml.version.value = version
mavenProjectXml.name.value = pluginName
val root = pomXmlPsi.rootTag ?: return@runWriteAction
val properties = root.findFirstSubTag("properties") ?: return@runWriteAction
if (!configuration.website.isNullOrEmpty()) {
val url = root.createChildTag("url", null, configuration.website, false)
root.addAfter(url, properties)
}
if (configuration.description.isNotEmpty()) {
val description = root.createChildTag("description", null, configuration.description, false)
root.addBefore(description, properties)
}
for ((id, url) in repositories) {
val repository = mavenProjectXml.repositories.addRepository()
repository.id.value = id
repository.url.value = url
}
for ((depArtifactId, depGroupId, depVersion, scope) in dependencies) {
val dependency = mavenProjectXml.dependencies.addDependency()
dependency.groupId.value = depGroupId
dependency.artifactId.value = depArtifactId
dependency.version.value = depVersion
dependency.scope.value = scope
}
val dir = PsiManager.getInstance(project).findDirectory(rootDirectory) ?: return@runWriteAction
dir.findFile(pomPsi.name)?.delete()
dir.add(pomPsi)
pomFile = rootDirectory.findChild("pom.xml") ?: return@runWriteAction
// Reformat the code to match their code style
PsiManager.getInstance(project).findFile(pomFile)?.let {
ReformatCodeProcessor(it, false).run()
}
}
}
}
override fun finishSetup(rootModule: Module, configurations: Collection<ProjectConfiguration>, indicator: ProgressIndicator) {
runWriteTask {
val project = rootModule.project
// Force Maven to setup the project
val manager = MavenProjectsManager.getInstance(project)
manager.addManagedFilesOrUnignore(listOf(pomFile))
manager.importingSettings.isDownloadDocsAutomatically = true
manager.importingSettings.isDownloadSourcesAutomatically = true
// Setup the default Maven run config
val params = MavenRunnerParameters()
params.workingDirPath = rootDirectory.canonicalPath!!
params.goals = listOf("clean", "package")
val runnerSettings = MavenRunConfigurationType
.createRunnerAndConfigurationSettings(null, null, params, project)
runnerSettings.name = rootModule.name + " build"
RunManager.getInstance(project).addConfiguration(runnerSettings, false)
}
}
}
| mit | 75a03ad511f4d10fe5c53d51901009d0 | 42.607692 | 130 | 0.672782 | 5.358223 | false | true | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/program/ProgramIndicatorTableInfo.kt | 1 | 3015 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.program
import org.hisp.dhis.android.core.arch.db.tableinfos.TableInfo
import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper
import org.hisp.dhis.android.core.common.CoreColumns
import org.hisp.dhis.android.core.common.NameableColumns
object ProgramIndicatorTableInfo {
@JvmField
val TABLE_INFO: TableInfo = object : TableInfo() {
override fun name(): String {
return "ProgramIndicator"
}
override fun columns(): CoreColumns {
return Columns()
}
}
class Columns : NameableColumns() {
override fun all(): Array<String> {
return CollectionsHelper.appendInNewArray(
super.all(),
DISPLAY_IN_FORM,
EXPRESSION,
DIMENSION_ITEM,
FILTER,
DECIMALS,
AGGREGATION_TYPE,
PROGRAM,
ANALYTICS_TYPE
)
}
companion object {
const val DISPLAY_IN_FORM = "displayInForm"
const val EXPRESSION = "expression"
const val DIMENSION_ITEM = "dimensionItem"
const val FILTER = "filter"
const val DECIMALS = "decimals"
const val AGGREGATION_TYPE = "aggregationType"
const val PROGRAM = "program"
const val ANALYTICS_TYPE = "analyticsType"
}
}
}
| bsd-3-clause | 6a8dbbef7e03e096e6c18aacae9fff98 | 40.30137 | 83 | 0.678275 | 4.652778 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/page/linkpreview/LinkPreviewErrorView.kt | 1 | 2115 | package org.wikipedia.page.linkpreview
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.appcompat.content.res.AppCompatResources
import org.wikipedia.R
import org.wikipedia.databinding.ViewLinkPreviewErrorBinding
class LinkPreviewErrorView : LinearLayout {
interface Callback {
fun onAddToList()
fun onDismiss()
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
private val binding = ViewLinkPreviewErrorBinding.inflate(LayoutInflater.from(context), this)
var callback: Callback? = null
val addToListCallback = OverlayViewAddToListCallback()
val dismissCallback = OverlayViewDismissCallback()
fun setError(caught: Throwable?) {
val errorType = LinkPreviewErrorType[caught]
binding.viewLinkPreviewErrorIcon.setImageDrawable(AppCompatResources.getDrawable(context, errorType.icon))
if (errorType === LinkPreviewErrorType.OFFLINE) {
val message = (resources.getString(R.string.page_offline_notice_cannot_load_while_offline) +
resources.getString(R.string.page_offline_notice_add_to_reading_list)).trimIndent()
binding.viewLinkPreviewErrorText.text = message
} else {
binding.viewLinkPreviewErrorText.text = context.resources.getString(errorType.text)
}
}
inner class OverlayViewAddToListCallback : LinkPreviewOverlayView.Callback {
override fun onPrimaryClick() {
callback?.onAddToList()
}
override fun onSecondaryClick() {}
override fun onTertiaryClick() {}
}
inner class OverlayViewDismissCallback : LinkPreviewOverlayView.Callback {
override fun onPrimaryClick() {
callback?.onDismiss()
}
override fun onSecondaryClick() {}
override fun onTertiaryClick() {}
}
}
| apache-2.0 | 7b0a372f0d7f76ecca2be411c9d03c06 | 38.166667 | 114 | 0.718676 | 4.988208 | false | false | false | false |
dahlstrom-g/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/OrderEntriesBridge.kt | 4 | 14869 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.ClonableOrderEntry
import com.intellij.openapi.roots.impl.ProjectRootManagerImpl
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.projectModel.ProjectModelBundle
import com.intellij.util.ArrayUtil
import com.intellij.util.PathUtil
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleByEntity
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryTableId
import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleDependencyItem
import org.jetbrains.annotations.Nls
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer
internal abstract class OrderEntryBridge(
private val rootModel: ModuleRootModelBridge,
private val initialIndex: Int,
var item: ModuleDependencyItem,
private val itemUpdater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)?
) : OrderEntry {
protected var index = initialIndex
protected val ownerModuleBridge: ModuleBridge
get() = rootModel.moduleBridge
protected val updater: (Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit
get() = itemUpdater ?: error("This mode is read-only. Call from a modifiable model")
fun getRootModel(): ModuleRootModelBridge = rootModel
fun updateIndex(newIndex: Int) {
index = newIndex
}
internal val currentIndex: Int
get() = index
override fun getOwnerModule() = ownerModuleBridge
override fun compareTo(other: OrderEntry?) = index.compareTo((other as OrderEntryBridge).index)
override fun isValid() = true
override fun isSynthetic() = false
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as OrderEntryBridge
if (ownerModuleBridge != other.ownerModuleBridge) return false
if (initialIndex != other.initialIndex) return false
if (item != other.item) return false
return true
}
override fun hashCode(): Int {
var result = ownerModuleBridge.hashCode()
result = 31 * result + initialIndex
result = 31 * result + item.hashCode()
return result
}
}
internal abstract class ExportableOrderEntryBridge(
rootModel: ModuleRootModelBridge,
index: Int,
exportableDependencyItem: ModuleDependencyItem.Exportable,
itemUpdater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)?
) : OrderEntryBridge(rootModel, index, exportableDependencyItem, itemUpdater), ExportableOrderEntry {
private val exportableItem
get() = item as ModuleDependencyItem.Exportable
override fun isExported() = exportableItem.exported
override fun setExported(value: Boolean) {
if (isExported == value) return
updater(index) { (it as ModuleDependencyItem.Exportable).withExported(value) }
item = (item as ModuleDependencyItem.Exportable).withExported(value)
}
override fun getScope() = exportableItem.scope.toDependencyScope()
override fun setScope(scope: DependencyScope) {
if (getScope() == scope) return
updater(index) { (it as ModuleDependencyItem.Exportable).withScope(scope.toEntityDependencyScope()) }
item = (item as ModuleDependencyItem.Exportable).withScope(scope.toEntityDependencyScope())
}
}
internal class ModuleOrderEntryBridge(
rootModel: ModuleRootModelBridge,
index: Int,
moduleDependencyItem: ModuleDependencyItem.Exportable.ModuleDependency,
itemUpdater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)?
) : ExportableOrderEntryBridge(rootModel, index, moduleDependencyItem, itemUpdater), ModuleOrderEntry, ClonableOrderEntry {
private val moduleDependencyItem
get() = item as ModuleDependencyItem.Exportable.ModuleDependency
override fun getModule(): Module? {
val storage = getRootModel().storage
val moduleEntity = storage.resolve(moduleDependencyItem.module)
val module = moduleEntity?.let {
storage.findModuleByEntity(it)
}
return getRootModel().accessor.getModule(module, moduleName)
}
override fun getModuleName() = moduleDependencyItem.module.name
override fun isProductionOnTestDependency() = moduleDependencyItem.productionOnTest
override fun setProductionOnTestDependency(productionOnTestDependency: Boolean) {
if (isProductionOnTestDependency == productionOnTestDependency) return
updater(index) { item ->
(item as ModuleDependencyItem.Exportable.ModuleDependency).copy(productionOnTest = productionOnTestDependency)
}
item = (item as ModuleDependencyItem.Exportable.ModuleDependency).copy(productionOnTest = productionOnTestDependency)
}
override fun getFiles(type: OrderRootType): Array<VirtualFile> = getEnumerator(type)?.roots ?: VirtualFile.EMPTY_ARRAY
override fun getUrls(rootType: OrderRootType): Array<String> = getEnumerator(rootType)?.urls ?: ArrayUtil.EMPTY_STRING_ARRAY
private fun getEnumerator(rootType: OrderRootType) = ownerModuleBridge.let {
getEnumeratorForType(rootType, it).usingCache()
}
private fun getEnumeratorForType(type: OrderRootType, module: Module): OrderRootsEnumerator {
val base = OrderEnumerator.orderEntries(module)
if (type === OrderRootType.CLASSES) {
return base.exportedOnly().withoutModuleSourceEntries().recursively().classes()
}
return if (type === OrderRootType.SOURCES) {
base.exportedOnly().recursively().sources()
}
else base.roots(type)
}
override fun getPresentableName() = moduleName
override fun isValid(): Boolean = module != null
override fun <R : Any?> accept(policy: RootPolicy<R>, initialValue: R?): R? = policy.visitModuleOrderEntry(this, initialValue)
override fun cloneEntry(rootModel: ModifiableRootModel,
projectRootManager: ProjectRootManagerImpl,
filePointerManager: VirtualFilePointerManager
): OrderEntry = ModuleOrderEntryBridge(
rootModel as ModuleRootModelBridge,
index, moduleDependencyItem.copy(), null
)
}
fun ModuleDependencyItem.DependencyScope.toDependencyScope() = when (this) {
ModuleDependencyItem.DependencyScope.COMPILE -> DependencyScope.COMPILE
ModuleDependencyItem.DependencyScope.RUNTIME -> DependencyScope.RUNTIME
ModuleDependencyItem.DependencyScope.PROVIDED -> DependencyScope.PROVIDED
ModuleDependencyItem.DependencyScope.TEST -> DependencyScope.TEST
}
fun DependencyScope.toEntityDependencyScope(): ModuleDependencyItem.DependencyScope = when (this) {
DependencyScope.COMPILE -> ModuleDependencyItem.DependencyScope.COMPILE
DependencyScope.RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME
DependencyScope.PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED
DependencyScope.TEST -> ModuleDependencyItem.DependencyScope.TEST
}
internal abstract class SdkOrderEntryBaseBridge(
rootModel: ModuleRootModelBridge,
index: Int,
item: ModuleDependencyItem
) : OrderEntryBridge(rootModel, index, item, null), LibraryOrSdkOrderEntry {
protected abstract val rootProvider: RootProvider?
override fun getRootFiles(type: OrderRootType): Array<VirtualFile> = rootProvider?.getFiles(type) ?: VirtualFile.EMPTY_ARRAY
override fun getRootUrls(type: OrderRootType): Array<String> = rootProvider?.getUrls(type) ?: ArrayUtil.EMPTY_STRING_ARRAY
override fun getFiles(type: OrderRootType) = getRootFiles(type)
override fun getUrls(rootType: OrderRootType) = getRootUrls(rootType)
}
internal class LibraryOrderEntryBridge(
rootModel: ModuleRootModelBridge,
index: Int,
libraryDependencyItem: ModuleDependencyItem.Exportable.LibraryDependency,
itemUpdater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)?
) : ExportableOrderEntryBridge(rootModel, index, libraryDependencyItem, itemUpdater), LibraryOrderEntry, ClonableOrderEntry {
override fun getPresentableName(): String = libraryName ?: getPresentableNameForUnnamedLibrary()
internal val libraryDependencyItem
get() = item as ModuleDependencyItem.Exportable.LibraryDependency
@Nls
private fun getPresentableNameForUnnamedLibrary(): String {
val url = getUrls(OrderRootType.CLASSES).firstOrNull()
return if (url != null) PathUtil.toPresentableUrl(url) else ProjectModelBundle.message("empty.library.title")
}
private val rootProvider: RootProvider?
get() = library?.rootProvider
override fun getLibraryLevel() = libraryDependencyItem.library.tableId.level
override fun getLibraryName() = LibraryNameGenerator.getLegacyLibraryName(libraryDependencyItem.library)
override fun getLibrary(): Library? {
val libraryId = libraryDependencyItem.library
val tableId = libraryId.tableId
val library = if (tableId is LibraryTableId.GlobalLibraryTableId) {
LibraryTablesRegistrar.getInstance()
.getLibraryTableByLevel(tableId.level, ownerModuleBridge.project)
?.getLibraryByName(libraryId.name)
}
else {
val storage = getRootModel().storage
val libraryEntity = storage.resolve(libraryId)
libraryEntity?.let { storage.libraryMap.getDataByEntity(libraryEntity) }
}
return if (tableId is LibraryTableId.ModuleLibraryTableId) {
// model.accessor.getLibrary is not applicable to module libraries
library
}
else {
getRootModel().accessor.getLibrary(library, libraryName, libraryLevel)
}
}
override fun isModuleLevel() = libraryLevel == JpsLibraryTableSerializer.MODULE_LEVEL
override fun getRootFiles(type: OrderRootType): Array<VirtualFile> = rootProvider?.getFiles(type) ?: VirtualFile.EMPTY_ARRAY
override fun getRootUrls(type: OrderRootType): Array<String> = rootProvider?.getUrls(type) ?: ArrayUtil.EMPTY_STRING_ARRAY
override fun getFiles(type: OrderRootType) = getRootFiles(type)
override fun getUrls(rootType: OrderRootType) = getRootUrls(rootType)
override fun isValid(): Boolean = library != null
override fun <R : Any?> accept(policy: RootPolicy<R>, initialValue: R?): R? = policy.visitLibraryOrderEntry(this, initialValue)
override fun cloneEntry(rootModel: ModifiableRootModel,
projectRootManager: ProjectRootManagerImpl,
filePointerManager: VirtualFilePointerManager
): OrderEntry {
return LibraryOrderEntryBridge(getRootModel(), index, libraryDependencyItem, null)
}
override fun isSynthetic(): Boolean = isModuleLevel
}
internal class SdkOrderEntryBridge(
rootModel: ModuleRootModelBridge,
index: Int,
internal val sdkDependencyItem: ModuleDependencyItem.SdkDependency
) : SdkOrderEntryBaseBridge(rootModel, index, sdkDependencyItem), ModuleJdkOrderEntry, ClonableOrderEntry {
override val rootProvider: RootProvider?
get() = jdk?.rootProvider
override fun getPresentableName() = "< ${jdk?.name ?: sdkDependencyItem.sdkName} >"
override fun isValid(): Boolean = jdk != null
override fun getJdk(): Sdk? {
val sdkType = sdkDependencyItem.sdkType
val sdkName = sdkDependencyItem.sdkName
val sdk = ModifiableRootModelBridge.findSdk(sdkName, sdkType)
return getRootModel().accessor.getSdk(sdk, sdkName)
}
override fun getJdkName() = sdkDependencyItem.sdkName
override fun getJdkTypeName() = sdkDependencyItem.sdkType
override fun <R : Any?> accept(policy: RootPolicy<R>, initialValue: R?): R? = policy.visitJdkOrderEntry(this, initialValue)
override fun cloneEntry(rootModel: ModifiableRootModel,
projectRootManager: ProjectRootManagerImpl,
filePointerManager: VirtualFilePointerManager
): OrderEntry = SdkOrderEntryBridge(rootModel as ModuleRootModelBridge, index, sdkDependencyItem.copy())
override fun isSynthetic(): Boolean = true
}
internal class InheritedSdkOrderEntryBridge(rootModel: ModuleRootModelBridge, index: Int, item: ModuleDependencyItem.InheritedSdkDependency)
: SdkOrderEntryBaseBridge(rootModel, index, item), InheritedJdkOrderEntry, ClonableOrderEntry {
override val rootProvider: RootProvider?
get() = jdk?.rootProvider
override fun getJdk(): Sdk? = getRootModel().accessor.getProjectSdk(getRootModel().moduleBridge.project)
override fun getJdkName(): String? = getRootModel().accessor.getProjectSdkName(getRootModel().moduleBridge.project)
override fun isValid(): Boolean = jdk != null
override fun getPresentableName() = "< $jdkName >"
override fun <R : Any?> accept(policy: RootPolicy<R>, initialValue: R?): R? = policy.visitInheritedJdkOrderEntry(this, initialValue)
override fun cloneEntry(rootModel: ModifiableRootModel,
projectRootManager: ProjectRootManagerImpl,
filePointerManager: VirtualFilePointerManager
): OrderEntry = InheritedSdkOrderEntryBridge(
rootModel as ModuleRootModelBridge, index, ModuleDependencyItem.InheritedSdkDependency
)
}
internal class ModuleSourceOrderEntryBridge(rootModel: ModuleRootModelBridge, index: Int, item: ModuleDependencyItem.ModuleSourceDependency)
: OrderEntryBridge(rootModel, index, item, null), ModuleSourceOrderEntry, ClonableOrderEntry {
override fun getFiles(type: OrderRootType): Array<out VirtualFile> = if (type == OrderRootType.SOURCES) rootModel.sourceRoots else VirtualFile.EMPTY_ARRAY
override fun getUrls(rootType: OrderRootType): Array<out String> = if (rootType == OrderRootType.SOURCES) rootModel.sourceRootUrls else ArrayUtil.EMPTY_STRING_ARRAY
override fun getPresentableName(): String = ProjectModelBundle.message("project.root.module.source")
override fun <R : Any?> accept(policy: RootPolicy<R>, initialValue: R?): R? =
policy.visitModuleSourceOrderEntry(this, initialValue)
override fun cloneEntry(rootModel: ModifiableRootModel,
projectRootManager: ProjectRootManagerImpl,
filePointerManager: VirtualFilePointerManager
): OrderEntry = ModuleSourceOrderEntryBridge(
rootModel as ModuleRootModelBridge, index, ModuleDependencyItem.ModuleSourceDependency
)
override fun isSynthetic(): Boolean = true
}
| apache-2.0 | e23b52b1c80c9db885dd3c1ef85ba2a0 | 42.476608 | 166 | 0.773757 | 5.202589 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/config/SettingsCategoryDescriptor.kt | 9 | 2404 | package com.intellij.settingsSync.config
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.components.SettingsCategory.*
import com.intellij.settingsSync.SettingsSyncBundle.message
import com.intellij.settingsSync.SettingsSyncSettings
import org.jetbrains.annotations.Nls
import java.util.*
internal class SettingsCategoryDescriptor(
private val category : SettingsCategory,
val secondaryGroup: SettingsSyncSubcategoryGroup? = null
) {
companion object {
private val DESCRIPTORS : List<SettingsCategoryDescriptor> = listOf(
SettingsCategoryDescriptor(UI, SettingsSyncUiGroup()),
SettingsCategoryDescriptor(KEYMAP),
SettingsCategoryDescriptor(CODE),
SettingsCategoryDescriptor(PLUGINS, SettingsSyncPluginsGroup()),
SettingsCategoryDescriptor(TOOLS),
SettingsCategoryDescriptor(SYSTEM),
)
fun listAll() : List<SettingsCategoryDescriptor> {
return DESCRIPTORS
}
}
var isSynchronized: Boolean = true
fun reset() {
isSynchronized = SettingsSyncSettings.getInstance().isCategoryEnabled(category)
if (secondaryGroup != null) {
secondaryGroup.getDescriptors().forEach {
it.isSelected = isSynchronized && SettingsSyncSettings.getInstance().isSubcategoryEnabled(category, it.id)
}
}
}
fun apply() {
if (secondaryGroup != null) {
secondaryGroup.getDescriptors().forEach {
// !isSynchronized not store disabled states individually
SettingsSyncSettings.getInstance().setSubcategoryEnabled(category, it.id, !isSynchronized || it.isSelected)
}
}
SettingsSyncSettings.getInstance().setCategoryEnabled(category, isSynchronized)
}
fun isModified() : Boolean {
if (isSynchronized != SettingsSyncSettings.getInstance().isCategoryEnabled(category)) return true
if (secondaryGroup != null && isSynchronized) {
secondaryGroup.getDescriptors().forEach {
if (it.isSelected != SettingsSyncSettings.getInstance().isSubcategoryEnabled(category, it.id)) return true
}
}
return false
}
val name: @Nls String
get() {
return message("${categoryKey}.name")
}
val description: @Nls String
get() {
return message("${categoryKey}.description")
}
private val categoryKey: String
get() {
return "settings.category." + category.name.lowercase(Locale.getDefault())
}
} | apache-2.0 | 0b4e9b193db3f73fb18c419e74bce3cc | 30.644737 | 115 | 0.729201 | 5.05042 | false | false | false | false |
marcplouhinec/trust-service-reputation | src/main/kotlin/fr/marcsworld/service/impl/DocumentParsingServiceImpl.kt | 1 | 13083 | package fr.marcsworld.service.impl
import fr.marcsworld.enums.AgencyType
import fr.marcsworld.enums.DocumentType
import fr.marcsworld.model.entity.Agency
import fr.marcsworld.model.entity.AgencyName
import fr.marcsworld.model.entity.Document
import fr.marcsworld.service.DocumentParsingService
import fr.marcsworld.utils.ResourceDownloader
import org.apache.pdfbox.io.RandomAccessBuffer
import org.apache.pdfbox.pdfparser.PDFParser
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.text.PDFTextStripper
import org.slf4j.LoggerFactory
import org.springframework.core.io.Resource
import org.springframework.stereotype.Service
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import org.xml.sax.SAXParseException
import java.io.IOException
import java.net.URL
import java.nio.charset.Charset
import javax.xml.XMLConstants
import javax.xml.namespace.NamespaceContext
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathFactory
/**
* Default implementation of [DocumentParsingService].
*
* @author Marc Plouhinec
*/
@Service
class DocumentParsingServiceImpl : DocumentParsingService {
companion object {
val LOGGER = LoggerFactory.getLogger(DocumentParsingServiceImpl::class.java)!!
}
private val namespaceContext = TsStatusListNamespaceContext()
override fun parseTsStatusList(resource: Resource): Agency {
val resourceUrl = resource.url.toString()
LOGGER.debug("Parse the trust service status list: {}", resourceUrl)
// Parse the XML file in memory
val documentByteArray = try {
ResourceDownloader.downloadResource(resource)
} catch (e: Exception) {
LOGGER.warn("Unable to download the document {}: {} - {}", resourceUrl, e.javaClass, e.message)
throw e
}
val documentBuilderFactory = DocumentBuilderFactory.newInstance()
documentBuilderFactory.isNamespaceAware = true
val documentBuilder = documentBuilderFactory.newDocumentBuilder()
val document = try {
documentByteArray.inputStream().buffered().use {
documentBuilder.parse(it)
}
} catch (e: SAXParseException) {
LOGGER.warn("Invalid XML document from {}: {} - ", resourceUrl, e.javaClass, e.message)
throw e
}
// Parse the TRUST_SERVICE_LIST_OPERATOR agency
val topTerritoryCode = evalXPathToString(document, "/v2:TrustServiceStatusList/v2:SchemeInformation/v2:SchemeTerritory/text()")
val topAgency = Agency(
type = AgencyType.TRUST_SERVICE_LIST_OPERATOR,
territoryCode = topTerritoryCode ?: throw IllegalArgumentException("Missing SchemeTerritory."))
topAgency.names = evalXPathToAgencyNames(document, "/v2:TrustServiceStatusList/v2:SchemeInformation/v2:SchemeOperatorName/v2:Name", topAgency)
// Parse the children TRUST_SERVICE_LIST_OPERATOR agencies
val tslPointerNodes = evalXPathToNodes(document, "/v2:TrustServiceStatusList/v2:SchemeInformation/v2:PointersToOtherTSL/v2:OtherTSLPointer" +
"[v2:AdditionalInformation/v2:OtherInformation/additionaltypes:MimeType=\"application/vnd.etsi.tsl+xml\"]")
val otherTsloAgencies = tslPointerNodes
.map {
val childTerritoryCode = evalXPathToString(it, "./v2:AdditionalInformation/v2:OtherInformation/v2:SchemeTerritory/text()")
val agency = Agency(
parentAgency = topAgency,
type = AgencyType.TRUST_SERVICE_LIST_OPERATOR,
territoryCode = childTerritoryCode ?: throw IllegalArgumentException("Missing SchemeTerritory."),
referencedByDocumentUrl = resourceUrl)
agency.names = evalXPathToAgencyNames(it, "./v2:AdditionalInformation/v2:OtherInformation/v2:SchemeOperatorName/v2:Name", agency)
val tslLocation = evalXPathToString(it, "./v2:TSLLocation/text()")
if (tslLocation is String) {
agency.providingDocuments = listOf(Document(
url = tslLocation,
type = DocumentType.TS_STATUS_LIST_XML,
languageCode = "en",
providedByAgency = agency,
referencedByDocumentType = DocumentType.TS_STATUS_LIST_XML))
}
agency
}
val memberStateTsloAgencies = otherTsloAgencies.filter { it.territoryCode != "EU" }
if (topTerritoryCode == "EU") {
val euTsloAgency = otherTsloAgencies.findLast { it.territoryCode == "EU" }
if (euTsloAgency is Agency) {
topAgency.providingDocuments = euTsloAgency.providingDocuments.map {
Document(
url = it.url,
type = it.type,
languageCode = it.languageCode,
providedByAgency = topAgency,
referencedByDocumentType = DocumentType.TS_STATUS_LIST_XML)
}
}
}
// Parse the TRUST_SERVICE_PROVIDER agencies
val tspNodes = evalXPathToNodes(document, "/v2:TrustServiceStatusList/v2:TrustServiceProviderList/v2:TrustServiceProvider")
val childrenTspAgencies = tspNodes.map {
val tspAgency = Agency(
parentAgency = topAgency,
type = AgencyType.TRUST_SERVICE_PROVIDER,
referencedByDocumentUrl = resourceUrl)
tspAgency.names = evalXPathToAgencyNames(it, "./v2:TSPInformation/v2:TSPName/v2:Name", tspAgency)
// Parse the children TRUST_SERVICE agencies
val tspServiceNode = evalXPathToNodes(it, "./v2:TSPServices/v2:TSPService")
tspAgency.childrenAgencies = tspServiceNode.map {
val tsAgency = Agency(
parentAgency = tspAgency,
type = AgencyType.TRUST_SERVICE,
referencedByDocumentUrl = resourceUrl
)
tsAgency.names = evalXPathToAgencyNames(it, "./v2:ServiceInformation/v2:ServiceName/v2:Name", tsAgency)
tsAgency.x509Certificate = evalXPathToString(it, "./v2:ServiceInformation/v2:ServiceDigitalIdentity/v2:DigitalId/v2:X509Certificate")
val tsdUriNodes = evalXPathToNodes(it, "./v2:ServiceInformation/v2:TSPServiceDefinitionURI/v2:URI")
val tsdDocuments = tsdUriNodes.map {
Document(
url = it.textContent,
type = DocumentType.TSP_SERVICE_DEFINITION,
languageCode = it.attributes.getNamedItem("xml:lang").nodeValue ?: throw IllegalArgumentException("Missing @xml:lang."),
providedByAgency = tsAgency,
referencedByDocumentType = DocumentType.TS_STATUS_LIST_XML)
}
val crlUriNodes = evalXPathToNodes(it, "./v2:ServiceInformation/v2:ServiceSupplyPoints/v2:ServiceSupplyPoint")
val crlDocuments = crlUriNodes
.filter { it.textContent.endsWith(".crl") }
.map {
Document(
url = it.textContent,
type = DocumentType.CERTIFICATE_REVOCATION_LIST,
languageCode = "en",
providedByAgency = tsAgency,
referencedByDocumentType = DocumentType.TS_STATUS_LIST_XML)
}
tsAgency.providingDocuments = tsdDocuments + crlDocuments
tsAgency
}
tspAgency
}
topAgency.childrenAgencies = memberStateTsloAgencies + childrenTspAgencies
return topAgency
}
override fun parseTspServiceDefinition(resource: Resource, providerAgency: Agency): List<Document> {
LOGGER.debug("Parse the TSP service definition: {}", resource.url)
val documentByteArray = try {
ResourceDownloader.downloadResource(resource)
} catch (e: Exception) {
LOGGER.warn("Unable to download the document {}: {} - {}", resource.url, e.javaClass, e.message)
throw e
}
val singleLinePdfText = documentByteArray.inputStream().use {
try {
val pdfParser = PDFParser(RandomAccessBuffer(it))
pdfParser.parse()
var singleLinePdfText: String = ""
var pdDocument: PDDocument? = null
try {
pdDocument = PDDocument(pdfParser.document)
val pdfText: String? = PDFTextStripper().getText(pdDocument)
if (pdfText is String) {
singleLinePdfText = pdfText.replace("\n", "").toLowerCase()
}
} finally {
pdfParser.document.close()
pdDocument?.close()
}
singleLinePdfText
} catch (e: IOException) {
// This is not a PDF file, so just try to open it like a text file
documentByteArray.toString(Charset.forName("UTF-8")).replace("\n", "").toLowerCase()
}
}
val crlRegex = """http[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]{1,2000}\.crl""".toRegex()
val matchResults = crlRegex.findAll(singleLinePdfText)
val documentUrls = matchResults
.map { it.value }
.distinct()
return documentUrls
.filter {
// Make sure the URL is valid
try {
URL(it).toURI()
true
} catch (e: Exception) {
LOGGER.error("The URL '{}' extracted from {} is not valid: {} - {}", it, resource.url, e.javaClass, e.message)
false
}
}
.map {
Document(
url = it,
type = DocumentType.CERTIFICATE_REVOCATION_LIST,
languageCode = "en",
providedByAgency = providerAgency,
referencedByDocumentType = DocumentType.TSP_SERVICE_DEFINITION
)
}
.toList()
}
private fun evalXPathToString(node: Node, expression: String): String? {
val xPath = XPathFactory.newInstance().newXPath()
xPath.namespaceContext = namespaceContext
val xPathExpression = xPath.compile(expression)
val value = xPathExpression.evaluate(node, XPathConstants.STRING)
return when (value) {
is String -> value
else -> null
}
}
private fun evalXPathToNodes(node: Node, expression: String): List<Node> {
val xPath = XPathFactory.newInstance().newXPath()
xPath.namespaceContext = namespaceContext
val xPathExpression = xPath.compile(expression)
val nodeSet = xPathExpression.evaluate(node, XPathConstants.NODESET)
return when (nodeSet) {
is NodeList -> (0..nodeSet.length - 1).map { nodeSet.item(it) }
else -> listOf()
}
}
private fun evalXPathToAgencyNames(node: Node, expression: String, agency: Agency): List<AgencyName> {
val nameNodes = evalXPathToNodes(node, expression)
return nameNodes.map {
AgencyName(
agency = agency,
languageCode = it.attributes.getNamedItem("xml:lang").nodeValue ?: throw IllegalArgumentException("Missing @xml:lang."),
name = it.textContent ?: throw IllegalArgumentException("Missing Name text."))
}
}
/**
* [NamespaceContext] compatible with documents of the type [DocumentType.TS_STATUS_LIST_XML].
*/
private class TsStatusListNamespaceContext : NamespaceContext {
override fun getNamespaceURI(prefix: String?): String {
return when (prefix) {
!is String -> throw NullPointerException("Null prefix")
"v2" -> "http://uri.etsi.org/02231/v2#"
"additionaltypes" -> "http://uri.etsi.org/02231/v2/additionaltypes#"
"xml" -> XMLConstants.XML_NS_URI
else -> XMLConstants.NULL_NS_URI
}
}
override fun getPrefix(namespaceURI: String?): String {
throw UnsupportedOperationException()
}
override fun getPrefixes(namespaceURI: String?): MutableIterator<Any?> {
throw UnsupportedOperationException()
}
}
} | mit | 1db5fbce81e9ec57efa40503c832f416 | 44.748252 | 150 | 0.588015 | 4.809926 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/AbstractModule.kt | 1 | 2811 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.insight.generation.GenerationData
import com.demonwav.mcdev.inspection.IsCancelled
import com.intellij.openapi.module.Module
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiReferenceExpression
import javax.swing.Icon
abstract class AbstractModule(protected val facet: MinecraftFacet) {
val module: Module = facet.module
val project = module.project
abstract val moduleType: AbstractModuleType<*>
abstract val type: PlatformType
open val icon: Icon?
get() = moduleType.icon
/**
* By default, this method is provided in the case that a specific platform has no
* listener handling whatsoever, or simply accepts event listeners with random
* classes. This is rather open ended. Primarily this should (platform dependent)
* evaluate to the type (or multiple types) to determine whether the event listener
* is not going to throw an error at runtime.
* @param eventClass The PsiClass of the event listener argument
* *
* @param method The method of the event listener
* *
* @return True if the class is valid or ignored. Returning false may highlight the
* * method as an error and prevent compiling.
*/
open fun isEventClassValid(eventClass: PsiClass, method: PsiMethod?) = false
open fun writeErrorMessageForEventParameter(eventClass: PsiClass, method: PsiMethod) =
"Parameter does not extend the proper Event Class!"
open fun doPreEventGenerate(psiClass: PsiClass, data: GenerationData?) {}
open fun generateEventListenerMethod(
containingClass: PsiClass,
chosenClass: PsiClass,
chosenName: String,
data: GenerationData?
): PsiMethod? = null
open fun shouldShowPluginIcon(element: PsiElement?) = false
open fun checkUselessCancelCheck(expression: PsiMethodCallExpression): IsCancelled? {
return null
}
open fun isStaticListenerSupported(method: PsiMethod) = false
protected fun standardSkip(method: PsiMethod, qualifierExpression: PsiExpression): Boolean {
if (qualifierExpression !is PsiReferenceExpression) {
return false
}
val refResolve = qualifierExpression.resolve() ?: return false
val parameters = method.parameterList.parameters
return parameters.isNotEmpty() && refResolve != parameters[0]
}
open fun init() {}
open fun dispose() {}
}
| mit | 2643d65d94c237785ec006d2bbae0acd | 31.686047 | 96 | 0.724297 | 4.829897 | false | false | false | false |
deso88/TinyGit | src/main/kotlin/hamburg/remme/tinygit/gui/GraphListView.kt | 1 | 6237 | package hamburg.remme.tinygit.gui
import hamburg.remme.tinygit.TinyGit
import hamburg.remme.tinygit.domain.Branch
import hamburg.remme.tinygit.domain.Commit
import hamburg.remme.tinygit.domain.Tag
import hamburg.remme.tinygit.domain.service.BranchService
import hamburg.remme.tinygit.domain.service.CommitLogService
import hamburg.remme.tinygit.domain.service.TagService
import hamburg.remme.tinygit.gui.builder.addClass
import hamburg.remme.tinygit.gui.builder.hbox
import hamburg.remme.tinygit.gui.builder.label
import hamburg.remme.tinygit.gui.builder.vbox
import hamburg.remme.tinygit.gui.component.Icons
import hamburg.remme.tinygit.shortDateTimeFormat
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.ListChangeListener
import javafx.collections.ObservableList
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.ListCell
import javafx.scene.control.ListView
import javafx.util.Callback
private const val DEFAULT_STYLE_CLASS = "graph-list-view"
private const val COMMIT_STYLE_CLASS = "commitId"
private const val DATE_STYLE_CLASS = "date"
private const val BRANCHES_STYLE_CLASS = "branches"
private const val MESSAGE_STYLE_CLASS = "message"
private const val AUTHOR_STYLE_CLASS = "author"
private const val BRANCH_BADGE_STYLE_CLASS = "branch-badge"
private const val TAG_BADGE_STYLE_CLASS = "tag-badge"
private const val DETACHED_STYLE_CLASS = "detached"
private const val CURRENT_STYLE_CLASS = "current"
private const val MAX_LENGTH = 60
/**
* This view has some heavy interaction with [GraphListViewSkin] but is still loosely coupled, as it would
* work with the default list skin, just without Git log graph.
*
* The commits argument should be [CommitLogService.commits] or a filtered view of it.
*
* @todo: skin should not extend ListViewSkin but wrap a [ListView]?!
* @todo: this class should be a control?!
*/
class GraphListView(commits: ObservableList<Commit>) : ListView<Commit>(commits) {
private val branchService = TinyGit.get<BranchService>()
private val tagService = TinyGit.get<TagService>()
init {
addClass(DEFAULT_STYLE_CLASS)
cellFactory = Callback { GraphListCell() }
branchService.head.addListener { _ -> refresh() }
branchService.branches.addListener(ListChangeListener { refresh() })
tagService.tags.addListener(ListChangeListener { refresh() })
}
override fun createDefaultSkin() = GraphListViewSkin(this)
/* --------------------------------------------------
* GRAPH VISIBLE
* -------------------------------------------------- */
private val graphVisibleProperty = SimpleBooleanProperty(true)
var isGraphVisible: Boolean
get() = graphVisibleProperty.get()
set(value) = graphVisibleProperty.set(value)
/* --------------------------------------------------
* GRAPH PADDING
* -------------------------------------------------- */
private val graphWidthProperty = SimpleObjectProperty<Insets>()
var graphWidth: Double
get() = graphWidthProperty.get().left
set(value) = graphWidthProperty.set(Insets(0.0, 0.0, 0.0, value))
/**
* This rather complex list cell is displaying brief information about the commit.
* It will show its ID, commit time, message and author.
*
* It will also display any branch pointing to the commit.
*
* The [ListCell] will have a left padding bound to [GraphListView.graphVisibleProperty] to leave space for the
* graph that is drawn by the [GraphListViewSkin].
*
* @todo branches all have the same color which is not synchronized with the log graph
*/
private inner class GraphListCell : ListCell<Commit>() {
private val commitId = label { addClass(COMMIT_STYLE_CLASS) }
private val date = label {
addClass(DATE_STYLE_CLASS)
graphic = Icons.calendar()
}
private val badges = hbox { addClass(BRANCHES_STYLE_CLASS) }
private val message = label { addClass(MESSAGE_STYLE_CLASS) }
private val author = label {
addClass(AUTHOR_STYLE_CLASS)
graphic = Icons.user()
}
init {
graphic = vbox {
paddingProperty().bind(graphWidthProperty)
+hbox {
alignment = Pos.CENTER_LEFT
+commitId
+date
+badges
}
+hbox {
alignment = Pos.CENTER_LEFT
+message
+author
}
}
}
override fun updateItem(item: Commit?, empty: Boolean) {
super.updateItem(item, empty)
graphic.isVisible = !empty
item?.let { c ->
commitId.text = c.shortId
date.text = c.date.format(shortDateTimeFormat)
badges.children.setAll(tagService.tags.filter { it.id == c.id }.toTagBadges())
badges.children.addAll(branchService.branches.filter { it.id == c.id }.toBranchBadges())
message.text = c.shortMessage
author.text = c.authorName
}
}
private fun List<Branch>.toBranchBadges(): List<Node> {
return map {
label {
addClass(BRANCH_BADGE_STYLE_CLASS)
if (branchService.isDetached(it)) addClass(DETACHED_STYLE_CLASS)
else if (branchService.isHead(it)) addClass(CURRENT_STYLE_CLASS)
text = it.name.abbrev()
graphic = if (branchService.isDetached(it)) Icons.locationArrow() else Icons.codeFork()
}
}
}
private fun List<Tag>.toTagBadges(): List<Node> {
return map {
label {
addClass(TAG_BADGE_STYLE_CLASS)
text = it.name
graphic = Icons.tag()
}
}
}
private fun String.abbrev() = if (length > MAX_LENGTH) "${substring(0, MAX_LENGTH)}..." else this
}
}
| bsd-3-clause | 02e4a6f5b071cc9e7296ddd47c21e22f | 37.98125 | 115 | 0.621613 | 4.63373 | false | false | false | false |
apoi/quickbeer-next | app/src/main/java/quickbeer/android/domain/review/Review.kt | 2 | 1807 | package quickbeer.android.domain.review
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import org.threeten.bp.ZonedDateTime
import quickbeer.android.data.store.Merger
@Parcelize
data class Review(
val id: Int,
val appearance: Int?,
val aroma: Int?,
val flavor: Int?,
val mouthfeel: Int?,
val overall: Int?,
val totalScore: Float?,
val comments: String?,
val timeEntered: ZonedDateTime?,
val timeUpdated: ZonedDateTime?,
val userId: Int?,
val userName: String?,
val city: String?,
val stateId: Int?,
val state: String?,
val countryId: Int?,
val country: String?,
val rateCount: Int?
) : Parcelable {
companion object {
val merger: Merger<Review> = { old, new ->
Review(
id = new.id,
appearance = new.appearance ?: old.appearance,
aroma = new.aroma ?: old.aroma,
flavor = new.flavor ?: old.flavor,
mouthfeel = new.mouthfeel ?: old.mouthfeel,
overall = new.overall ?: old.overall,
totalScore = new.totalScore ?: old.totalScore,
comments = new.comments ?: old.comments,
timeEntered = new.timeEntered ?: old.timeEntered,
timeUpdated = new.timeUpdated ?: old.timeUpdated,
userId = new.userId ?: old.userId,
userName = new.userName ?: old.userName,
city = new.city ?: old.city,
stateId = new.stateId ?: old.stateId,
state = new.state ?: old.state,
countryId = new.countryId ?: old.countryId,
country = new.country ?: old.country,
rateCount = new.rateCount ?: old.rateCount
)
}
}
}
| gpl-3.0 | d6a40ec1f0708f4d9f150987550a46de | 32.462963 | 65 | 0.570006 | 4.333333 | false | false | false | false |
JetBrains/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/kotlin/KotlinPluginBuilder.kt | 1 | 16725 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.kotlin
import com.intellij.util.io.Decompressor
import kotlinx.collections.immutable.persistentListOf
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.BuildTasks
import org.jetbrains.intellij.build.ProductProperties
import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot
import org.jetbrains.intellij.build.dependencies.TeamCityHelper
import org.jetbrains.intellij.build.impl.*
import org.jetbrains.jps.model.library.JpsOrderRootType
import org.jetbrains.jps.model.library.JpsRepositoryLibraryType
import java.nio.file.Path
import java.util.function.BiConsumer
import java.util.regex.Pattern
object KotlinPluginBuilder {
/**
* Module which contains META-INF/plugin.xml
*/
const val MAIN_KOTLIN_PLUGIN_MODULE: String = "kotlin.plugin"
/**
* Version of Kotlin compiler which is used in the cooperative development setup in kt-master && kt-*-master branches
*/
private const val KOTLIN_COOP_DEV_VERSION = "1.7.255"
@SuppressWarnings("SpellCheckingInspection")
val MODULES: List<String> = persistentListOf(
"kotlin.plugin.common",
"kotlin.plugin.k1",
"kotlin.plugin.k2",
"kotlin.base.util",
"kotlin.base.indices",
"kotlin.base.compiler-configuration",
"kotlin.base.plugin",
"kotlin.base.psi",
"kotlin.base.kdoc",
"kotlin.base.platforms",
"kotlin.base.facet",
"kotlin.base.klib",
"kotlin.base.project-structure",
"kotlin.base.external-build-system",
"kotlin.base.scripting",
"kotlin.base.analysis-api-providers",
"kotlin.base.analysis",
"kotlin.base.highlighting",
"kotlin.base.code-insight",
"kotlin.base.jps",
"kotlin.base.analysis-api.utils",
"kotlin.base.compiler-configuration-ui",
"kotlin.base.obsolete-compat",
"kotlin.base.resources",
"kotlin.base.statistics",
"kotlin.base.fe10.plugin",
"kotlin.base.fe10.analysis",
"kotlin.base.fe10.analysis-api-providers",
"kotlin.base.fe10.kdoc",
"kotlin.base.fe10.highlighting",
"kotlin.base.fe10.code-insight",
"kotlin.base.fe10.obsolete-compat",
"kotlin.core",
"kotlin.idea",
"kotlin.fir.frontend-independent",
"kotlin.line-indent-provider",
"kotlin.jvm",
"kotlin.compiler-reference-index",
"kotlin.compiler-plugins.parcelize.common",
"kotlin.compiler-plugins.parcelize.gradle",
"kotlin.compiler-plugins.allopen.common",
"kotlin.compiler-plugins.allopen.gradle",
"kotlin.compiler-plugins.allopen.maven",
"kotlin.compiler-plugins.compiler-plugin-support.common",
"kotlin.compiler-plugins.compiler-plugin-support.gradle",
"kotlin.compiler-plugins.compiler-plugin-support.maven",
"kotlin.compiler-plugins.kapt",
"kotlin.compiler-plugins.kotlinx-serialization.common",
"kotlin.compiler-plugins.kotlinx-serialization.gradle",
"kotlin.compiler-plugins.kotlinx-serialization.maven",
"kotlin.compiler-plugins.noarg.common",
"kotlin.compiler-plugins.noarg.gradle",
"kotlin.compiler-plugins.noarg.maven",
"kotlin.compiler-plugins.sam-with-receiver.common",
"kotlin.compiler-plugins.sam-with-receiver.gradle",
"kotlin.compiler-plugins.sam-with-receiver.maven",
"kotlin.compiler-plugins.assignment.common",
"kotlin.compiler-plugins.assignment.gradle",
"kotlin.compiler-plugins.assignment.maven",
"kotlin.compiler-plugins.lombok.gradle",
"kotlin.compiler-plugins.lombok.maven",
"kotlin.compiler-plugins.scripting",
"kotlin.compiler-plugins.android-extensions-stubs",
"kotlin.completion.api",
"kotlin.completion.impl-shared",
"kotlin.completion.impl-k1",
"kotlin.completion.impl-k2",
"kotlin.maven",
"kotlin.gradle.gradle-tooling",
"kotlin.gradle.gradle",
"kotlin.gradle.code-insight-common",
"kotlin.gradle.gradle-java",
"kotlin.gradle.code-insight-groovy",
"kotlin.native",
"kotlin.grazie",
"kotlin.run-configurations.jvm",
"kotlin.run-configurations.junit",
"kotlin.run-configurations.junit-fe10",
"kotlin.run-configurations.testng",
"kotlin.formatter",
"kotlin.repl",
"kotlin.git",
"kotlin.injection",
"kotlin.scripting",
"kotlin.coverage",
"kotlin.ml-completion",
"kotlin.copyright",
"kotlin.spellchecker",
"kotlin.jvm-decompiler",
"kotlin.properties",
"kotlin.j2k.post-processing",
"kotlin.j2k.idea",
"kotlin.j2k.old",
"kotlin.j2k.old.post-processing",
"kotlin.j2k.new",
"kotlin.plugin-updater",
"kotlin.preferences",
"kotlin.project-configuration",
"kotlin.project-wizard.cli",
"kotlin.project-wizard.core",
"kotlin.project-wizard.idea",
"kotlin.project-wizard.idea-k1",
"kotlin.project-wizard.maven",
"kotlin.project-wizard.gradle",
"kotlin.project-wizard.compose",
"kotlin.jvm-debugger.base.util",
"kotlin.jvm-debugger.util",
"kotlin.jvm-debugger.core",
"kotlin.jvm-debugger.core-fe10",
"kotlin.jvm-debugger.evaluation",
"kotlin.jvm-debugger.coroutines",
"kotlin.jvm-debugger.sequence",
"kotlin.jvm-debugger.eval4j",
"kotlin.uast.uast-kotlin-base",
"kotlin.uast.uast-kotlin",
"kotlin.uast.uast-kotlin-idea-base",
"kotlin.uast.uast-kotlin-idea",
"kotlin.i18n",
"kotlin.migration",
"kotlin.inspections",
"kotlin.inspections-fe10",
"kotlin.features-trainer",
"kotlin.base.fir.analysis-api-providers",
"kotlin.base.fir.code-insight",
"kotlin.code-insight.api",
"kotlin.code-insight.utils",
"kotlin.code-insight.intentions-shared",
"kotlin.code-insight.inspections-shared",
"kotlin.code-insight.impl-base",
"kotlin.code-insight.descriptions",
"kotlin.code-insight.intentions-k1",
"kotlin.code-insight.intentions-k2",
"kotlin.code-insight.inspections-k2",
"kotlin.code-insight.k2",
"kotlin.code-insight.override-implement-shared",
"kotlin.code-insight.override-implement-k1",
"kotlin.code-insight.override-implement-k2",
"kotlin.code-insight.live-templates-shared",
"kotlin.code-insight.live-templates-k1",
"kotlin.code-insight.live-templates-k2",
"kotlin.code-insight.postfix-templates-k1",
"kotlin.code-insight.postfix-templates-k2",
"kotlin.code-insight.structural-search-k1",
"kotlin.code-insight.line-markers-shared",
"kotlin.code-insight.line-markers-k2",
"kotlin.fir",
"kotlin.searching.k2",
"kotlin.searching.base",
"kotlin.highlighting",
"kotlin.uast.uast-kotlin-fir",
"kotlin.uast.uast-kotlin-idea-fir",
"kotlin.fir.fir-low-level-api-ide-impl",
"kotlin.navigation",
"kotlin.refactorings.common",
"kotlin.refactorings.k2",
"kotlin.refactorings.rename.k2",
)
@SuppressWarnings("SpellCheckingInspection")
private val LIBRARIES = persistentListOf(
"kotlinc.analysis-api-providers",
"kotlinc.analysis-project-structure",
"kotlinc.high-level-api",
"kotlinc.high-level-api-fe10",
"kotlinc.high-level-api-impl-base",
"kotlinc.kotlin-script-runtime",
"kotlinc.kotlin-scripting-compiler-impl",
"kotlinc.kotlin-scripting-common",
"kotlinc.kotlin-scripting-jvm",
"kotlinc.kotlin-gradle-statistics",
"kotlinc.high-level-api-fir",
"kotlinc.kotlin-compiler-fir",
"kotlinc.low-level-api-fir",
"kotlinc.symbol-light-classes",
)
private val GRADLE_TOOLING_MODULES = persistentListOf(
"kotlin.base.project-model",
"kotlin.gradle.gradle-tooling.impl",
)
private val GRADLE_TOOLING_LIBRARIES = persistentListOf(
"kotlin-gradle-plugin-idea",
"kotlin-gradle-plugin-idea-proto",
"kotlin-tooling-core",
)
private val COMPILER_PLUGINS = persistentListOf(
"kotlinc.android-extensions-compiler-plugin",
"kotlinc.allopen-compiler-plugin",
"kotlinc.noarg-compiler-plugin",
"kotlinc.sam-with-receiver-compiler-plugin",
"kotlinc.assignment-compiler-plugin",
"kotlinc.kotlinx-serialization-compiler-plugin",
"kotlinc.parcelize-compiler-plugin",
"kotlinc.lombok-compiler-plugin",
)
@JvmStatic
fun kotlinPlugin(ultimateSources: KotlinUltimateSources): PluginLayout {
return kotlinPlugin(
kind = KotlinPluginKind.valueOf(System.getProperty("kotlin.plugin.kind", "IJ")),
ultimateSources = ultimateSources,
)
}
// weird groovy bug - remove method once AppCodeProperties will be converted to kotlin
fun kotlinPluginAcKmm(): PluginLayout {
return kotlinPlugin(KotlinPluginKind.AC_KMM, KotlinUltimateSources.WITH_ULTIMATE_MODULES)
}
@JvmStatic
fun kotlinPlugin(kind: KotlinPluginKind, ultimateSources: KotlinUltimateSources): PluginLayout {
return PluginLayout.plugin(MAIN_KOTLIN_PLUGIN_MODULE) { spec ->
spec.directoryName = "Kotlin"
spec.mainJarName = "kotlin-plugin.jar"
for (moduleName in MODULES) {
spec.withModule(moduleName)
}
for (libraryName in LIBRARIES) {
spec.withProjectLibraryUnpackedIntoJar(libraryName, spec.mainJarName)
}
val toolingJarName = "kotlin-gradle-tooling.jar"
for (moduleName in GRADLE_TOOLING_MODULES) {
spec.withModule(moduleName, toolingJarName)
}
for (library in GRADLE_TOOLING_LIBRARIES) {
spec.withProjectLibraryUnpackedIntoJar(library, toolingJarName)
}
for (library in COMPILER_PLUGINS) {
spec.withProjectLibrary(library, LibraryPackMode.STANDALONE_MERGED)
}
if (ultimateSources == KotlinUltimateSources.WITH_ULTIMATE_MODULES && kind == KotlinPluginKind.IJ) {
spec.withModules(persistentListOf(
"kotlin-ultimate.common-native",
//noinspection SpellCheckingInspection
"kotlin-ultimate.javascript.debugger",
"kotlin-ultimate.javascript.nodeJs",
"kotlin-ultimate.ultimate-plugin",
"kotlin-ultimate.ultimate-native",
"kotlin.performanceExtendedPlugin",
))
}
val kotlincKotlinCompilerCommon = "kotlinc.kotlin-compiler-common"
spec.withProjectLibrary(kotlincKotlinCompilerCommon, LibraryPackMode.STANDALONE_MERGED)
spec.withPatch(BiConsumer { patcher, context ->
val library = context.project.libraryCollection.findLibrary(kotlincKotlinCompilerCommon)!!
val jars = library.getFiles(JpsOrderRootType.COMPILED)
if (jars.size != 1) {
throw IllegalStateException("$kotlincKotlinCompilerCommon is expected to have only one jar")
}
consumeDataByPrefix(jars[0].toPath(), "META-INF/extensions/") { name, data ->
patcher.patchModuleOutput(MAIN_KOTLIN_PLUGIN_MODULE, name, data)
}
})
spec.withProjectLibrary("kotlinc.kotlin-compiler-fe10")
spec.withProjectLibrary("kotlinc.kotlin-compiler-ir")
spec.withProjectLibrary("kotlinc.kotlin-jps-plugin-classpath", "jps/kotlin-jps-plugin.jar")
spec.withProjectLibrary("kotlinc.kotlin-stdlib", "kotlinc-lib.jar")
spec.withProjectLibrary("kotlinc.kotlin-jps-common")
//noinspection SpellCheckingInspection
spec.withProjectLibrary("javaslang", LibraryPackMode.STANDALONE_MERGED)
spec.withProjectLibrary("kotlinx-collections-immutable-jvm", LibraryPackMode.STANDALONE_MERGED)
spec.withProjectLibrary("javax-inject", LibraryPackMode.STANDALONE_MERGED)
spec.withGeneratedResources(BiConsumer { targetDir, context ->
val distLibName = "kotlinc.kotlin-dist"
val library = context.project.libraryCollection.findLibrary(distLibName)!!
val jars = library.getFiles(JpsOrderRootType.COMPILED)
if (jars.size != 1) {
throw IllegalStateException("$distLibName is expected to have only one jar")
}
Decompressor.Zip(jars[0]).extract(targetDir.resolve("kotlinc"))
})
spec.withCustomVersion(object : PluginLayout.VersionEvaluator {
override fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext): String {
val ijBuildNumber = Pattern.compile("^(\\d+)\\.([\\d.]+|SNAPSHOT.*)\$").matcher(ideBuildVersion)
if (ijBuildNumber.matches()) {
val major = ijBuildNumber.group(1)
val minor = ijBuildNumber.group(2)
val library = context.project.libraryCollection.libraries
.firstOrNull { it.name.startsWith("kotlinc.kotlin-jps-plugin-classpath") && it.type is JpsRepositoryLibraryType }
val kotlinVersion = library?.asTyped(JpsRepositoryLibraryType.INSTANCE)?.properties?.data?.version ?: KOTLIN_COOP_DEV_VERSION
val version = "${major}-${kotlinVersion}-${kind}${minor}"
context.messages.info("version: $version")
return version
}
// Build number isn't recognized as IJ build number then it means build
// number must be plain Kotlin plugin version (build configuration in kt-branch)
if (ideBuildVersion.contains("IJ")) {
val version = ideBuildVersion.replace("IJ", kind.toString())
context.messages.info("Kotlin plugin IJ version: $version")
return version
}
throw IllegalStateException("Can't parse build number: $ideBuildVersion")
}
})
spec.withPluginXmlPatcher { rawText ->
val sinceBuild = System.getProperty("kotlin.plugin.since")
val untilBuild = System.getProperty("kotlin.plugin.until")
val text = if (sinceBuild != null && untilBuild != null) {
// In kt-branches we have own since and until versions
replace(rawText, "<idea-version.*?\\/>", "<idea-version since-build=\"${sinceBuild}\" until-build=\"${untilBuild}\"/>")
}
else {
rawText
}
when (kind) {
KotlinPluginKind.IJ ->
//noinspection SpellCheckingInspection
replace(
text,
"<!-- IJ/AS-INCOMPATIBLE-PLACEHOLDER -->",
"<incompatible-with>com.intellij.modules.androidstudio</incompatible-with>"
)
KotlinPluginKind.AS ->
//noinspection SpellCheckingInspection
replace(
text,
"<!-- IJ/AS-DEPENDENCY-PLACEHOLDER -->",
"<plugin id=\"com.intellij.modules.androidstudio\"/>"
)
KotlinPluginKind.AC_KMM ->
replace(text, "<plugin id=\"com.intellij.java\"/>", "<plugin id=\"com.intellij.kotlinNative.platformDeps\"/>\n" +
"<plugin id=\"com.intellij.modules.appcode\"/>")
else -> throw IllegalStateException("Unknown kind = $kind")
}
}
if (kind == KotlinPluginKind.IJ && ultimateSources == KotlinUltimateSources.WITH_ULTIMATE_MODULES) {
// TODO KTIJ-11539 change to `System.getenv("TEAMCITY_VERSION") == null` later but make sure
// that `IdeaUltimateBuildTest.testBuild` passes on TeamCity
val skipIfDoesntExist = true
// Use 'DownloadAppCodeDependencies' run configuration to download LLDBFrontend
spec.withBin("../CIDR/cidr-debugger/bin/lldb/linux/bin/LLDBFrontend", "bin/linux", skipIfDoesntExist)
spec.withBin("../CIDR/cidr-debugger/bin/lldb/mac/LLDBFrontend", "bin/macos", skipIfDoesntExist)
spec.withBin("../CIDR/cidr-debugger/bin/lldb/win/x64/bin/LLDBFrontend.exe", "bin/windows", skipIfDoesntExist)
spec.withBin("../CIDR/cidr-debugger/bin/lldb/renderers", "bin/lldb/renderers")
spec.withBin("../mobile-ide/common-native/scripts", "scripts")
}
}
}
private fun replace(oldText: String, regex: String, newText: String): String {
val result = oldText.replaceFirst(Regex(regex), newText)
if (result == oldText) {
if (oldText.contains(newText) && !TeamCityHelper.isUnderTeamCity) {
// Locally e.g. in 'Update IDE from Sources' allow data to be already present
return result
}
throw IllegalStateException("Cannot find '$regex' in '$oldText'")
}
return result
}
suspend fun build(communityHome: BuildDependenciesCommunityRoot, home: Path, properties: ProductProperties) {
val buildContext = BuildContextImpl.createContext(communityHome = communityHome, projectHome = home, productProperties = properties)
BuildTasks.create(buildContext).buildNonBundledPlugins(listOf(MAIN_KOTLIN_PLUGIN_MODULE))
}
enum class KotlinUltimateSources {
WITH_COMMUNITY_MODULES,
WITH_ULTIMATE_MODULES,
}
enum class KotlinPluginKind {
IJ, AS, MI,
// AppCode KMM plugin
AC_KMM {
override fun toString() = "AC"
}
}
}
| apache-2.0 | 731c50ba2d8bfe03c39d4da140af73bc | 38.445755 | 137 | 0.687294 | 4.073307 | false | false | false | false |
JetBrains/intellij-community | platform/platform-api/src/com/intellij/ui/dsl/gridLayout/Constraints.kt | 1 | 3660 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.gridLayout
import com.intellij.ui.dsl.UiDslException
import com.intellij.ui.dsl.checkNonNegative
import com.intellij.ui.dsl.checkPositive
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
enum class HorizontalAlign {
LEFT,
CENTER,
RIGHT,
FILL
}
enum class VerticalAlign {
TOP,
CENTER,
BOTTOM,
FILL
}
@ApiStatus.Experimental
data class Constraints(
/**
* Grid destination
*/
val grid: Grid,
/**
* Cell x coordinate in [grid]
*/
val x: Int,
/**
* Cell y coordinate in [grid]
*/
val y: Int,
/**
* Columns number occupied by the cell
*/
val width: Int = 1,
/**
* Rows number occupied by the cell
*/
val height: Int = 1,
/**
* Horizontal alignment of content inside the cell
*/
val horizontalAlign: HorizontalAlign = HorizontalAlign.LEFT,
/**
* Vertical alignment of content inside the cell
*/
val verticalAlign: VerticalAlign = VerticalAlign.CENTER,
/**
* If true then vertical align is done by baseline:
*
* 1. All cells in the same grid row with [baselineAlign] true, [height] equals 1 and with the same [verticalAlign]
* (except [VerticalAlign.FILL], which doesn't support baseline) are aligned by baseline together
* 2. Sub grids (see [com.intellij.ui.dsl.gridLayout.impl.GridImpl.registerSubGrid]) with only one row and that contain cells only with [VerticalAlign.FILL] and another
* specific [VerticalAlign] (at least one cell without fill align) have own baseline and can be aligned by baseline in parent grid
*/
val baselineAlign: Boolean = false,
/**
* Gaps between grid cell bounds and components visual bounds (visual bounds is component bounds minus [visualPaddings])
*/
val gaps: Gaps = Gaps.EMPTY,
/**
* Gaps between component bounds and its visual bounds. Can be used when component has focus ring outside of
* its usual size. In such case components size is increased on focus size (so focus ring is not clipped)
* and [visualPaddings] should be set to maintain right alignments
*
* 1. Layout manager aligns components by their visual bounds
* 2. Cell size with gaps is calculated as component.bounds + [gaps] - [visualPaddings]
* 3. Cells that contain [JComponent] with own [GridLayout] calculate and update [visualPaddings] automatically.
* To disable this behaviour set [GridLayoutComponentProperty.SUB_GRID_AUTO_VISUAL_PADDINGS] to false
*/
var visualPaddings: Gaps = Gaps.EMPTY,
/**
* All components from the same width group will have the same width equals to maximum width from the group.
* Cannot be used together with [HorizontalAlign.FILL] or for sub-grids (see [GridLayout.addLayoutSubGrid])
*/
val widthGroup: String? = null,
/**
* Component helper for custom behaviour
*/
@ApiStatus.Experimental
val componentHelper: ComponentHelper? = null
) {
init {
checkNonNegative("x", x)
checkNonNegative("y", y)
checkPositive("width", width)
checkPositive("height", height)
if (widthGroup != null && horizontalAlign == HorizontalAlign.FILL) {
throw UiDslException("Width group cannot be used with horizontal align FILL: $widthGroup")
}
}
}
/**
* A helper for custom behaviour for components in cells
*/
@ApiStatus.Experimental
interface ComponentHelper {
/**
* Returns custom baseline or null if default baseline calculation should be used
*
* @see JComponent.getBaseline
*/
fun getBaseline(width: Int, height: Int): Int?
}
| apache-2.0 | bf1bf14534c70e73f9f32e1a5c9466bc | 28.047619 | 170 | 0.710656 | 4.295775 | false | false | false | false |
JetBrains/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/MavenizedStructureWizardStep.kt | 1 | 14575 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.wizard
import com.intellij.ide.IdeBundle
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.installNameGenerators
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ui.DataView
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory.createSingleLocalFileDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.observable.properties.transform
import com.intellij.openapi.observable.properties.map
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.BrowseFolderDescriptor.Companion.withPathToTextConvertor
import com.intellij.openapi.ui.BrowseFolderDescriptor.Companion.withTextToPathConvertor
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.getCanonicalPath
import com.intellij.openapi.ui.getPresentablePath
import com.intellij.openapi.util.io.FileUtil.*
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.SortedComboBoxModel
import com.intellij.ui.layout.*
import java.io.File
import java.nio.file.InvalidPathException
import java.nio.file.Paths
import java.util.Comparator.comparing
import java.util.function.Function
import javax.swing.JList
import javax.swing.JTextField
import javax.swing.ListCellRenderer
abstract class MavenizedStructureWizardStep<Data : Any>(val context: WizardContext) : ModuleWizardStep() {
abstract fun createView(data: Data): DataView<Data>
abstract fun findAllParents(): List<Data>
private val propertyGraph = PropertyGraph()
private val entityNameProperty = propertyGraph.graphProperty(::suggestName)
private val locationProperty = propertyGraph.graphProperty { suggestLocationByName() }
private val parentProperty = propertyGraph.graphProperty(::suggestParentByLocation)
private val groupIdProperty = propertyGraph.graphProperty(::suggestGroupIdByParent)
private val artifactIdProperty = propertyGraph.graphProperty(::suggestArtifactIdByName)
private val versionProperty = propertyGraph.graphProperty(::suggestVersionByParent)
var entityName by entityNameProperty.map { it.trim() }
var location by locationProperty
var parent by parentProperty
var groupId by groupIdProperty.map { it.trim() }
var artifactId by artifactIdProperty.map { it.trim() }
var version by versionProperty.map { it.trim() }
val parents by lazy { parentsData.map(::createView) }
val parentsData by lazy { findAllParents() }
var parentData: Data?
get() = DataView.getData(parent)
set(value) {
parent = if (value == null) EMPTY_VIEW else createView(value)
}
init {
entityNameProperty.dependsOn(locationProperty, ::suggestNameByLocation)
entityNameProperty.dependsOn(artifactIdProperty, ::suggestNameByArtifactId)
parentProperty.dependsOn(locationProperty, ::suggestParentByLocation)
locationProperty.dependsOn(parentProperty) { suggestLocationByParentAndName() }
locationProperty.dependsOn(entityNameProperty) { suggestLocationByParentAndName() }
groupIdProperty.dependsOn(parentProperty, ::suggestGroupIdByParent)
artifactIdProperty.dependsOn(entityNameProperty, ::suggestArtifactIdByName)
versionProperty.dependsOn(parentProperty, ::suggestVersionByParent)
}
private val contentPanel by lazy {
panel {
if (!context.isCreatingNewProject) {
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.parent.label")) {
val presentationName = Function<DataView<Data>, String> { it.presentationName }
val parentComboBoxModel = SortedComboBoxModel(comparing(presentationName, String.CASE_INSENSITIVE_ORDER))
parentComboBoxModel.add(EMPTY_VIEW)
parentComboBoxModel.addAll(parents)
comboBox(parentComboBoxModel, parentProperty, renderer = getParentRenderer())
}
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.label")) {
textField(entityNameProperty)
.withValidationOnApply { validateName() }
.withValidationOnInput { validateName() }
.constraints(pushX)
.focused()
installNameGenerators(getBuilderId(), entityNameProperty)
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.location.label")) {
val fileChooserDescriptor = createSingleLocalFileDescriptor()
.withFileFilter { it.isDirectory }
.withPathToTextConvertor(::getPresentablePath)
.withTextToPathConvertor(::getCanonicalPath)
val title = IdeBundle.message("title.select.project.file.directory", context.presentationName)
val property = locationProperty.transform(::getPresentablePath, ::getCanonicalPath)
textFieldWithBrowseButton(property, title, context.project, fileChooserDescriptor)
.withValidationOnApply { validateLocation() }
.withValidationOnInput { validateLocation() }
}
hideableRow(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.coordinates.title")) {
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.label")) {
textField(groupIdProperty)
.withValidationOnApply { validateGroupId() }
.withValidationOnInput { validateGroupId() }
.comment(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.help"))
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.label")) {
textField(artifactIdProperty)
.withValidationOnApply { validateArtifactId() }
.withValidationOnInput { validateArtifactId() }
.comment(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.help", context.presentationName))
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.version.label")) {
textField(versionProperty)
.withValidationOnApply { validateVersion() }
.withValidationOnInput { validateVersion() }
}
}
}.apply {
registerValidators(context.disposable)
}
}
protected open fun getBuilderId(): String? = null
override fun getPreferredFocusedComponent() = contentPanel.preferredFocusedComponent
override fun getComponent() = contentPanel
override fun updateStep() = (preferredFocusedComponent as JTextField).selectAll()
private fun getParentRenderer(): ListCellRenderer<DataView<Data>?> {
return object : SimpleListCellRenderer<DataView<Data>?>() {
override fun customize(list: JList<out DataView<Data>?>,
value: DataView<Data>?,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
val view = value ?: EMPTY_VIEW
text = view.presentationName
icon = DataView.getIcon(view)
}
}
}
protected open fun suggestName(): String {
val projectFileDirectory = File(context.projectFileDirectory)
val moduleNames = findAllModules().map { it.name }.toSet()
return createSequentFileName(projectFileDirectory, "untitled", "") {
!it.exists() && it.name !in moduleNames
}
}
protected fun findAllModules(): List<Module> {
val project = context.project ?: return emptyList()
val moduleManager = ModuleManager.getInstance(project)
return moduleManager.modules.toList()
}
protected open fun suggestNameByLocation(): String {
return File(location).name
}
protected open fun suggestNameByArtifactId(): String {
return artifactId
}
protected open fun suggestLocationByParentAndName(): String {
if (!parent.isPresent) return suggestLocationByName()
return join(parent.location, entityName)
}
protected open fun suggestLocationByName(): String {
return join(context.projectFileDirectory, entityName)
}
protected open fun suggestParentByLocation(): DataView<Data> {
val location = location
return parents.find { isAncestor(it.location, location, true) } ?: EMPTY_VIEW
}
protected open fun suggestGroupIdByParent(): String {
return parent.groupId
}
protected open fun suggestArtifactIdByName(): String {
return entityName
}
protected open fun suggestVersionByParent(): String {
return parent.version
}
override fun validate(): Boolean {
return contentPanel.validateCallbacks
.asSequence()
.mapNotNull { it() }
.all { it.okEnabled }
}
protected open fun ValidationInfoBuilder.validateGroupId() = superValidateGroupId()
protected fun ValidationInfoBuilder.superValidateGroupId(): ValidationInfo? {
if (groupId.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateArtifactId() = superValidateArtifactId()
protected fun ValidationInfoBuilder.superValidateArtifactId(): ValidationInfo? {
if (artifactId.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateVersion() = superValidateVersion()
private fun ValidationInfoBuilder.superValidateVersion(): ValidationInfo? {
if (version.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.version.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateName() = superValidateName()
protected fun ValidationInfoBuilder.superValidateName(): ValidationInfo? {
if (entityName.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
val moduleNames = findAllModules().map { it.name }.toSet()
if (entityName in moduleNames) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.entity.name.exists.error",
context.presentationName.capitalize(), entityName)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateLocation() = superValidateLocation()
private fun ValidationInfoBuilder.superValidateLocation(): ValidationInfo? {
val location = location
if (location.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.location.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
val locationPath = try {
Paths.get(location)
}
catch (ex: InvalidPathException) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.invalid", ex.reason)
return error(message)
}
for (project in ProjectManager.getInstance().openProjects) {
if (ProjectUtil.isSameProject(locationPath, project)) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.already.taken.error", project.name)
return error(message)
}
}
val file = locationPath.toFile()
if (file.exists()) {
if (!file.canWrite()) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.not.writable.error")
return error(message)
}
val children = file.list()
if (children == null) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.file.not.directory.error")
return error(message)
}
if (!ApplicationManager.getApplication().isUnitTestMode) {
if (children.isNotEmpty()) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.not.empty.warning")
return warning(message)
}
}
}
return null
}
override fun updateDataModel() {
val location = location
context.projectName = entityName
context.setProjectFileDirectory(location)
createDirectory(File(location))
updateProjectData()
}
abstract fun updateProjectData()
companion object {
private val EMPTY_VIEW = object : DataView<Nothing>() {
override val data: Nothing get() = throw UnsupportedOperationException()
override val location: String = ""
override val icon: Nothing get() = throw UnsupportedOperationException()
override val presentationName: String = "<None>"
override val groupId: String = "org.example"
override val version: String = "1.0-SNAPSHOT"
override val isPresent: Boolean = false
}
}
}
| apache-2.0 | 3e3ef76f99cd709387e5ad02e7e4919b | 43.846154 | 140 | 0.73036 | 5.323229 | false | false | false | false |
StepicOrg/stepik-android | model/src/main/java/org/stepik/android/model/Section.kt | 1 | 2151 | package org.stepik.android.model
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import ru.nobird.app.core.model.Identifiable
import java.util.Date
@Parcelize
data class Section(
@SerializedName("id")
override val id: Long = 0,
@SerializedName("course")
val course: Long = 0, // course id
@SerializedName("units")
val units: List<Long> = emptyList(),
@SerializedName("position")
val position: Int = 0,
@SerializedName("progress")
override val progress: String? = null,
@SerializedName("title")
val title: String? = null,
@SerializedName("slug")
val slug: String? = null,
@SerializedName("begin_date")
val beginDate: Date? = null,
@SerializedName("end_date")
val endDate: Date? = null,
@SerializedName("soft_deadline")
val softDeadline: Date? = null,
@SerializedName("hard_deadline")
val hardDeadline: Date? = null,
@SerializedName("create_date")
val createDate: Date? = null,
@SerializedName("update_date")
val updateDate: Date? = null,
@SerializedName("grading_policy")
val gradingPolicy: String? = null,
@SerializedName("is_active")
val isActive: Boolean = false,
@SerializedName("actions")
val actions: Actions? = null,
@SerializedName("is_exam")
val isExam: Boolean = false,
@SerializedName("exam_duration_minutes")
val examDurationMinutes: Int? = null,
@SerializedName("exam_session")
val examSession: Long? = null,
@SerializedName("proctor_session")
val proctorSession: Long? = null,
@SerializedName("is_proctoring_can_be_scheduled")
val isProctoringCanBeScheduled: Boolean = false,
@SerializedName("discounting_policy")
val discountingPolicy: DiscountingPolicyType? = null,
@SerializedName("is_requirement_satisfied")
val isRequirementSatisfied: Boolean = true,
@SerializedName("required_section")
val requiredSection: Long = 0, //id of required section
@SerializedName("required_percent")
val requiredPercent: Int = 0
) : Parcelable, Progressable, Identifiable<Long> | apache-2.0 | b0bba4329a02de2e273859bb39d6ea8b | 32.107692 | 59 | 0.695026 | 4.081594 | false | false | false | false |
ptkNktq/AndroidNotificationNotifier | AndroidApp/domain/src/main/java/me/nya_n/notificationnotifier/domain/usecase/SaveAddressUseCase.kt | 1 | 942 | package me.nya_n.notificationnotifier.domain.usecase
import androidx.core.text.isDigitsOnly
import me.nya_n.notificationnotifier.data.repository.UserSettingRepository
import me.nya_n.notificationnotifier.model.AppException
/**
* IPアドレスを保存する
*/
class SaveAddressUseCase(
private val userSettingRepository: UserSettingRepository
) {
operator fun invoke(address: String?): Result<Unit> {
val addr = (address ?: "").split(":")
if (addr.size != 2
|| addr[0].isEmpty()
|| !(addr[1].isNotEmpty() && addr[1].isDigitsOnly())
) {
return Result.failure(AppException.InvalidAddrException())
}
val setting = userSettingRepository.getUserSetting()
.copy(
host = addr[0],
port = addr[1].toInt()
)
userSettingRepository.saveUserSetting(setting)
return Result.success(Unit)
}
} | mit | 04d3b7cafaf94b5e0e7852711ca0eed8 | 30.896552 | 74 | 0.633117 | 4.297674 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/State.kt | 2 | 8409 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.advertiser.KnownExtensionsService
import com.intellij.ide.plugins.advertiser.PluginData
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.fileTypes.FileNameMatcher
import com.intellij.openapi.fileTypes.FileTypeFactory
import com.intellij.openapi.fileTypes.PlainTextLikeFileType
import com.intellij.openapi.fileTypes.ex.DetectedByContentFileType
import com.intellij.openapi.fileTypes.ex.FakeFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.mapSmartSet
import com.intellij.util.containers.orNull
import com.intellij.util.xmlb.annotations.Tag
import com.intellij.util.xmlb.annotations.XMap
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
internal data class PluginAdvertiserExtensionsData(
// Either extension or file name. Depends on which of the two properties has more priority for advertising plugins for this specific file.
val extensionOrFileName: String,
val plugins: Set<PluginData>,
)
@State(
name = "PluginAdvertiserExtensions",
storages = [Storage(StoragePathMacros.CACHE_FILE, roamingType = RoamingType.DISABLED)]
)
@Service(Service.Level.APP)
internal class PluginAdvertiserExtensionsStateService : SimplePersistentStateComponent<PluginAdvertiserExtensionsStateService.State>(
State()
) {
@Tag("pluginAdvertiserExtensions")
class State : BaseState() {
@get:XMap
val plugins by linkedMap<String, PluginData>()
operator fun set(fileNameOrExtension: String, descriptor: PluginDescriptor) {
plugins[fileNameOrExtension] = PluginData(descriptor)
// no need to waste time to check that map is really changed - registerLocalPlugin is not called often after start-up,
// so, mod count will be not incremented too often
incrementModificationCount()
}
operator fun get(fileNameOrExtension: String): PluginAdvertiserExtensionsData? {
return plugins[fileNameOrExtension]?.let {
PluginAdvertiserExtensionsData(fileNameOrExtension, setOf(it))
}
}
}
companion object {
private val LOG = logger<PluginAdvertiserExtensionsStateService>()
@JvmStatic
val instance
get() = service<PluginAdvertiserExtensionsStateService>()
@JvmStatic
fun getFullExtension(file: VirtualFile): String? = file.extension?.let { "*.$it" }
private fun requestCompatiblePlugins(
extensionOrFileName: String,
dataSet: Set<PluginData>,
): Set<PluginData> {
if (dataSet.isEmpty()) {
LOG.debug("No features for extension $extensionOrFileName")
return emptySet()
}
val pluginIdsFromMarketplace = MarketplaceRequests.Instance
.getLastCompatiblePluginUpdate(dataSet.mapSmartSet { it.pluginId })
.map { it.pluginId }
.toSet()
val plugins = dataSet
.asSequence()
.filter {
it.isFromCustomRepository
|| it.isBundled
|| pluginIdsFromMarketplace.contains(it.pluginIdString)
}.toSet()
LOG.debug {
if (plugins.isEmpty())
"No plugins for extension $extensionOrFileName"
else
"Found following plugins for '${extensionOrFileName}': ${plugins.joinToString { it.pluginIdString }}"
}
return plugins
}
@Suppress("HardCodedStringLiteral")
private fun createUnknownExtensionFeature(extensionOrFileName: String) = UnknownFeature(
FileTypeFactory.FILE_TYPE_FACTORY_EP.name,
"File Type",
extensionOrFileName,
extensionOrFileName,
)
private fun findEnabledPlugin(plugins: Set<String>): IdeaPluginDescriptor? {
return if (plugins.isNotEmpty())
PluginManagerCore.getLoadedPlugins().find {
it.isEnabled && plugins.contains(it.pluginId.idString)
}
else
null
}
}
private val cache = Caffeine
.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build<String, Optional<PluginAdvertiserExtensionsData>>()
fun createExtensionDataProvider(project: Project) = ExtensionDataProvider(project)
fun registerLocalPlugin(matcher: FileNameMatcher, descriptor: PluginDescriptor) {
state[matcher.presentableString] = descriptor
}
fun updateCache(extensionOrFileName: String): Boolean {
LOG.assertTrue(!ApplicationManager.getApplication().isReadAccessAllowed)
LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread)
if (cache.getIfPresent(extensionOrFileName) != null) {
return false
}
val knownExtensions = KnownExtensionsService.instance.extensions
if (knownExtensions == null) {
LOG.debug("No known extensions loaded")
return false
}
val compatiblePlugins = requestCompatiblePlugins(
extensionOrFileName,
knownExtensions[extensionOrFileName],
)
val optionalData = if (compatiblePlugins.isEmpty())
Optional.empty()
else
Optional.of(PluginAdvertiserExtensionsData(extensionOrFileName, compatiblePlugins))
cache.put(extensionOrFileName, optionalData)
return true
}
inner class ExtensionDataProvider(private val project: Project) {
private val unknownFeaturesCollector get() = UnknownFeaturesCollector.getInstance(project)
private val enabledExtensionOrFileNames = Collections.newSetFromMap<String>(ConcurrentHashMap())
fun ignoreExtensionOrFileNameAndInvalidateCache(extensionOrFileName: String) {
unknownFeaturesCollector.ignoreFeature(createUnknownExtensionFeature(extensionOrFileName))
cache.invalidate(extensionOrFileName)
}
fun addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName: String) {
enabledExtensionOrFileNames.add(extensionOrFileName)
cache.invalidate(extensionOrFileName)
}
fun requestExtensionData(file: VirtualFile): PluginAdvertiserExtensionsData? {
val fullExtension = getFullExtension(file)
if (fullExtension != null && isIgnored(fullExtension)) {
LOG.debug("Extension '$fullExtension' is ignored in project '${project.name}'")
return null
}
val fileName = file.name
if (isIgnored(fileName)) {
LOG.debug("File '$fileName' is ignored in project '${project.name}'")
return null
}
val fileType = file.fileType
if (fullExtension == null && fileType is FakeFileType) {
return null
}
state[fileName]?.let {
return it
}
fullExtension?.let { state[it] }?.let {
return it
}
val knownExtensions = KnownExtensionsService.instance.extensions
if (knownExtensions == null) {
LOG.debug("No known extensions loaded")
return null
}
val optionalData = if (fileType is PlainTextLikeFileType
|| fileType is DetectedByContentFileType) {
fullExtension?.let { cache.getIfPresent(it) }
?: cache.getIfPresent(fileName)
}
else {
val plugin = findEnabledPlugin(knownExtensions[fileName].map { it.pluginIdString }.toSet())
LOG.debug {
val suffix = plugin?.let { "by fileName via '${it.name}'(id: '${it.pluginId}') plugin" }
?: "therefore looking only for plugins exactly matching fileName"
"File '$fileName' (type: '$fileType') is already supported $suffix"
}
if (plugin != null) null else cache.getIfPresent(fileName)
}
return optionalData?.orNull()
}
private fun isIgnored(extensionOrFileName: String): Boolean {
return enabledExtensionOrFileNames.contains(extensionOrFileName)
|| unknownFeaturesCollector.isIgnored(createUnknownExtensionFeature(extensionOrFileName))
}
}
}
| apache-2.0 | b6b3c39bf78641f4a2e44511afbf6d8a | 34.782979 | 140 | 0.724938 | 5.017303 | false | false | false | false |
allotria/intellij-community | platform/configuration-store-impl/src/StateMap.kt | 2 | 6925 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.util.ArrayUtil
import com.intellij.util.SystemProperties
import com.intellij.util.isEmpty
import net.jpountz.lz4.LZ4FrameInputStream
import net.jpountz.lz4.LZ4FrameOutputStream
import org.jdom.Element
import java.io.ByteArrayInputStream
import java.util.*
import java.util.concurrent.atomic.AtomicReferenceArray
private fun archiveState(state: Element): BufferExposingByteArrayOutputStream {
val byteOut = BufferExposingByteArrayOutputStream()
LZ4FrameOutputStream(byteOut, LZ4FrameOutputStream.BLOCKSIZE.SIZE_256KB).use {
serializeElementToBinary(state, it)
}
return byteOut
}
private fun unarchiveState(state: ByteArray): Element {
return LZ4FrameInputStream(ByteArrayInputStream(state)).use {
deserializeElementFromBinary(it)
}
}
private fun getNewByteIfDiffers(key: String, newState: Any, oldState: ByteArray): ByteArray? {
val newBytes: ByteArray
if (newState is Element) {
val byteOut = archiveState(newState)
if (arrayEquals(byteOut.internalBuffer, oldState, byteOut.size())) {
return null
}
newBytes = byteOut.toByteArray()
}
else {
newBytes = newState as ByteArray
if (newBytes.contentEquals(oldState)) {
return null
}
}
val logChangedComponents = SystemProperties.getBooleanProperty("idea.log.changed.components", false)
if (ApplicationManager.getApplication().isUnitTestMode || logChangedComponents ) {
fun stateToString(state: Any) = JDOMUtil.write(state as? Element ?: unarchiveState(state as ByteArray), "\n")
val before = stateToString(oldState)
val after = stateToString(newState)
if (before == after) {
throw IllegalStateException("$key serialization error - serialized are different, but unserialized are equal")
}
else if (logChangedComponents) {
LOG.info("$key ${"=".repeat(80 - key.length)}\nBefore:\n$before\nAfter:\n$after")
}
}
return newBytes
}
fun stateToElement(key: String, state: Any?, newLiveStates: Map<String, Element>? = null): Element? {
if (state is Element) {
return state.clone()
}
else {
return newLiveStates?.get(key) ?: (state as? ByteArray)?.let(::unarchiveState)
}
}
class StateMap private constructor(private val names: Array<String>, private val states: AtomicReferenceArray<Any>) {
override fun toString() = if (this == EMPTY) "EMPTY" else states.toString()
companion object {
internal val EMPTY = StateMap(ArrayUtil.EMPTY_STRING_ARRAY, AtomicReferenceArray(0))
fun fromMap(map: Map<String, Any>): StateMap {
if (map.isEmpty()) {
return EMPTY
}
val names = map.keys.toTypedArray()
if (map !is TreeMap) {
Arrays.sort(names)
}
val states = AtomicReferenceArray<Any>(names.size)
for (i in names.indices) {
states.set(i, map[names[i]])
}
return StateMap(names, states)
}
}
fun toMutableMap(): MutableMap<String, Any> {
val map = HashMap<String, Any>(names.size)
for (i in names.indices) {
map.put(names[i], states.get(i))
}
return map
}
/**
* Sorted by name.
*/
fun keys(): Array<String> = names
fun get(key: String): Any? {
val index = Arrays.binarySearch(names, key)
return if (index < 0) null else states.get(index)
}
fun getElement(key: String, newLiveStates: Map<String, Element>? = null): Element? = stateToElement(key, get(key), newLiveStates)
fun isEmpty(): Boolean = names.isEmpty()
fun hasState(key: String): Boolean = get(key) is Element
fun hasStates(): Boolean {
return !isEmpty() && names.indices.any { states.get(it) is Element }
}
fun compare(key: String, newStates: StateMap, diffs: MutableSet<String>) {
val oldState = get(key)
val newState = newStates.get(key)
if (oldState is Element) {
if (!JDOMUtil.areElementsEqual(oldState as Element?, newState as Element?)) {
diffs.add(key)
}
}
else if (oldState == null) {
if (newState != null) {
diffs.add(key)
}
}
else if (newState == null || getNewByteIfDiffers(key, newState, oldState as ByteArray) != null) {
diffs.add(key)
}
}
fun getState(key: String, archive: Boolean = false): Element? {
val index = names.binarySearch(key)
if (index < 0) {
return null
}
val prev = states.getAndUpdate(index) { state ->
when {
archive && state is Element -> archiveState(state).toByteArray()
!archive && state is ByteArray -> unarchiveState(state)
else -> state
}
}
return prev as? Element
}
fun archive(key: String, state: Element?) {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return
}
states.set(index, state?.let { archiveState(state).toByteArray() })
}
}
fun setStateAndCloneIfNeeded(key: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>? = null): MutableMap<String, Any>? {
val oldState = oldStates.get(key)
if (newState == null || newState.isEmpty()) {
if (oldState == null) {
return null
}
val newStates = oldStates.toMutableMap()
newStates.remove(key)
return newStates
}
newLiveStates?.put(key, newState)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return null
}
}
else if (oldState != null) {
newBytes = getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return null
}
val newStates = oldStates.toMutableMap()
newStates.put(key, newBytes ?: JDOMUtil.internElement(newState))
return newStates
}
// true if updated (not equals to previous state)
internal fun updateState(states: MutableMap<String, Any>, key: String, newState: Element?, newLiveStates: MutableMap<String, Element>? = null): Boolean {
if (newState == null || JDOMUtil.isEmpty(newState)) {
states.remove(key)
return true
}
newLiveStates?.put(key, newState)
val oldState = states.get(key)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return false
}
}
else if (oldState != null) {
newBytes = getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return false
}
states.put(key, newBytes ?: JDOMUtil.internElement(newState))
return true
}
private fun arrayEquals(a: ByteArray, a2: ByteArray, size: Int = a.size): Boolean {
if (a === a2) {
return true
}
return a2.size == size && (0 until size).none { a[it] != a2[it] }
} | apache-2.0 | 291a5d32af1da523186a5b40ae3e353a | 29.377193 | 162 | 0.684477 | 3.968481 | false | false | false | false |
zdary/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/ConstructorCallConstraint.kt | 12 | 2225 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors.inference
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiType
import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula
import com.intellij.psi.impl.source.resolve.graphInference.constraints.TypeCompatibilityConstraint
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression
class ConstructorCallConstraint(private val leftType: PsiType?, private val expression: GrNewExpression) : GrConstraintFormula() {
override fun reduce(session: GroovyInferenceSession, constraints: MutableList<in ConstraintFormula>): Boolean {
val reference = expression.referenceElement ?: return true
val result = reference.advancedResolve()
val clazz = result.element as? PsiClass ?: return true
val contextSubstitutor = result.contextSubstitutor
session.startNestedSession(clazz.typeParameters, contextSubstitutor, expression, result) { nested ->
runConstructorSession(nested)
if (leftType != null) {
val left = nested.substituteWithInferenceVariables(leftType)
if (left != null) {
val classType = nested.substituteWithInferenceVariables(contextSubstitutor.substitute(clazz.type()))
if (classType != null) {
nested.addConstraint(TypeCompatibilityConstraint(left, classType))
}
}
}
nested.repeatInferencePhases()
}
return true
}
private fun runConstructorSession(classSession: GroovyInferenceSession) {
val result = expression.advancedResolve() as? GroovyMethodResult ?: return
val mapping = result.candidate?.argumentMapping ?: return
classSession.startNestedSession(result.element.typeParameters, result.contextSubstitutor, expression, result) {
it.initArgumentConstraints(mapping, classSession.inferenceSubstitution)
it.repeatInferencePhases()
}
}
override fun toString(): String = "${expression.text} -> ${leftType?.presentableText}"
}
| apache-2.0 | 9fe39a7a040d72b1236231c7754553ee | 48.444444 | 140 | 0.765393 | 4.89011 | false | false | false | false |
leafclick/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/JavaUastLanguagePlugin.kt | 1 | 19114 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.java
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.*
import com.intellij.psi.impl.source.javadoc.PsiDocMethodOrFieldRef
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.javadoc.PsiDocToken
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.uast.*
import org.jetbrains.uast.analysis.UastAnalysisPlugin
import org.jetbrains.uast.java.expressions.JavaUAnnotationCallExpression
import org.jetbrains.uast.java.expressions.JavaUNamedExpression
import org.jetbrains.uast.java.expressions.JavaUSynchronizedExpression
class JavaUastLanguagePlugin : UastLanguagePlugin {
override val priority: Int = 0
override fun isFileSupported(fileName: String): Boolean = fileName.endsWith(".java", ignoreCase = true)
override val language: Language
get() = JavaLanguage.INSTANCE
override fun isExpressionValueUsed(element: UExpression): Boolean = when (element) {
is JavaUDeclarationsExpression -> false
is UnknownJavaExpression -> (element.uastParent as? UExpression)?.let { isExpressionValueUsed(it) } ?: false
else -> {
val statement = element.sourcePsi as? PsiStatement
statement != null && statement.parent !is PsiExpressionStatement
}
}
override fun getMethodCallExpression(
element: PsiElement,
containingClassFqName: String?,
methodName: String
): UastLanguagePlugin.ResolvedMethod? {
if (element !is PsiMethodCallExpression) return null
if (element.methodExpression.referenceName != methodName) return null
val callExpression = when (val uElement = convertElementWithParent(element, null)) {
is UCallExpression -> uElement
is UQualifiedReferenceExpression -> uElement.selector as UCallExpression
else -> error("Invalid element type: $uElement")
}
val method = callExpression.resolve() ?: return null
if (containingClassFqName != null) {
val containingClass = method.containingClass ?: return null
if (containingClass.qualifiedName != containingClassFqName) return null
}
return UastLanguagePlugin.ResolvedMethod(callExpression, method)
}
override fun getConstructorCallExpression(
element: PsiElement,
fqName: String
): UastLanguagePlugin.ResolvedConstructor? {
if (element !is PsiNewExpression) return null
val simpleName = fqName.substringAfterLast('.')
if (element.classReference?.referenceName != simpleName) return null
val callExpression = convertElementWithParent(element, null) as? UCallExpression ?: return null
val constructorMethod = element.resolveConstructor() ?: return null
val containingClass = constructorMethod.containingClass ?: return null
if (containingClass.qualifiedName != fqName) return null
return UastLanguagePlugin.ResolvedConstructor(callExpression, constructorMethod, containingClass)
}
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? {
return convertElement(element, parent, elementTypes(requiredType))
}
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? {
if (element is PsiJavaFile) return requiredType.el<UFile> { JavaUFile(element, this) }
return convertElement(element, null, requiredType)
}
@Suppress("UNCHECKED_CAST")
fun <T : UElement> convertElement(element: PsiElement, parent: UElement?, requiredTypes: Array<out Class<out T>>): T? {
val nonEmptyRequiredTypes = requiredTypes.nonEmptyOr(DEFAULT_TYPES_LIST)
if (!canConvert(element.javaClass, requiredTypes)) return null
return (convertDeclaration(element, parent, nonEmptyRequiredTypes)
?: JavaConverter.convertPsiElement(element, parent, nonEmptyRequiredTypes)) as? T
}
override fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? {
return convertElement(element, null, requiredTypes)
}
@Suppress("UNCHECKED_CAST")
override fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>) = when (element) {
is PsiMethodCallExpression ->
JavaConverter.psiMethodCallConversionAlternatives(element,
null,
requiredTypes.nonEmptyOr(DEFAULT_EXPRESSION_TYPES_LIST)) as Sequence<T>
else -> sequenceOf(convertElementWithParent(element, requiredTypes.nonEmptyOr(DEFAULT_TYPES_LIST)) as? T).filterNotNull()
}
private fun convertDeclaration(element: PsiElement,
givenParent: UElement?,
requiredType: Array<out Class<out UElement>>): UElement? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? {
@Suppress("UNCHECKED_CAST")
return fun(): UElement? {
return ctor(element as P, givenParent)
}
}
return with(requiredType) {
when (element) {
is PsiJavaFile -> el<UFile> { JavaUFile(element, this@JavaUastLanguagePlugin) }
is UDeclaration -> el<UDeclaration> { element }
is PsiClass -> el<UClass> {
JavaUClass.create(element, givenParent)
}
is PsiMethod -> el<UMethod> {
JavaUMethod.create(element, this@JavaUastLanguagePlugin, givenParent)
}
is PsiClassInitializer -> el<UClassInitializer>(build(::JavaUClassInitializer))
is PsiEnumConstant -> el<UEnumConstant>(build(::JavaUEnumConstant))
is PsiLocalVariable -> el<ULocalVariable>(build(::JavaULocalVariable))
is PsiParameter -> el<UParameter>(build(::JavaUParameter))
is PsiField -> el<UField>(build(::JavaUField))
is PsiVariable -> el<UVariable>(build(::JavaUVariable))
is PsiAnnotation -> el<UAnnotation>(build(::JavaUAnnotation))
else -> null
}
}
}
override val analysisPlugin: UastAnalysisPlugin?
get() = UastAnalysisPlugin.byLanguage(JavaLanguage.INSTANCE)
}
internal inline fun <reified ActualT : UElement> Class<*>?.el(f: () -> UElement?): UElement? {
return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null
}
internal inline fun <reified ActualT : UElement> Array<out Class<out UElement>>.el(f: () -> UElement?): UElement? {
return if (isAssignableFrom(ActualT::class.java)) f() else null
}
internal inline fun <reified ActualT : UElement> Array<out Class<out UElement>>.expr(f: () -> UExpression?): UExpression? {
return if (isAssignableFrom(ActualT::class.java)) f() else null
}
internal fun Array<out Class<out UElement>>.isAssignableFrom(cls: Class<*>) = any { it.isAssignableFrom(cls) }
internal object JavaConverter {
internal tailrec fun unwrapElements(element: PsiElement?): PsiElement? = when (element) {
is PsiExpressionStatement -> unwrapElements(element.parent)
is PsiParameterList -> unwrapElements(element.parent)
is PsiAnnotationParameterList -> unwrapElements(element.parent)
is PsiModifierList -> unwrapElements(element.parent)
is PsiExpressionList -> unwrapElements(element.parent)
is PsiPackageStatement -> unwrapElements(element.parent)
is PsiImportList -> unwrapElements(element.parent)
is PsiReferenceList -> unwrapElements(element.parent)
is PsiBlockStatement -> unwrapElements(element.parent)
else -> element
}
internal fun convertPsiElement(el: PsiElement,
givenParent: UElement?,
requiredType: Array<out Class<out UElement>> = DEFAULT_TYPES_LIST): UElement? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? {
@Suppress("UNCHECKED_CAST")
return fun(): UElement? {
return ctor(el as P, givenParent)
}
}
return with(requiredType) {
when (el) {
is PsiCodeBlock -> el<UBlockExpression>(build(::JavaUCodeBlockExpression))
is PsiResourceExpression -> convertExpression(el.expression, givenParent, requiredType)
is PsiExpression -> convertExpression(el, givenParent, requiredType)
is PsiStatement -> convertStatement(el, givenParent, requiredType)
is PsiImportStatementBase -> el<UImportStatement>(build(::JavaUImportStatement))
is PsiIdentifier -> el<USimpleNameReferenceExpression> { JavaUSimpleNameReferenceExpression(el, el.text, givenParent) }
?: el<UIdentifier> { LazyParentUIdentifier(el, givenParent) }
is PsiNameValuePair -> el<UNamedExpression>(build(::JavaUNamedExpression))
is PsiArrayInitializerMemberValue -> el<UCallExpression>(build(::JavaAnnotationArrayInitializerUCallExpression))
is PsiTypeElement -> el<UTypeReferenceExpression>(build(::JavaUTypeReferenceExpression))
is PsiJavaCodeReferenceElement -> convertReference(el, givenParent, requiredType)
is PsiAnnotation -> el.takeIf { PsiTreeUtil.getParentOfType(it, PsiAnnotationMemberValue::class.java, true) != null }?.let {
el<UExpression> { JavaUAnnotationCallExpression(it, givenParent) }
}
is PsiComment -> el<UComment>(build(::UComment))
is PsiDocToken -> el<USimpleNameReferenceExpression> { el.takeIf { it.tokenType == JavaDocTokenType.DOC_TAG_VALUE_TOKEN }?.let {
val methodOrFieldRef = el.parent as? PsiDocMethodOrFieldRef ?: return@let null
JavaUSimpleNameReferenceExpression(el, el.text, givenParent, methodOrFieldRef.reference) }
}
is PsiCatchSection -> el<UCatchClause>(build(::JavaUCatchClause))
else -> null
}
}
}
internal fun convertBlock(block: PsiCodeBlock, parent: UElement?): UBlockExpression = JavaUCodeBlockExpression(block, parent)
internal fun convertReference(reference: PsiJavaCodeReferenceElement,
givenParent: UElement?,
requiredType: Array<out Class<out UElement>> = DEFAULT_TYPES_LIST): UExpression? {
return with(requiredType) {
if (reference.isQualified) {
expr<UQualifiedReferenceExpression> { JavaUQualifiedReferenceExpression(reference, givenParent) }
}
else {
val name = reference.referenceName ?: "<error name>"
expr<USimpleNameReferenceExpression> { JavaUSimpleNameReferenceExpression(reference, name, givenParent, reference) }
}
}
}
internal fun convertExpression(el: PsiExpression,
givenParent: UElement?,
requiredType: Array<out Class<out UElement>> = DEFAULT_EXPRESSION_TYPES_LIST): UExpression? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? {
@Suppress("UNCHECKED_CAST")
return fun(): UExpression? {
return ctor(el as P, givenParent)
}
}
return with(requiredType) {
when (el) {
is PsiAssignmentExpression -> expr<UBinaryExpression>(build(::JavaUAssignmentExpression))
is PsiConditionalExpression -> expr<UIfExpression>(build(::JavaUTernaryIfExpression))
is PsiNewExpression -> {
if (el.anonymousClass != null)
expr<UObjectLiteralExpression>(build(::JavaUObjectLiteralExpression))
else
expr<UCallExpression>(build(::JavaConstructorUCallExpression))
}
is PsiMethodCallExpression -> psiMethodCallConversionAlternatives(el, givenParent, requiredType).firstOrNull()
is PsiArrayInitializerExpression -> expr<UCallExpression>(build(::JavaArrayInitializerUCallExpression))
is PsiBinaryExpression -> expr<UBinaryExpression>(build(::JavaUBinaryExpression))
// Should go after PsiBinaryExpression since it implements PsiPolyadicExpression
is PsiPolyadicExpression -> expr<UPolyadicExpression>(build(::JavaUPolyadicExpression))
is PsiParenthesizedExpression -> expr<UParenthesizedExpression>(build(::JavaUParenthesizedExpression))
is PsiPrefixExpression -> expr<UPrefixExpression>(build(::JavaUPrefixExpression))
is PsiPostfixExpression -> expr<UPostfixExpression>(build(::JavaUPostfixExpression))
is PsiLiteralExpressionImpl -> expr<JavaULiteralExpression>(build(::JavaULiteralExpression))
is PsiMethodReferenceExpression -> expr<UCallableReferenceExpression>(build(::JavaUCallableReferenceExpression))
is PsiReferenceExpression -> convertReference(el, givenParent, requiredType)
is PsiThisExpression -> expr<UThisExpression>(build(::JavaUThisExpression))
is PsiSuperExpression -> expr<USuperExpression>(build(::JavaUSuperExpression))
is PsiInstanceOfExpression -> expr<UBinaryExpressionWithType>(build(::JavaUInstanceCheckExpression))
is PsiTypeCastExpression -> expr<UBinaryExpressionWithType>(build(::JavaUTypeCastExpression))
is PsiClassObjectAccessExpression -> expr<UClassLiteralExpression>(build(::JavaUClassLiteralExpression))
is PsiArrayAccessExpression -> expr<UArrayAccessExpression>(build(::JavaUArrayAccessExpression))
is PsiLambdaExpression -> expr<ULambdaExpression>(build(::JavaULambdaExpression))
is PsiSwitchExpression -> expr<USwitchExpression>(build(::JavaUSwitchExpression))
else -> expr<UExpression>(build(::UnknownJavaExpression))
}
}
}
internal fun psiMethodCallConversionAlternatives(element: PsiMethodCallExpression,
givenParent: UElement?,
requiredTypes: Array<out Class<out UElement>>): Sequence<UExpression> {
if (element.methodExpression.qualifierExpression == null) {
return sequenceOf(requiredTypes.expr<UCallExpression> { JavaUCallExpression(element, givenParent) }).filterNotNull()
}
if (!requiredTypes.isAssignableFrom(UQualifiedReferenceExpression::class.java) &&
!requiredTypes.isAssignableFrom(UCallExpression::class.java)) return emptySequence()
val expr = JavaUCompositeQualifiedExpression(element, givenParent).apply {
receiverInitializer = {
convertOrEmpty(element.methodExpression.qualifierExpression!!, this@apply)
}
selector = JavaUCallExpression(element, this@apply)
}
val results = sequenceOf(expr, expr.selector)
return requiredTypes.asSequence().flatMap { required -> results.filter { required.isInstance(it) } }.distinct()
}
internal fun convertStatement(el: PsiStatement,
givenParent: UElement?,
requiredType: Array<out Class<out UElement>> = DEFAULT_EXPRESSION_TYPES_LIST): UExpression? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? {
@Suppress("UNCHECKED_CAST")
return fun(): UExpression? {
return ctor(el as P, givenParent)
}
}
return with(requiredType) {
when (el) {
is PsiDeclarationStatement -> expr<UDeclarationsExpression> {
convertDeclarations(el.declaredElements, givenParent ?: unwrapElements(el.parent).toUElement())
}
is PsiExpressionListStatement -> expr<UDeclarationsExpression> {
convertDeclarations(el.expressionList.expressions, givenParent ?: unwrapElements(el.parent).toUElement())
}
is PsiBlockStatement -> expr<UBlockExpression>(build(::JavaUBlockExpression))
is PsiLabeledStatement -> expr<ULabeledExpression>(build(::JavaULabeledExpression))
is PsiExpressionStatement -> convertExpression(el.expression, givenParent, requiredType)
is PsiIfStatement -> expr<UIfExpression>(build(::JavaUIfExpression))
is PsiSwitchStatement -> expr<USwitchExpression>(build(::JavaUSwitchExpression))
is PsiWhileStatement -> expr<UWhileExpression>(build(::JavaUWhileExpression))
is PsiDoWhileStatement -> expr<UDoWhileExpression>(build(::JavaUDoWhileExpression))
is PsiForStatement -> expr<UForExpression>(build(::JavaUForExpression))
is PsiForeachStatement -> expr<UForEachExpression>(build(::JavaUForEachExpression))
is PsiBreakStatement -> expr<UBreakExpression>(build(::JavaUBreakExpression))
is PsiYieldStatement -> expr<UYieldExpression> { JavaUYieldExpression(el, el.expression, givenParent) }
is PsiContinueStatement -> expr<UContinueExpression>(build(::JavaUContinueExpression))
is PsiReturnStatement -> expr<UReturnExpression>(build(::JavaUReturnExpression))
is PsiAssertStatement -> expr<UCallExpression>(build(::JavaUAssertExpression))
is PsiThrowStatement -> expr<UThrowExpression>(build(::JavaUThrowExpression))
is PsiSynchronizedStatement -> expr<UBlockExpression>(build(::JavaUSynchronizedExpression))
is PsiTryStatement -> expr<UTryExpression>(build(::JavaUTryExpression))
is PsiEmptyStatement -> expr<UExpression> { UastEmptyExpression(el.parent?.toUElement()) }
is PsiSwitchLabelStatementBase -> expr<UExpression> {
when (givenParent) {
is JavaUSwitchEntryList -> givenParent.findUSwitchEntryForLabel(el)
null -> PsiTreeUtil.getParentOfType(el, PsiSwitchBlock::class.java)?.let {
JavaUSwitchExpression(it, null).body.findUSwitchEntryForLabel(el)
}
else -> null
}
}
else -> expr<UExpression>(build(::UnknownJavaExpression))
}
}
}
private fun convertDeclarations(elements: Array<out PsiElement>, parent: UElement?): UDeclarationsExpression {
return JavaUDeclarationsExpression(parent).apply {
val declarations = mutableListOf<UDeclaration>()
for (element in elements) {
if (element is PsiVariable) {
declarations += JavaUVariable.create(element, this)
}
else if (element is PsiClass) {
declarations += JavaUClass.create(element, this)
}
}
this.declarations = declarations
}
}
internal fun convertOrEmpty(statement: PsiStatement?, parent: UElement?): UExpression =
statement?.let { convertStatement(it, parent) } ?: UastEmptyExpression(parent)
internal fun convertOrEmpty(expression: PsiExpression?, parent: UElement?): UExpression =
expression?.let { convertExpression(it, parent) } ?: UastEmptyExpression(parent)
internal fun convertOrNull(expression: PsiExpression?, parent: UElement?): UExpression? =
if (expression != null) convertExpression(expression, parent) else null
internal fun convertOrEmpty(block: PsiCodeBlock?, parent: UElement?): UExpression =
if (block != null) convertBlock(block, parent) else UastEmptyExpression(parent)
}
private fun elementTypes(requiredType: Class<out UElement>?) = requiredType?.let { arrayOf(it) } ?: DEFAULT_TYPES_LIST
private fun <T : UElement> Array<out Class<out T>>.nonEmptyOr(default: Array<out Class<out UElement>>) = takeIf { it.isNotEmpty() } ?: default | apache-2.0 | ce276b00a4d9bf120c5d7da0c5656ae6 | 50.522911 | 142 | 0.707858 | 5.360067 | false | false | false | false |
leafclick/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/lang/parser/GFMCommentAwareMarkerProcessor.kt | 1 | 3250 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.lang.parser
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.flavours.commonmark.CommonMarkMarkerProcessor
import org.intellij.markdown.flavours.gfm.GFMConstraints
import org.intellij.markdown.flavours.gfm.GFMTokenTypes
import org.intellij.markdown.flavours.gfm.table.GitHubTableMarkerProvider
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.MarkerProcessor
import org.intellij.markdown.parser.MarkerProcessorFactory
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.providers.AtxHeaderProvider
import org.intellij.markdown.parser.markerblocks.providers.LinkReferenceDefinitionProvider
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
class GFMCommentAwareMarkerProcessor(productionHolder: ProductionHolder, constraintsBase: MarkdownConstraints)
: CommonMarkMarkerProcessor(productionHolder, constraintsBase) {
private val markerBlockProviders = super.getMarkerBlockProviders()
.filterNot { it is AtxHeaderProvider }
.filterNot { it is LinkReferenceDefinitionProvider }
.plus(listOf(
GitHubTableMarkerProvider(),
AtxHeaderProvider(false),
CommentAwareLinkReferenceDefinitionProvider()))
override fun populateConstraintsTokens(pos: LookaheadText.Position,
constraints: MarkdownConstraints,
productionHolder: ProductionHolder) {
if (constraints !is GFMConstraints || !constraints.hasCheckbox()) {
super.populateConstraintsTokens(pos, constraints, productionHolder)
return
}
val line = pos.currentLine
var offset = pos.offsetInCurrentLine
while (offset < line.length && line[offset] != '[') {
offset++
}
if (offset == line.length) {
super.populateConstraintsTokens(pos, constraints, productionHolder)
return
}
val type = when (constraints.getLastType()) {
'>' ->
MarkdownTokenTypes.BLOCK_QUOTE
'.', ')' ->
MarkdownTokenTypes.LIST_NUMBER
else ->
MarkdownTokenTypes.LIST_BULLET
}
val middleOffset = pos.offset - pos.offsetInCurrentLine + offset
val endOffset = Math.min(pos.offset - pos.offsetInCurrentLine + constraints.getCharsEaten(pos.currentLine),
pos.nextLineOrEofOffset)
productionHolder.addProduction(listOf(
SequentialParser.Node(pos.offset..middleOffset, type),
SequentialParser.Node(middleOffset..endOffset, GFMTokenTypes.CHECK_BOX)
))
}
override fun getMarkerBlockProviders(): List<MarkerBlockProvider<StateInfo>> {
return markerBlockProviders
}
object Factory : MarkerProcessorFactory {
override fun createMarkerProcessor(productionHolder: ProductionHolder): MarkerProcessor<*> {
return GFMCommentAwareMarkerProcessor(productionHolder, GFMConstraints.BASE)
}
}
} | apache-2.0 | 5e5b8044b9b648e04e7d4b0a82904ace | 42.346667 | 140 | 0.756308 | 5.126183 | false | false | false | false |
benoitletondor/EasyBudget | Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/main/calendar/CalendarFragment.kt | 1 | 2436 | /*
* Copyright 2022 Benoit LETONDOR
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.benoitletondor.easybudgetapp.view.main.calendar
import com.benoitletondor.easybudgetapp.db.DB
import com.benoitletondor.easybudgetapp.parameters.Parameters
import com.roomorama.caldroid.CaldroidFragment
import com.roomorama.caldroid.CaldroidGridAdapter
import dagger.hilt.android.AndroidEntryPoint
import java.time.LocalDate
import javax.inject.Inject
/**
* @author Benoit LETONDOR
*/
@AndroidEntryPoint
class CalendarFragment : CaldroidFragment() {
private var mSelectedDate = LocalDate.now()
@Inject lateinit var db: DB
@Inject lateinit var parameters: Parameters
// --------------------------------------->
override fun getNewDatesGridAdapter(month: Int, year: Int): CaldroidGridAdapter {
return CalendarGridAdapter(requireContext(), db, parameters, month, year, getCaldroidData(), extraData)
}
override fun setSelectedDate(date: LocalDate) {
this.mSelectedDate = date
super.clearSelectedDates()
super.setSelectedDate(date)
try {
// Exception that occurs if we call this code before the calendar being initialized
super.moveToDate(date)
} catch (ignored: Exception) { }
}
fun getSelectedDate(): LocalDate = mSelectedDate
fun setFirstDayOfWeek(firstDayOfWeek: Int) {
if (firstDayOfWeek != startDayOfWeek) {
startDayOfWeek = firstDayOfWeek
val weekdaysAdapter = getNewWeekdayAdapter(themeResource)
weekdayGridView.adapter = weekdaysAdapter
nextMonth()
prevMonth()
}
}
fun goToCurrentMonth() {
try {
// Exception that occurs if we call this code before the calendar being initialized
super.moveToDate(LocalDate.now())
} catch (ignored: Exception) { }
}
}
| apache-2.0 | 63121c2e0f0c33d7856143c902f52a40 | 31.918919 | 111 | 0.689655 | 4.711799 | false | false | false | false |
zdary/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/ui/preview/PreviewLAFThemeStyles.kt | 2 | 4126 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.preview
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.ui.JBColor
import com.intellij.ui.JBColor.namedColor
import com.intellij.util.ui.UIUtil
import java.awt.Color
/**
* Service to with utility functions to generate
* style for Markdown preview from IntelliJ LAF Settings
*/
internal object PreviewLAFThemeStyles {
/**
* This method will generate stylesheet with colors and other attributes matching current LAF settings of the IDE.
* Generated CSS will override base rules from the default.css, so the preview elements will have correct colors.
* @return String containing generated CSS rules.
*/
@JvmStatic
fun createStylesheet(): String {
with(EditorColorsManager.getInstance().globalScheme) {
val contrastedForeground = defaultForeground.contrast(0.1)
val panelBackground = UIUtil.getPanelBackground()
val linkActiveForeground = namedColor("Link.activeForeground", getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR).foregroundColor)
val separatorColor = namedColor("Group.separatorColor", panelBackground)
val infoForeground = namedColor("Component.infoForeground", contrastedForeground)
val markdownFenceBackground = JBColor(Color(212, 222, 231, 255 / 4), Color(212, 222, 231, 25))
val fontSize = EditorUtil.getEditorFont().size + 1
// For some reason background-color for ::-webkit-scrollbar-thumb
// doesn't work with [0..255] alpha values. Fortunately it works fine with [0..1] values.
// Default color from base stylesheets will be used, if the final value is null.
// (Generated rule will be invalid)
val scrollbarColor = getColor(EditorColors.SCROLLBAR_THUMB_COLOR)?.run {
"rgba($red, $blue, $green, ${alpha / 255.0})"
}
// language=CSS
val backgroundColor: String = defaultBackground.webRgba()//if (UIUtil.isUnderDarcula()) "rgb(49, 51, 53)" else defaultBackground.webRgba()
return """
body {
background-color: ${backgroundColor};
font-size: ${fontSize}px !important;
}
body, p, blockquote, ul, ol, dl, table, pre, code, tr {
color: ${defaultForeground.webRgba()};
}
a {
color: ${linkActiveForeground.webRgba()};
}
table td, table th {
border: 1px solid ${separatorColor.webRgba()};
}
hr {
background-color: ${separatorColor.webRgba()};
}
kbd, tr {
border: 1px solid ${separatorColor.webRgba()};
}
h6 {
color: ${infoForeground.webRgba()};
}
blockquote {
border-left: 2px solid ${linkActiveForeground.webRgba(alpha = 0.4)};
}
::-webkit-scrollbar-thumb {
background-color: $scrollbarColor;
}
blockquote, code, pre {
background-color: ${markdownFenceBackground.webRgba(markdownFenceBackground.alpha / 255.0)};
}
""".trimIndent()
}
}
private fun Color.webRgba(alpha: Double = this.alpha.toDouble()) = "rgba($red, $green, $blue, $alpha)"
/**
* Simple linear contrast function.
*
* 0 < coefficient < 1 results in reduced contrast.
* coefficient > 1 results in increased contrast.
*/
private fun Color.contrast(coefficient: Double) =
Color(
(coefficient * (red - 128) + 128).toInt(),
(coefficient * (green - 128) + 128).toInt(),
(coefficient * (blue - 128) + 128).toInt(),
alpha
)
}
| apache-2.0 | 1dddb9a5a5a723c22f3e41377aae703a | 37.560748 | 144 | 0.610034 | 4.610056 | false | false | false | false |
LUSHDigital/android-lush-views | views/src/main/java/com/lush/dialog/BaseDialog.kt | 1 | 3047 | package com.lush.dialog
import android.app.DialogFragment
import android.app.FragmentManager
import android.app.FragmentTransaction
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.TextView
import com.lush.view.R
/**
* Base class for all dialogs.
*
* This will set the correct dimensions based on device
* and apply our tool bar design to the top of the dialog.
*/
abstract class BaseDialog: DialogFragment(), View.OnKeyListener
{
init
{
retainInstance = true
// This exists to call the code in the setter for cancelable
setCancelable(isCancelable)
}
fun show(manager: FragmentManager?)
{
super.show(manager, null)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
val view = inflater.inflate(R.layout.dialog_base, container, false)
val frameLayout = view?.findViewById<FrameLayout>(R.id.container)
val subView = inflater.inflate(getLayoutResource(), frameLayout, false)
frameLayout?.addView(subView)
view?.setBackgroundColor(Color.WHITE)
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?)
{
super.onActivityCreated(savedInstanceState)
view?.findViewById<TextView>(R.id.header_title)?.text = getTitle()
val closeBtn = view?.findViewById<ImageButton>(R.id.header_close)
if (isCancelable)
{
closeBtn?.setOnClickListener { dismiss() }
}
else
{
closeBtn?.visibility = View.INVISIBLE
}
onInnerViewCreated()
}
override fun onDestroyView()
{
val dialog = dialog
// handles https://code.google.com/p/android/issues/detail?id=17423
if (dialog != null && retainInstance)
{
dialog.setDismissMessage(null)
}
super.onDestroyView()
}
override fun onSaveInstanceState(outState: Bundle)
{
// Fix for https://stackoverflow.com/questions/7575921/illegalstateexception-can-not-perform-this-action-after-onsaveinstancestate-wit
outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE")
super.onSaveInstanceState(outState)
}
override fun dismiss()
{
hideKeyboard()
super.dismiss()
}
override fun onKey(p0: View?, p1: Int, p2: KeyEvent?): Boolean
{
if (p1 == KeyEvent.KEYCODE_ENTER)
{
hideKeyboard()
return true
}
return false
}
protected fun hideKeyboard()
{
val view = view
if (view != null)
{
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
fun show(transaction: FragmentTransaction?): Int = super.show(transaction, null)
@LayoutRes protected abstract fun getLayoutResource(): Int
protected abstract fun onInnerViewCreated()
protected abstract fun getTitle(): String
}
| apache-2.0 | bb4e24714706f5b9a6315f0fc4cb094a | 25.495652 | 136 | 0.759436 | 3.711328 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inlineMultiFile/fromJavaToKotlin/delegateToCallChain/before/usage/main.kt | 12 | 1315 | package usage
import javapackage.one.JavaClassOne
fun a() {
JavaClassOne().<caret>a()
val d = JavaClassOne()
d.a()
d.let {
it.a()
}
d.also {
it.a()
}
with(d) {
a()
}
with(d) out@{
with(4) {
[email protected]()
}
}
}
fun a2() {
val d: JavaClassOne? = null
d?.a()
d?.let {
it.a()
}
d?.also {
it.a()
}
with(d) {
this?.a()
}
with(d) out@{
with(4) {
this@out?.a()
}
}
}
fun a3() {
val d: JavaClassOne? = null
val a1 = d?.a()
val a2 = d?.let {
it.a()
}
val a3 = d?.also {
it.a()
}
val a4 = with(d) {
this?.a()
}
val a5 = with(d) out@{
with(4) {
this@out?.a()
}
}
}
fun a4() {
val d: JavaClassOne? = null
d?.a()?.dec()
val a2 = d?.let {
it.a()
}
a2?.toLong()
d?.also {
it.a()
}?.a()?.and(4)
val a4 = with(d) {
this?.a()
}
val a5 = with(d) out@{
with(4) {
this@out?.a()
}
}
val a6 = a4?.let { out -> a5?.let { out + it } }
}
fun JavaClassOne.b(): Int? = a()
fun JavaClassOne.c(): Int = this.a()
fun d(d: JavaClassOne) = d.a()
| apache-2.0 | e2121990755ab22eadc5be737f58dafc | 11.644231 | 52 | 0.370342 | 2.915743 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/mayTypeAffectAncestors.0.kt | 1 | 635 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages
data class A(val <caret>n: Int, val s: String)
data class B(val x: Int, val y: Int)
fun condition(a: A) = true
fun x(a: A, b: Boolean, list: List<Int>) {
val (x, y) = if (condition(a)) {
print(A(1, "").toString())
B(1, 2)
} else {
B(3, 4)
}
val (x1, y1) = if (b) {
A(1, "").apply { val (x2, y2) = this }
} else {
return
}
if (list.any { it == 0 }) {
A(1, "")
}
}
fun y1(a: A) = condition(a)
fun y2(a: A): Boolean = condition(a)
fun y3(a: A) {
condition(a)
}
// FIR_IGNORE | apache-2.0 | 9815d359a3e93590e10e707d7c176843 | 17.171429 | 52 | 0.496063 | 2.57085 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyNamespacePackageUtil.kt | 12 | 2568 | @file:JvmName("PyNamespacePackageUtil")
package com.jetbrains.python.psi.resolve
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.lexer.PythonLexer
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyUtil
import java.util.regex.Pattern
fun isNamespacePackage(element: PsiElement): Boolean {
if (element is PsiDirectory) {
val level = LanguageLevel.forElement(element)
val initFile = PyUtil.turnDirIntoInit(element) ?: return !level.isPython2
val lexer = PythonLexer()
lexer.start(initFile.text)
while (lexer.tokenType in TOKENS_TO_SKIP) {
lexer.advance()
}
val codeStart = initFile.text.substring(lexer.tokenStart)
var nextPattern: Pattern? = null
for (line in codeStart.lineSequence()) {
val trimmed = line.trim()
if (trimmed.isEmpty() || trimmed.startsWith("#")) continue
else if (nextPattern != null) return nextPattern.matcher(trimmed).matches()
else if (ONE_LINE_NAMESPACE_DECLARATIONS.any { it.matcher(trimmed).matches() }) return true
else {
val matched = TWO_LINE_NAMESPACE_DECLARATIONS.find { it[0].matcher(trimmed).matches() }
nextPattern = matched?.get(1) ?: return false
}
}
}
return false
}
private val TOKENS_TO_SKIP = TokenSet.create(PyTokenTypes.DOCSTRING,
PyTokenTypes.END_OF_LINE_COMMENT,
PyTokenTypes.LINE_BREAK,
PyTokenTypes.SPACE,
PyTokenTypes.TRY_KEYWORD,
PyTokenTypes.COLON)
private val TWO_LINE_NAMESPACE_DECLARATIONS = listOf(
patterns("^from pkgutil import extend_path.*", "^__path__[ ]?=[ ]?extend_path\\(__path__,[ ]?__name__\\).*"),
patterns("^import pkgutil.*", "^__path__[ ]?=[ ]?pkgutil\\.extend_path\\(__path__,[ ]?__name__\\).*"),
patterns("^from pkg_resources import declare_namespace.*", "^declare_namespace\\(__name__\\).*"),
patterns("^import pkg_resources.*", "^pkg_resources.declare_namespace\\(__name__\\).*")
)
private val ONE_LINE_NAMESPACE_DECLARATIONS = patterns(
"^__path__[ ]?=[ ]?__import__\\(['\"]pkgutil['\"]\\).extend_path\\(__path__, __name__\\).*",
"^__import__\\(['\"]pkg_resources['\"]\\).declare_namespace\\(__name__\\).*"
)
private fun patterns(vararg patterns: String) = patterns.map { it.toPattern() } | apache-2.0 | 84db03aa87225bae4b0ded3556c7409f | 41.816667 | 111 | 0.626558 | 3.987578 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/HeadbarType.kt | 1 | 3909 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Method2
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.*
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.Instruction2
@DependsOn(Headbar.type::class)
class HeadbarType : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.type == field<Headbar.type>().type }
@DependsOn(Packet::class)
class decode : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(type<Packet>()) }
.and { it.instructions.none { it.opcode == BIPUSH && it.intOperand == 6 } }
}
@DependsOn(Packet::class)
class decode0 : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(type<Packet>()) }
.and { it.instructions.any { it.opcode == BIPUSH && it.intOperand == 6 } }
}
class int1 : OrderMapper.InConstructor.Field(HeadbarType::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class int2 : OrderMapper.InConstructor.Field(HeadbarType::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class int3 : OrderMapper.InConstructor.Field(HeadbarType::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class int4 : OrderMapper.InConstructor.Field(HeadbarType::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class int5 : OrderMapper.InConstructor.Field(HeadbarType::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class spritefront : OrderMapper.InConstructor.Field(HeadbarType::class, 5) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class spriteback : OrderMapper.InConstructor.Field(HeadbarType::class, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class width : OrderMapper.InConstructor.Field(HeadbarType::class, 7) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class widthPadding : OrderMapper.InConstructor.Field(HeadbarType::class, 8) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
@MethodParameters()
@DependsOn(Sprite::class, spritefront::class)
class getFrontSprite : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<Sprite>() }
.and { it.instructions.any { it.isField && it.fieldId == field<spritefront>().id } }
}
@MethodParameters()
@DependsOn(Sprite::class, spriteback::class)
class getBackSprite : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<Sprite>() }
.and { it.instructions.any { it.isField && it.fieldId == field<spriteback>().id } }
}
} | mit | 1923e776142f6d70d248bc31e3e97431 | 46.108434 | 112 | 0.693272 | 4.132135 | false | false | false | false |
charlesng/SampleAppArch | app/src/main/java/com/cn29/aac/ui/base/BaseFragment.kt | 1 | 1488 | package com.cn29.aac.ui.base
import android.os.Bundle
import com.cn29.aac.ui.common.AlertDialogComponent
import com.cn29.aac.ui.common.FragmentPermissionComponent.PermissionCallback
import com.cn29.aac.ui.common.ProgressDialogComponent
import dagger.android.support.DaggerFragment
/**
* Created by charlesng0209 on 2/10/2017.
*/
open class BaseFragment :
DaggerFragment() {
//common UI component
@JvmField
protected var progressDialogComponent: ProgressDialogComponent? = null
private var dialogComponent: AlertDialogComponent? = null
//permission callback
private var permissionCallback: PermissionCallback? = null
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
progressDialogComponent = activity?.let {
ProgressDialogComponent(it,
this.lifecycle)
}
dialogComponent = activity?.let {
AlertDialogComponent(it,
this.lifecycle)
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
permissionCallback!!.onRequestPermissionsResult(requestCode,
permissions,
grantResults)
}
} | apache-2.0 | ab040b79bec9a265aff571df78e78691 | 35.317073 | 76 | 0.611559 | 5.928287 | false | false | false | false |
idea4bsd/idea4bsd | python/src/com/jetbrains/python/console/PyConsoleEnterHandler.kt | 1 | 5209 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.console
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.Result
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.actionSystem.EditorActionManager
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.codeStyle.IndentHelperImpl
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.PythonFileType
import com.jetbrains.python.psi.PyStatementListContainer
import com.jetbrains.python.psi.PyStringLiteralExpression
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl
class PyConsoleEnterHandler {
fun handleEnterPressed(editor: EditorEx): Boolean {
val project = editor.project ?: throw IllegalArgumentException()
if (editor.document.lineCount != 0) { // move to end of line
editor.selectionModel.removeSelection()
val caretPosition = editor.caretModel.logicalPosition
val lineEndOffset = editor.document.getLineEndOffset(caretPosition.line)
editor.caretModel.moveToOffset(lineEndOffset)
}
val psiMgr = PsiDocumentManager.getInstance(project)
psiMgr.commitDocument(editor.document)
val caretOffset = editor.expectedCaretOffset
val atElement = findFirstNoneSpaceElement(psiMgr.getPsiFile(editor.document)!!, caretOffset)
var insideDocString = false
atElement?.let {
insideDocString = isElementInsideDocString(atElement, caretOffset)
}
val enterHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER)
object : WriteCommandAction<Nothing>(project) {
@Throws(Throwable::class)
override fun run(result: Result<Nothing>) {
enterHandler.execute(editor, null, DataManager.getInstance().getDataContext(editor.component))
}
}.execute()
val prevLine = getLineAtOffset(editor.document, caretOffset)
val isCellMagic = prevLine.trim().startsWith("%%") && !prevLine.trimEnd().endsWith("?")
val isCellHelp = prevLine.trim().startsWith("%%") && prevLine.trimEnd().endsWith("?")
val isLineCellMagic = prevLine.trim().startsWith("%")
val hasCompleteStatement = atElement != null && !insideDocString && !isCellMagic &&
(isCellHelp || isLineCellMagic || checkComplete(atElement))
val currentLine = getLineAtOffset(editor.document, editor.expectedCaretOffset)
val indent = IndentHelperImpl.getIndent(project, PythonFileType.INSTANCE, currentLine, false)
return indent == 0 || (hasCompleteStatement && prevLine.isBlank())
}
private fun isElementInsideDocString(atElement: PsiElement, caretOffset: Int): Boolean {
return (atElement.context is PyStringLiteralExpression &&
(PyTokenTypes.TRIPLE_NODES.contains(atElement.node.elementType)
|| atElement.node.elementType === PyTokenTypes.DOCSTRING)
&& (atElement.textRange.endOffset > caretOffset || !isCompletDocString(atElement.text)))
}
private fun checkComplete(el: PsiElement): Boolean {
val compoundStatement = PsiTreeUtil.getParentOfType(el, PyStatementListContainer::class.java)
if (compoundStatement != null) {
return compoundStatement.statementList.statements.size != 0
}
val topLevel = PyPsiUtils.getParentRightBefore(el, el.containingFile)
return topLevel != null && PsiTreeUtil.hasErrorElements(topLevel)
}
private fun findFirstNoneSpaceElement(psiFile: PsiFile, offset: Int): PsiElement? {
for (i in offset downTo 0) {
val el = psiFile.findElementAt(i)
if (el != null && el !is PsiWhiteSpace) {
return el
}
}
return null
}
private fun getLineAtOffset(doc: Document, offset: Int): String {
val line = doc.getLineNumber(offset)
val start = doc.getLineStartOffset(line)
val end = doc.getLineEndOffset(line)
return doc.getText(TextRange(start, end))
}
private fun isCompletDocString(str: String): Boolean {
val prefixLen = PyStringLiteralExpressionImpl.getPrefixLength(str)
val text = str.substring(prefixLen)
for (token in arrayOf("\"\"\"", "'''")) {
if (text.length >= 2 * token.length && text.startsWith(token) && text.endsWith(token)) {
return true
}
}
return false
}
} | apache-2.0 | a948d3fb5f2cd3529e428cbc2e1ea842 | 40.68 | 105 | 0.747168 | 4.392074 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/cli/common/arguments/CliArgumentStringBuilder.kt | 2 | 3669 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.cli.common.arguments
import com.intellij.openapi.util.text.StringUtil.compareVersionNumbers
import org.jetbrains.kotlin.config.LanguageFeature
object CliArgumentStringBuilder {
private const val LANGUAGE_FEATURE_FLAG_PREFIX = "-XXLanguage:"
private const val LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX = "-X"
private val versionRegex = Regex("""^(\d+)\.(\d+)\.(\d+)""")
private val LanguageFeature.dedicatedFlagInfo
get() = when (this) {
LanguageFeature.InlineClasses -> Pair("inline-classes", KotlinVersion(1, 3, 50))
else -> null
}
private val LanguageFeature.State.sign: String
get() = when (this) {
LanguageFeature.State.ENABLED -> "+"
LanguageFeature.State.DISABLED -> "-"
LanguageFeature.State.ENABLED_WITH_WARNING -> "+" // not supported normally
LanguageFeature.State.ENABLED_WITH_ERROR -> "-" // not supported normally
}
private fun LanguageFeature.getFeatureMentionInCompilerArgsRegex(): Regex {
val basePattern = "$LANGUAGE_FEATURE_FLAG_PREFIX(?:-|\\+)$name"
val fullPattern =
if (dedicatedFlagInfo != null) "(?:$basePattern)|$LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX${dedicatedFlagInfo!!.first}" else basePattern
return Regex(fullPattern)
}
fun LanguageFeature.buildArgumentString(state: LanguageFeature.State, kotlinVersion: String?): String {
val shouldBeFeatureEnabled = state == LanguageFeature.State.ENABLED || state == LanguageFeature.State.ENABLED_WITH_WARNING
val dedicatedFlag = dedicatedFlagInfo?.run {
val (xFlag, xFlagSinceVersion) = this
if (kotlinVersion == null) return@run xFlag
val parsedVersion = versionRegex.find(kotlinVersion) ?: return@run xFlag
val isAtLeastSpecifiedVersion = parsedVersion.destructured.let { (major, minor, patch) ->
KotlinVersion(major.toInt(), minor.toInt(), patch.toInt()) >= xFlagSinceVersion
}
if (isAtLeastSpecifiedVersion) xFlag else null
}
return if (shouldBeFeatureEnabled && dedicatedFlag != null) {
LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX + dedicatedFlag
} else {
"$LANGUAGE_FEATURE_FLAG_PREFIX${state.sign}$name"
}
}
fun String.replaceLanguageFeature(
feature: LanguageFeature,
state: LanguageFeature.State,
kotlinVersion: String?,
prefix: String = "",
postfix: String = "",
separator: String = ", ",
quoted: Boolean = true
): String {
val quote = if (quoted) "\"" else ""
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val existingFeatureMatchResult = feature.getFeatureMentionInCompilerArgsRegex().find(this)
return if (existingFeatureMatchResult != null) {
replace(existingFeatureMatchResult.value, featureArgumentString)
} else {
val splitText = if (postfix.isNotEmpty()) split(postfix) else listOf(this, "")
if (splitText.size != 2) {
"$prefix$quote$featureArgumentString$quote$postfix"
} else {
val (mainPart, commentPart) = splitText
// In Groovy / Kotlin DSL, we can have comment after [...] or listOf(...)
mainPart + "$separator$quote$featureArgumentString$quote$postfix" + commentPart
}
}
}
} | apache-2.0 | dd1ddfd9e4baed1384ab84c6ca6c6e19 | 43.216867 | 158 | 0.646225 | 4.878989 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/NamedEntityImpl.kt | 2 | 9672 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class NamedEntityImpl: NamedEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(NamedEntity::class.java, NamedChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
@JvmField var _myName: String? = null
override val myName: String
get() = _myName!!
@JvmField var _additionalProperty: String? = null
override val additionalProperty: String?
get() = _additionalProperty
override val children: List<NamedChildEntity>
get() = snapshot.extractOneToManyChildren<NamedChildEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: NamedEntityData?): ModifiableWorkspaceEntityBase<NamedEntity>(), NamedEntity.Builder {
constructor(): this(NamedEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity NamedEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isMyNameInitialized()) {
error("Field NamedEntity#myName should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field NamedEntity#entitySource should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field NamedEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field NamedEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var myName: String
get() = getEntityData().myName
set(value) {
checkModificationAllowed()
getEntityData().myName = value
changedProperty.add("myName")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var additionalProperty: String?
get() = getEntityData().additionalProperty
set(value) {
checkModificationAllowed()
getEntityData().additionalProperty = value
changedProperty.add("additionalProperty")
}
// List of non-abstract referenced types
var _children: List<NamedChildEntity>? = emptyList()
override var children: List<NamedChildEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<NamedChildEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<NamedChildEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<NamedChildEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): NamedEntityData = result ?: super.getEntityData() as NamedEntityData
override fun getEntityClass(): Class<NamedEntity> = NamedEntity::class.java
}
}
class NamedEntityData : WorkspaceEntityData.WithCalculablePersistentId<NamedEntity>() {
lateinit var myName: String
var additionalProperty: String? = null
fun isMyNameInitialized(): Boolean = ::myName.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<NamedEntity> {
val modifiable = NamedEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): NamedEntity {
val entity = NamedEntityImpl()
entity._myName = myName
entity._additionalProperty = additionalProperty
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun persistentId(): PersistentEntityId<*> {
return NameId(myName)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return NamedEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as NamedEntityData
if (this.myName != other.myName) return false
if (this.entitySource != other.entitySource) return false
if (this.additionalProperty != other.additionalProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as NamedEntityData
if (this.myName != other.myName) return false
if (this.additionalProperty != other.additionalProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + myName.hashCode()
result = 31 * result + additionalProperty.hashCode()
return result
}
} | apache-2.0 | 73ba866607cd22cf91c20a1e060f8086 | 39.304167 | 214 | 0.617763 | 5.97775 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/RelocationRequester.kt | 3 | 1994 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.layout
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.geometry.Rect
/**
* This class can be used to send relocation requests. Pass it as a parameter to
* [Modifier.relocationRequester()][relocationRequester].
*/
@ExperimentalComposeUiApi
@Suppress("UNUSED_PARAMETER", "RedundantSuspendModifier")
@Deprecated(
message = "Please use BringIntoViewRequester instead.",
replaceWith = ReplaceWith(
"BringIntoViewRequester",
"androidx.compose.foundation.relocation.BringIntoViewRequester"
),
level = DeprecationLevel.ERROR
)
class RelocationRequester {
/**
* Bring this item into bounds by making all the scrollable parents scroll appropriately.
*
* @param rect The rectangle (In local coordinates) that should be brought into view. If you
* don't specify the coordinates, the coordinates of the
* [Modifier.relocationRequester()][relocationRequester] associated with this
* [RelocationRequester] will be used.
*/
@Deprecated(
message = "Please use BringIntoViewRequester instead.",
replaceWith = ReplaceWith(
"bringIntoView",
"androidx.compose.foundation.relocation.BringIntoViewRequester"
),
level = DeprecationLevel.ERROR
)
suspend fun bringIntoView(rect: Rect? = null) {}
}
| apache-2.0 | 580b31eab4718fd67879fd7f71fc83ca | 34.607143 | 96 | 0.72317 | 4.583908 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/shape/AbsoluteRoundedCornerShape.kt | 3 | 6471 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.shape
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.toRect
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
/**
* A shape describing the rectangle with rounded corners.
*
* This shape will not automatically mirror the corner sizes in [LayoutDirection.Rtl], use
* [RoundedCornerShape] for the layout direction aware version of this shape.
*
* @param topLeft a size of the top left corner
* @param topRight a size of the top right corner
* @param bottomRight a size of the bottom right corner
* @param bottomLeft a size of the bottom left corner
*/
class AbsoluteRoundedCornerShape(
topLeft: CornerSize,
topRight: CornerSize,
bottomRight: CornerSize,
bottomLeft: CornerSize
) : CornerBasedShape(
topStart = topLeft,
topEnd = topRight,
bottomEnd = bottomRight,
bottomStart = bottomLeft
) {
override fun createOutline(
size: Size,
topStart: Float,
topEnd: Float,
bottomEnd: Float,
bottomStart: Float,
layoutDirection: LayoutDirection
) = if (topStart + topEnd + bottomEnd + bottomStart == 0.0f) {
Outline.Rectangle(size.toRect())
} else {
Outline.Rounded(
RoundRect(
rect = size.toRect(),
topLeft = CornerRadius(topStart),
topRight = CornerRadius(topEnd),
bottomRight = CornerRadius(bottomEnd),
bottomLeft = CornerRadius(bottomStart)
)
)
}
override fun copy(
topStart: CornerSize,
topEnd: CornerSize,
bottomEnd: CornerSize,
bottomStart: CornerSize
) = AbsoluteRoundedCornerShape(
topLeft = topStart,
topRight = topEnd,
bottomRight = bottomEnd,
bottomLeft = bottomStart
)
override fun toString(): String {
return "AbsoluteRoundedCornerShape(topLeft = $topStart, topRight = $topEnd, " +
"bottomRight = $bottomEnd, bottomLeft = $bottomStart)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AbsoluteRoundedCornerShape) return false
if (topStart != other.topStart) return false
if (topEnd != other.topEnd) return false
if (bottomEnd != other.bottomEnd) return false
if (bottomStart != other.bottomStart) return false
return true
}
override fun hashCode(): Int {
var result = topStart.hashCode()
result = 31 * result + topEnd.hashCode()
result = 31 * result + bottomEnd.hashCode()
result = 31 * result + bottomStart.hashCode()
return result
}
private fun Float.toRadius() = CornerRadius(this)
}
/**
* Creates [AbsoluteRoundedCornerShape] with the same size applied for all four corners.
* @param corner [CornerSize] to apply.
*/
fun AbsoluteRoundedCornerShape(corner: CornerSize) =
AbsoluteRoundedCornerShape(corner, corner, corner, corner)
/**
* Creates [AbsoluteRoundedCornerShape] with the same size applied for all four corners.
* @param size Size in [Dp] to apply.
*/
fun AbsoluteRoundedCornerShape(size: Dp) = AbsoluteRoundedCornerShape(CornerSize(size))
/**
* Creates [AbsoluteRoundedCornerShape] with the same size applied for all four corners.
* @param size Size in pixels to apply.
*/
fun AbsoluteRoundedCornerShape(size: Float) = AbsoluteRoundedCornerShape(CornerSize(size))
/**
* Creates [AbsoluteRoundedCornerShape] with the same size applied for all four corners.
* @param percent Size in percents to apply.
*/
fun AbsoluteRoundedCornerShape(percent: Int) =
AbsoluteRoundedCornerShape(CornerSize(percent))
/**
* Creates [AbsoluteRoundedCornerShape] with sizes defined in [Dp].
*/
fun AbsoluteRoundedCornerShape(
topLeft: Dp = 0.dp,
topRight: Dp = 0.dp,
bottomRight: Dp = 0.dp,
bottomLeft: Dp = 0.dp
) = AbsoluteRoundedCornerShape(
topLeft = CornerSize(topLeft),
topRight = CornerSize(topRight),
bottomRight = CornerSize(bottomRight),
bottomLeft = CornerSize(bottomLeft)
)
/**
* Creates [AbsoluteRoundedCornerShape] with sizes defined in pixels.
*/
fun AbsoluteRoundedCornerShape(
topLeft: Float = 0.0f,
topRight: Float = 0.0f,
bottomRight: Float = 0.0f,
bottomLeft: Float = 0.0f
) = AbsoluteRoundedCornerShape(
topLeft = CornerSize(topLeft),
topRight = CornerSize(topRight),
bottomRight = CornerSize(bottomRight),
bottomLeft = CornerSize(bottomLeft)
)
/**
* Creates [AbsoluteRoundedCornerShape] with sizes defined in percents of the shape's smaller side.
*
* @param topLeftPercent The top left corner radius as a percentage of the smaller side, with a
* range of 0 - 100.
* @param topRightPercent The top right corner radius as a percentage of the smaller side, with a
* range of 0 - 100.
* @param bottomRightPercent The bottom right corner radius as a percentage of the smaller side,
* with a range of 0 - 100.
* @param bottomLeftPercent The bottom left corner radius as a percentage of the smaller side,
* with a range of 0 - 100.
*/
fun AbsoluteRoundedCornerShape(
/*@IntRange(from = 0, to = 100)*/
topLeftPercent: Int = 0,
/*@IntRange(from = 0, to = 100)*/
topRightPercent: Int = 0,
/*@IntRange(from = 0, to = 100)*/
bottomRightPercent: Int = 0,
/*@IntRange(from = 0, to = 100)*/
bottomLeftPercent: Int = 0
) = AbsoluteRoundedCornerShape(
topLeft = CornerSize(topLeftPercent),
topRight = CornerSize(topRightPercent),
bottomRight = CornerSize(bottomRightPercent),
bottomLeft = CornerSize(bottomLeftPercent)
)
| apache-2.0 | 44ced429c9c77d54d6d660ee5be65253 | 32.35567 | 99 | 0.694329 | 4.375254 | false | false | false | false |
GunoH/intellij-community | plugins/evaluation-plugin/src/com/intellij/cce/evaluation/step/BackgroundEvaluationStep.kt | 8 | 2220 | package com.intellij.cce.evaluation.step
import com.intellij.cce.evaluation.EvaluationStep
import com.intellij.cce.evaluation.HeadlessEvaluationAbortHandler
import com.intellij.cce.evaluation.UIEvaluationAbortHandler
import com.intellij.cce.util.CommandLineProgress
import com.intellij.cce.util.IdeaProgress
import com.intellij.cce.util.Progress
import com.intellij.cce.workspace.EvaluationWorkspace
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.FutureResult
abstract class BackgroundEvaluationStep(protected val project: Project, private val isHeadless: Boolean) : EvaluationStep {
protected companion object {
val LOG = Logger.getInstance(BackgroundEvaluationStep::class.java)
}
abstract fun runInBackground(workspace: EvaluationWorkspace, progress: Progress): EvaluationWorkspace
override fun start(workspace: EvaluationWorkspace): EvaluationWorkspace? {
val result = FutureResult<EvaluationWorkspace?>()
val task = object : Task.Backgroundable(project, name, true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = this.title
indicator.isIndeterminate = false
result.set(runInBackground(workspace, createProgress(indicator)))
}
override fun onCancel() {
evaluationAbortedHandler.onCancel(this.title)
result.set(null)
}
override fun onThrowable(error: Throwable) {
evaluationAbortedHandler.onError(error, this.title)
result.setException(error)
}
}
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, BackgroundableProcessIndicator(task))
return result.get()
}
private val evaluationAbortedHandler =
if (isHeadless) HeadlessEvaluationAbortHandler() else UIEvaluationAbortHandler(project)
private fun createProgress(indicator: ProgressIndicator) =
if (isHeadless) CommandLineProgress(indicator.text) else IdeaProgress(indicator)
} | apache-2.0 | 7de315e48933d789c8be7e3d70bf52ba | 40.90566 | 123 | 0.794144 | 4.879121 | false | false | false | false |
GunoH/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUVariable.kt | 2 | 10544 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.java
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightElement
import com.intellij.psi.impl.light.LightRecordCanonicalConstructor.LightRecordConstructorParameter
import com.intellij.psi.impl.light.LightRecordField
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.psi.util.parentOfType
import com.intellij.util.asSafely
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import org.jetbrains.uast.internal.UElementAlternative
import org.jetbrains.uast.internal.accommodate
import org.jetbrains.uast.internal.alternative
import org.jetbrains.uast.java.internal.JavaUElementWithComments
@ApiStatus.Internal
abstract class AbstractJavaUVariable(
givenParent: UElement?
) : JavaAbstractUElement(givenParent), PsiVariable, UVariableEx, JavaUElementWithComments, UAnchorOwner {
abstract override val javaPsi: PsiVariable
@Suppress("OverridingDeprecatedMember")
override val psi
get() = javaPsi
override val uastInitializer: UExpression? by lz {
val initializer = javaPsi.initializer ?: return@lz null
UastFacade.findPlugin(initializer)?.convertElement(initializer, this) as? UExpression
}
override val uAnnotations: List<UAnnotation> by lz { javaPsi.annotations.map { JavaUAnnotation(it, this) } }
override val typeReference: UTypeReferenceExpression? by lz {
javaPsi.typeElement?.let { UastFacade.findPlugin(it)?.convertOpt<UTypeReferenceExpression>(javaPsi.typeElement, this) }
}
abstract override val sourcePsi: PsiVariable?
override val uastAnchor: UIdentifier?
get() = sourcePsi?.let { UIdentifier(it.nameIdentifier, this) }
override fun equals(other: Any?): Boolean = other is AbstractJavaUVariable && javaPsi == other.javaPsi
override fun hashCode(): Int = javaPsi.hashCode()
}
@ApiStatus.Internal
class JavaUVariable(
override val javaPsi: PsiVariable,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UVariableEx, PsiVariable by javaPsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiVariable
get() = javaPsi
override val sourcePsi: PsiVariable? get() = javaPsi.takeIf { it !is LightElement }
companion object {
fun create(psi: PsiVariable, containingElement: UElement?): UVariable {
return when (psi) {
is PsiEnumConstant -> JavaUEnumConstant(psi, containingElement)
is PsiLocalVariable -> JavaULocalVariable(psi, containingElement)
is PsiParameter -> JavaUParameter(psi, containingElement)
is PsiField -> JavaUField(psi, containingElement)
else -> JavaUVariable(psi, containingElement)
}
}
}
override fun getOriginalElement(): PsiElement? = javaPsi.originalElement
}
@ApiStatus.Internal
class JavaUParameter(
override val javaPsi: PsiParameter,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiParameter
get() = javaPsi
override val sourcePsi: PsiParameter?
get() = javaPsi.takeIf { it !is LightElement }
override fun getOriginalElement(): PsiElement? = javaPsi.originalElement
}
private class JavaRecordUParameter(
override val sourcePsi: PsiRecordComponent,
override val javaPsi: PsiParameter,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiParameter
get() = javaPsi
override val uastAnchor: UIdentifier
get() = UIdentifier(sourcePsi.nameIdentifier, this)
override fun getPsiParentForLazyConversion(): PsiElement? = javaPsi.context
}
internal fun convertRecordConstructorParameterAlternatives(element: PsiElement,
givenParent: UElement?,
expectedTypes: Array<out Class<out UElement>>): Sequence<UVariable> {
val (paramAlternative, fieldAlternative) = createAlternatives(element, givenParent) ?: return emptySequence()
return when (element) {
is LightRecordField -> expectedTypes.accommodate(fieldAlternative, paramAlternative)
else -> expectedTypes.accommodate(paramAlternative, fieldAlternative)
}
}
internal fun convertRecordConstructorParameterAlternatives(element: PsiElement,
givenParent: UElement?,
expectedType: Class<out UElement>): UVariable? {
val (paramAlternative, fieldAlternative) = createAlternatives(element, givenParent) ?: return null
return when (element) {
is LightRecordField -> expectedType.accommodate(fieldAlternative, paramAlternative)
else -> expectedType.accommodate(paramAlternative, fieldAlternative)
}
}
private fun createAlternatives(element: PsiElement,
givenParent: UElement?): Pair<UElementAlternative<JavaRecordUParameter>, UElementAlternative<JavaRecordUField>>? {
val (psiRecordComponent, lightRecordField, lightConstructorParameter) = when (element) {
is PsiRecordComponent -> Triple(element, null, null)
is LightRecordConstructorParameter -> {
val lightRecordField = element.parentOfType<PsiMethod>()?.containingClass?.findFieldByName(element.name, false)
?.asSafely<LightRecordField>() ?: return null
Triple(lightRecordField.recordComponent, lightRecordField, element)
}
is LightRecordField -> Triple(element.recordComponent, element, null)
else -> return null
}
val paramAlternative = alternative {
val psiClass = psiRecordComponent.containingClass ?: return@alternative null
val jvmParameter = lightConstructorParameter ?: psiClass.constructors.asSequence()
.filter { it is LightElement }
.flatMap { it.parameterList.parameters.asSequence() }.firstOrNull { it.name == psiRecordComponent.name }
JavaRecordUParameter(psiRecordComponent, jvmParameter ?: return@alternative null, givenParent)
}
val fieldAlternative = alternative {
val psiField = lightRecordField ?: psiRecordComponent.containingClass?.findFieldByName(psiRecordComponent.name, false)
?: return@alternative null
JavaRecordUField(psiRecordComponent, psiField, givenParent)
}
return Pair(paramAlternative, fieldAlternative)
}
@ApiStatus.Internal
class JavaUField(
override val sourcePsi: PsiField,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by sourcePsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiField
get() = javaPsi
override val javaPsi: PsiField = unwrap<UField, PsiField>(sourcePsi)
override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement
}
private class JavaRecordUField(
private val psiRecord: PsiRecordComponent,
override val javaPsi: PsiField,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by javaPsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiField
get() = javaPsi
override val sourcePsi: PsiVariable?
get() = null
override val uastAnchor: UIdentifier
get() = UIdentifier(psiRecord.nameIdentifier, this)
override fun getPsiParentForLazyConversion(): PsiElement? = javaPsi.context
}
@ApiStatus.Internal
class JavaULocalVariable(
override val sourcePsi: PsiLocalVariable,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), ULocalVariableEx, PsiLocalVariable by sourcePsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiLocalVariable
get() = javaPsi
override val javaPsi: PsiLocalVariable = unwrap<ULocalVariable, PsiLocalVariable>(sourcePsi)
override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let {
when (it) {
is PsiResourceList -> it.parent
else -> it
}
}
override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement
}
@ApiStatus.Internal
class JavaUEnumConstant(
override val sourcePsi: PsiEnumConstant,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UEnumConstantEx, UCallExpression, PsiEnumConstant by sourcePsi, UMultiResolvable {
override val initializingClass: UClass? by lz { UastFacade.findPlugin(sourcePsi)?.convertOpt(sourcePsi.initializingClass, this) }
@Suppress("OverridingDeprecatedMember")
override val psi: PsiEnumConstant
get() = javaPsi
override val javaPsi: PsiEnumConstant get() = sourcePsi
override val kind: UastCallKind
get() = UastCallKind.CONSTRUCTOR_CALL
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression
get() = JavaEnumConstantClassReference(sourcePsi, this)
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val valueArgumentCount: Int
get() = sourcePsi.argumentList?.expressions?.size ?: 0
override val valueArguments: List<UExpression> by lz {
sourcePsi.argumentList?.expressions?.map {
UastFacade.findPlugin(it)?.convertElement(it, this) as? UExpression ?: UastEmptyExpression(this)
} ?: emptyList()
}
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val returnType: PsiType
get() = sourcePsi.type
override fun resolve(): PsiMethod? = sourcePsi.resolveMethod()
override fun multiResolve(): Iterable<ResolveResult> =
listOfNotNull(sourcePsi.resolveMethodGenerics())
override val methodName: String?
get() = null
private class JavaEnumConstantClassReference(
override val sourcePsi: PsiEnumConstant,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable {
override fun resolve() = sourcePsi.containingClass
override fun multiResolve(): Iterable<ResolveResult> =
listOfNotNull(resolve()?.let { PsiTypesUtil.getClassType(it).resolveGenerics() })
override val resolvedName: String?
get() = sourcePsi.containingClass?.name
override val identifier: String
get() = sourcePsi.containingClass?.name ?: "<error>"
}
override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement
}
| apache-2.0 | 0c10b23e29fc91e2af8422285643da5f | 37.064982 | 145 | 0.747439 | 5.224975 | false | false | false | false |
GunoH/intellij-community | platform/statistics/devkit/src/com/intellij/internal/statistic/devkit/actions/ConfigureEventsSchemeFileAction.kt | 6 | 3722 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.devkit.actions
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.internal.statistic.StatisticsBundle
import com.intellij.internal.statistic.devkit.StatisticsDevKitUtil
import com.intellij.internal.statistic.eventLog.validator.IntellijSensitiveDataValidator
import com.intellij.internal.statistic.eventLog.validator.storage.persistence.EventLogMetadataSettingsPersistence
import com.intellij.internal.statistic.eventLog.validator.storage.persistence.EventsSchemePathSettings
import com.intellij.internal.statistic.utils.StatisticsRecorderUtil
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.LayeredIcon
import com.intellij.ui.components.dialog
class ConfigureEventsSchemeFileAction(private var myRecorderId: String = StatisticsDevKitUtil.DEFAULT_RECORDER)
: DumbAwareAction(ActionsBundle.message("action.ConfigureEventsSchemeFileAction.text"),
ActionsBundle.message("action.ConfigureEventsSchemeFileAction.description"),
null) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
val configurationModel = EventsSchemeConfigurationModel().reset(myRecorderId)
val dialog = dialog(
title = "Configure Custom Events Scheme",
panel = configurationModel.panel,
resizable = true,
project = project,
ok = { listOfNotNull(configurationModel.validate()) }
)
if (!dialog.showAndGet()) return
ProgressManager.getInstance().run(object : Task.Backgroundable(project, StatisticsBundle.message("stats.saving.events.scheme.configuration"), false) {
override fun run(indicator: ProgressIndicator) {
updateSchemeSettings(configurationModel.recorderToSettings)
}
})
}
private fun updateSchemeSettings(recorderToSettings: MutableMap<String, EventsSchemeConfigurationModel.EventsSchemePathSettings>) {
val settingsPersistence = EventLogMetadataSettingsPersistence.getInstance()
for ((recorder, settings) in recorderToSettings) {
val customPath = settings.customPath
if (settings.useCustomPath && customPath != null) {
settingsPersistence.setPathSettings(recorder, EventsSchemePathSettings(customPath, true))
}
else {
val oldSettings = settingsPersistence.getPathSettings(recorder)
if (oldSettings != null && oldSettings.isUseCustomPath) {
settingsPersistence.setPathSettings(recorder, EventsSchemePathSettings(oldSettings.customPath, false))
}
}
val validator = IntellijSensitiveDataValidator.getInstance(recorder)
validator.update()
validator.reload()
}
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(event: AnActionEvent) {
super.update(event)
val presentation = event.presentation
presentation.isEnabled = StatisticsRecorderUtil.isTestModeEnabled(myRecorderId)
val settings = EventLogMetadataSettingsPersistence.getInstance().getPathSettings(myRecorderId)
presentation.icon = if (settings != null && settings.isUseCustomPath) customPathConfiguredIcon else AllIcons.General.Settings
}
companion object {
private val customPathConfiguredIcon = LayeredIcon(AllIcons.General.Settings, AllIcons.Nodes.WarningMark)
}
}
| apache-2.0 | f21b1111ca453a783bf6b29dd96523af | 46.717949 | 154 | 0.785062 | 5.162275 | false | true | false | false |
GunoH/intellij-community | platform/webSymbols/src/com/intellij/webSymbols/utils/WebSymbolUtils.kt | 2 | 7984 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("WebSymbolUtils")
package com.intellij.webSymbols.utils
import com.intellij.model.Pointer
import com.intellij.navigation.EmptyNavigatable
import com.intellij.navigation.ItemPresentation
import com.intellij.navigation.NavigationItem
import com.intellij.navigation.NavigationTarget
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.Stack
import com.intellij.webSymbols.*
import com.intellij.webSymbols.html.WebSymbolHtmlAttributeValue
import com.intellij.webSymbols.impl.sortSymbolsByPriority
import com.intellij.webSymbols.references.WebSymbolReferenceProblem.ProblemKind
import com.intellij.webSymbols.query.WebSymbolMatch
import com.intellij.webSymbols.query.WebSymbolNamesProvider
import com.intellij.webSymbols.query.WebSymbolsNameMatchQueryParams
import java.util.*
import javax.swing.Icon
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
val Project.psiModificationCount get() = PsiModificationTracker.getInstance(this).modificationCount
@OptIn(ExperimentalContracts::class)
inline fun <T : Any, P : Any> T.applyIfNotNull(param: P?, block: T.(P) -> T): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return if (param != null)
block(this, param)
else this
}
fun List<WebSymbol>.hasOnlyExtensions(): Boolean =
all { it.extension }
fun List<WebSymbol>.asSingleSymbol(): WebSymbol? =
if (isEmpty())
null
else if (size == 1)
this[0]
else {
val first = this[0]
WebSymbolMatch.create(first.name, listOf(WebSymbolNameSegment(0, first.name.length, sortSymbolsByPriority())),
first.namespace, first.kind, first.origin)
}
fun WebSymbol.withMatchedName(matchedName: String) =
if (matchedName != name) {
WebSymbolMatch.create(matchedName, listOf(WebSymbolNameSegment(0, matchedName.length, this)), namespace, kind, origin)
}
else this
fun WebSymbol.unwrapMatchedSymbols(): Sequence<WebSymbol> =
Sequence {
object : Iterator<WebSymbol> {
private var next: WebSymbol? = null
val fifo = LinkedList<WebSymbol>()
init {
fifo.addLast(this@unwrapMatchedSymbols)
advance()
}
private fun advance() {
while (fifo.isNotEmpty()) {
val symbol = fifo.removeFirst()
if (symbol is WebSymbolMatch) {
symbol.nameSegments.forEach {
fifo.addAll(it.symbols)
}
}
else {
next = symbol
return
}
}
next = null
}
override fun hasNext(): Boolean =
next != null
override fun next(): WebSymbol =
next!!.also { advance() }
}
}
fun WebSymbol.match(nameToMatch: String,
context: Stack<WebSymbolsScope>,
params: WebSymbolsNameMatchQueryParams): List<WebSymbol> {
pattern?.let { pattern ->
context.push(this)
try {
return pattern
.match(this, context, nameToMatch, params)
.mapNotNull { matchResult ->
if ((matchResult.segments.lastOrNull()?.end ?: 0) < nameToMatch.length) {
null
}
else {
WebSymbolMatch.create(nameToMatch, matchResult.segments,
this.namespace, kind, this.origin)
}
}
}
finally {
context.pop()
}
}
val queryExecutor = params.queryExecutor
val queryNames = queryExecutor.namesProvider.getNames(this.namespace, this.kind,
nameToMatch, WebSymbolNamesProvider.Target.NAMES_QUERY)
val symbolNames = queryExecutor.namesProvider.getNames(this.namespace, this.kind, this.matchedName,
WebSymbolNamesProvider.Target.NAMES_MAP_STORAGE).toSet()
return if (queryNames.any { symbolNames.contains(it) }) {
listOf(this.withMatchedName(nameToMatch))
}
else {
emptyList()
}
}
fun WebSymbolNameSegment.getProblemKind(): ProblemKind? =
when (problem) {
WebSymbolNameSegment.MatchProblem.MISSING_REQUIRED_PART -> ProblemKind.MissingRequiredPart
WebSymbolNameSegment.MatchProblem.UNKNOWN_ITEM ->
if (start == end)
ProblemKind.MissingRequiredPart
else
ProblemKind.UnknownSymbol
WebSymbolNameSegment.MatchProblem.DUPLICATE -> ProblemKind.DuplicatedPart
null -> null
}
val WebSymbol.hideFromCompletion
get() =
properties[WebSymbol.PROP_HIDE_FROM_COMPLETION] == true
val (WebSymbolNameSegment.MatchProblem?).isCritical
get() = this == WebSymbolNameSegment.MatchProblem.MISSING_REQUIRED_PART || this == WebSymbolNameSegment.MatchProblem.UNKNOWN_ITEM
fun List<WebSymbolNameSegment>.withOffset(offset: Int): List<WebSymbolNameSegment> =
if (offset != 0) map { it.withOffset(offset) }
else this
fun Sequence<WebSymbolHtmlAttributeValue?>.merge(): WebSymbolHtmlAttributeValue? {
var kind: WebSymbolHtmlAttributeValue.Kind? = null
var type: WebSymbolHtmlAttributeValue.Type? = null
var required: Boolean? = null
var default: String? = null
var langType: Any? = null
for (value in this) {
if (value == null) continue
if (kind == null) {
kind = value.kind
}
if (type == null) {
type = value.type
}
if (required == null) {
required = value.required
}
if (default == null) {
default = value.default
}
if (langType == null) {
langType = value.langType
}
if (kind != null && type != null && required != null) {
break
}
}
return if (kind != null
|| type != null
|| required != null
|| langType != null
|| default != null)
WebSymbolHtmlAttributeValue.create(kind, type, required, default, langType)
else null
}
fun NavigationTarget.createPsiRangeNavigationItem(element: PsiElement, offsetWithinElement: Int): Navigatable {
val vf = element.containingFile.virtualFile
?: return EmptyNavigatable.INSTANCE
val targetPresentation = this.presentation()
val descriptor = OpenFileDescriptor(
element.project, vf, element.textRange.startOffset + offsetWithinElement)
return object : NavigationItem, ItemPresentation {
override fun navigate(requestFocus: Boolean) {
descriptor.navigate(requestFocus)
}
override fun canNavigate(): Boolean = descriptor.canNavigate()
override fun canNavigateToSource(): Boolean = descriptor.canNavigateToSource()
override fun getName(): String = targetPresentation.presentableText
override fun getPresentation(): ItemPresentation = this
override fun getPresentableText(): String = targetPresentation.presentableText
override fun getIcon(unused: Boolean): Icon? = targetPresentation.icon
override fun getLocationString(): String? {
val container = targetPresentation.containerText
val location = targetPresentation.locationText
return if (container != null || location != null) {
sequenceOf(container, location).joinToString(", ", "(", ")")
}
else null
}
override fun toString(): String =
descriptor.file.name + " [" + descriptor.offset + "]"
}
}
internal fun createModificationTracker(trackersPointers: List<Pointer<out ModificationTracker>>): ModificationTracker =
ModificationTracker {
var modCount = 0L
for (tracker in trackersPointers) {
modCount += (tracker.dereference() ?: return@ModificationTracker -1)
.modificationCount.also { if (it < 0) return@ModificationTracker -1 }
}
modCount
} | apache-2.0 | a50e5dc04bec97f6a7018f45c5c4a2e1 | 32.13278 | 131 | 0.686247 | 4.58587 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/plantuml/PlantUMLCodeGeneratingProvider.kt | 2 | 3920 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.extensions.common.plantuml
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import org.intellij.markdown.ast.ASTNode
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension
import org.intellij.plugins.markdown.extensions.MarkdownCodeFenceCacheableProvider
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithDownloadableFiles
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithDownloadableFiles.FileEntry
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel
import org.intellij.plugins.markdown.ui.preview.html.MarkdownCodeFencePluginCacheCollector
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.io.IOException
@ApiStatus.Internal
class PlantUMLCodeGeneratingProvider(
collector: MarkdownCodeFencePluginCacheCollector? = null
): MarkdownCodeFenceCacheableProvider(collector), MarkdownExtensionWithDownloadableFiles, MarkdownBrowserPreviewExtension.Provider {
override val externalFiles: Iterable<String>
get() = ownFiles
override val filesToDownload: Iterable<FileEntry>
get() = dowloadableFiles
override fun isApplicable(language: String): Boolean {
return isEnabled && isAvailable && PlantUMLCodeFenceLanguageProvider.isPlantUmlInfoString(language.lowercase())
}
override fun generateHtml(language: String, raw: String, node: ASTNode): String {
val key = getUniqueFile(language.lowercase(), raw, "png").toFile()
cacheDiagram(key, raw)
collector?.addAliveCachedFile(this, key)
return "<img src=\"${key.toURI()}\"/>"
}
override val displayName: String
get() = MarkdownBundle.message("markdown.extensions.plantuml.display.name")
override val description: String
get() = MarkdownBundle.message("markdown.extensions.plantuml.description")
override val id: String = "PlantUMLLanguageExtension"
override fun beforeCleanup() {
PlantUMLJarManager.getInstance().dropCache()
}
/**
* PlantUML support doesn't currently require any actions/resources inside an actual browser.
* This implementation is not registered in plugin.xml and is needed to make sure that
* PlantUML support extension is treated the same way as other browser extensions (like Mermaid.js one).
*
* Such code can be found mostly in [org.intellij.plugins.markdown.settings.MarkdownSettingsConfigurable].
*/
override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? {
return null
}
private fun cacheDiagram(path: File, text: String) {
if (!path.exists()) {
generateDiagram(text, path)
}
}
@Throws(IOException::class)
private fun generateDiagram(text: CharSequence, diagramPath: File) {
var innerText: String = text.toString().trim()
if (!innerText.startsWith("@startuml")) {
innerText = "@startuml\n$innerText"
}
if (!innerText.endsWith("@enduml")) {
innerText += "\n@enduml"
}
FileUtil.createParentDirs(diagramPath)
storeDiagram(innerText, diagramPath)
}
companion object {
const val jarFilename = "plantuml.jar"
private val ownFiles = listOf(jarFilename)
private val dowloadableFiles = listOf(FileEntry(jarFilename) { Registry.stringValue("markdown.plantuml.download.link") })
private fun storeDiagram(source: String, file: File) {
try {
file.outputStream().buffered().use { PlantUMLJarManager.getInstance().generateImage(source, it) }
} catch (exception: Exception) {
thisLogger().warn("Cannot save diagram PlantUML diagram. ", exception)
}
}
}
}
| apache-2.0 | 762c53e0a6b69f3afb2cda7d13e59e13 | 40.263158 | 158 | 0.766582 | 4.469783 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPREditorReviewThreadsModel.kt | 12 | 2193 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.comment.ui
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.SortedList
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewThread
import java.util.*
class GHPREditorReviewThreadsModel {
private val changeEventDispatcher = EventDispatcher.create(ChangesListener::class.java)
val modelsByLine: MutableMap<Int, SortedList<GHPRReviewThreadModel>> = mutableMapOf()
fun addChangesListener(listener: ChangesListener) = changeEventDispatcher.addListener(listener)
fun update(threadsByLine: Map<Int, List<GHPullRequestReviewThread>>) {
val removedLines = modelsByLine.keys - threadsByLine.keys
for (line in removedLines) {
val removed = modelsByLine.remove(line).orEmpty()
changeEventDispatcher.multicaster.threadsRemoved(line, removed.toList())
}
for ((line, threads) in threadsByLine) {
val models = modelsByLine.computeIfAbsent(line) { SortedList(compareBy { it.createdAt }) }
val modelsById = models.map { it.id to it }.toMap()
val threadsById = threads.map { it.id to it }.toMap()
val removedModels = (modelsById - threadsById.keys).values
if (removedModels.isNotEmpty()) {
models.removeAll(removedModels)
changeEventDispatcher.multicaster.threadsRemoved(line, removedModels.toList())
}
val addedModels = mutableListOf<GHPRReviewThreadModel>()
for ((id, thread) in threadsById) {
val current = modelsById[id]
if (current == null) {
val model = GHPRReviewThreadModelImpl(thread)
models.add(model)
addedModels.add(model)
}
else {
current.update(thread)
}
}
if (addedModels.isNotEmpty()) changeEventDispatcher.multicaster.threadsAdded(line, addedModels)
}
}
interface ChangesListener : EventListener {
fun threadsAdded(line: Int, threads: List<GHPRReviewThreadModel>)
fun threadsRemoved(line: Int, threads: List<GHPRReviewThreadModel>)
}
} | apache-2.0 | cf7708e98c6d65c59789f072c4b7ad3e | 39.62963 | 140 | 0.724122 | 4.521649 | false | false | false | false |
android/compose-samples | Jetchat/app/src/main/java/com/example/compose/jetchat/theme/Color.kt | 1 | 1843 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.jetchat.theme
import androidx.compose.ui.graphics.Color
val Blue10 = Color(0xFF000F5E)
val Blue20 = Color(0xFF001E92)
val Blue30 = Color(0xFF002ECC)
val Blue40 = Color(0xFF1546F6)
val Blue80 = Color(0xFFB8C3FF)
val Blue90 = Color(0xFFDDE1FF)
val DarkBlue10 = Color(0xFF00036B)
val DarkBlue20 = Color(0xFF000BA6)
val DarkBlue30 = Color(0xFF1026D3)
val DarkBlue40 = Color(0xFF3648EA)
val DarkBlue80 = Color(0xFFBBC2FF)
val DarkBlue90 = Color(0xFFDEE0FF)
val Yellow10 = Color(0xFF261900)
val Yellow20 = Color(0xFF402D00)
val Yellow30 = Color(0xFF5C4200)
val Yellow40 = Color(0xFF7A5900)
val Yellow80 = Color(0xFFFABD1B)
val Yellow90 = Color(0xFFFFDE9C)
val Red10 = Color(0xFF410001)
val Red20 = Color(0xFF680003)
val Red30 = Color(0xFF930006)
val Red40 = Color(0xFFBA1B1B)
val Red80 = Color(0xFFFFB4A9)
val Red90 = Color(0xFFFFDAD4)
val Grey10 = Color(0xFF191C1D)
val Grey20 = Color(0xFF2D3132)
val Grey80 = Color(0xFFC4C7C7)
val Grey90 = Color(0xFFE0E3E3)
val Grey95 = Color(0xFFEFF1F1)
val Grey99 = Color(0xFFFBFDFD)
val BlueGrey30 = Color(0xFF45464F)
val BlueGrey50 = Color(0xFF767680)
val BlueGrey60 = Color(0xFF90909A)
val BlueGrey80 = Color(0xFFC6C5D0)
val BlueGrey90 = Color(0xFFE2E1EC)
| apache-2.0 | 8d22801c2f2082f943203b910ad41f70 | 29.716667 | 75 | 0.76994 | 2.800912 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/tail/InstanceAnalyzer.kt | 1 | 1668 | package com.cognifide.gradle.aem.common.instance.tail
import com.cognifide.gradle.aem.common.instance.Instance
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.consumeEach
@OptIn(ExperimentalCoroutinesApi::class)
class InstanceAnalyzer(
private val tailer: Tailer,
private val instance: Instance,
private val logsChannel: ReceiveChannel<Log>,
private val notificationChannel: SendChannel<LogChunk>
) {
private val incidentChannel = Channel<Log>(Channel.UNLIMITED)
private var incidentCannonade = mutableListOf<Log>()
fun listenTailed() {
GlobalScope.launch {
logsChannel.consumeEach { log ->
tailer.logListener.invoke(log, instance)
if (tailer.incidentChecker.invoke(log, instance)) {
incidentChannel.send(log)
}
}
}
GlobalScope.launch {
while (isActive) {
val log = incidentChannel.poll()
if (log != null) {
incidentCannonade.add(log)
}
if (incidentCannonade.lastOrNull()?.isOlderThan(tailer.incidentDelay.get()) == true) {
notificationChannel.send(LogChunk(instance, incidentCannonade))
incidentCannonade = mutableListOf()
}
delay(INCIDENT_CANNONADE_END_INTERVAL)
}
}
}
companion object {
private const val INCIDENT_CANNONADE_END_INTERVAL = 100L
}
}
| apache-2.0 | 6fd3588afb072b7e904a8e8d2ff4e4aa | 30.471698 | 102 | 0.633094 | 4.607735 | false | false | false | false |
milkcan/effortless-prefs | moshi-serializer/src/main/java/io/milkcan/effortlessprefs/moshiserializer/MoshiSerializer.kt | 1 | 2550 | @file:JvmName("MoshiSerializer")
package io.milkcan.effortlessprefs.moshiserializer
import android.content.SharedPreferences
import android.util.Log
import com.squareup.moshi.Moshi
import io.milkcan.effortlessprefs.library.PrefSerializer
import java.io.IOException
/**
* @author Eric Bachhuber
* @version 1.1.0
* @since 1.1.0
*/
class MoshiSerializer(private val moshi: Moshi) : PrefSerializer {
companion object {
@JvmStatic val TAG: String = MoshiSerializer::class.java.simpleName
}
lateinit var prefs: SharedPreferences
override fun setSharedPreferenceInstance(sharedPreferences: SharedPreferences) {
prefs = sharedPreferences
}
/**
* Stores an Object using Moshi.
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*/
override fun putObject(key: String, value: Any) {
val adapter = moshi.adapter<Any>(value::class.java)
val json = adapter.toJson(value)
prefs.edit().putString(key, json).apply()
}
/**
* Retrieves a stored Object.
*
* @param key The name of the preference to retrieve.
* @param defaultValue Value to return if this preference does not exist.
* @return Deserialized representation of the object at [key], or [defaultValue] if unavailable
* or an [IOException] is thrown while deserializing.
*/
override fun <T : Any> getObject(key: String, defaultValue: T): T {
val adapter = moshi.adapter<T>(defaultValue::class.java)
val json = prefs.getString(key, "")
return try {
adapter.fromJson(json) as T
} catch (ex: IOException) {
Log.d(TAG, "Error deserializing object, returning default value. ${ex.message}", ex)
defaultValue
}
}
/**
* Retrieves a stored Object.
*
* @param key The name of the preference to retrieve.
* @param clazz Class that the preference will be deserialized as.
* @return Deserialized representation of the object at [key], or null if unavailable or an
* [IOException] is thrown while deserializing.
*/
override fun <T : Any> getObject(key: String, clazz: Class<T>): T? {
val adapter = moshi.adapter<T>(clazz)
val json = prefs.getString(key, "")
return try {
adapter.fromJson(json) as T
} catch (ex: IOException) {
Log.d(TAG, "Error deserializing object, returning null. ${ex.message}", ex)
null
}
}
}
| apache-2.0 | 3cc1bfdb051c52d2f2b03da756dba5c6 | 30.481481 | 99 | 0.647059 | 4.285714 | false | false | false | false |
AMARJITVS/NoteDirector | app/src/main/kotlin/com/amar/notesapp/extensions/activity.kt | 1 | 12179 | package com.amar.NoteDirector.extensions
import android.app.Activity
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.v7.app.AppCompatActivity
import android.util.DisplayMetrics
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.ViewConfiguration
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.amar.NoteDirector.activities.SimpleActivity
import com.amar.NoteDirector.helpers.NOMEDIA
import com.amar.NoteDirector.helpers.REQUEST_EDIT_IMAGE
import com.amar.NoteDirector.helpers.REQUEST_SET_AS
import com.amar.NoteDirector.models.Directory
import com.amar.NoteDirector.models.Medium
import com.amar.NoteDirector.views.MySquareImageView
import java.io.File
import java.util.*
import android.support.v4.app.ActivityCompat.startActivityForResult
import android.os.Environment.getExternalStorageDirectory
import android.support.v4.content.FileProvider
import android.util.Log
import com.amar.NoteDirector.R
import java.text.SimpleDateFormat
fun Activity.shareUri(medium: Medium, uri: Uri) {
val shareTitle = resources.getString(com.amar.NoteDirector.R.string.share_via)
Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM, uri)
type = medium.getMimeType()
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(this, shareTitle))
}
}
fun Activity.shareMedium(medium: Medium) {
val shareTitle = resources.getString(com.amar.NoteDirector.R.string.share_via)
val file = File(medium.path)
//val uri = Uri.fromFile(file)
val uri =FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file)
Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM, uri)
type = medium.getMimeType()
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(this, shareTitle))
}
}
fun Activity.sharepdf(pdf: String) {
val shareTitle = resources.getString(com.amar.NoteDirector.R.string.share_via)
val file = File(pdf)
//val uri = Uri.fromFile(file)
val uri =FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file)
Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM, uri)
type = "application/pdf"
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(this, shareTitle))
}
}
fun Activity.shareMedia(media: List<Medium>) {
val shareTitle = resources.getString(com.amar.NoteDirector.R.string.share_via)
val uris = media.map { FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", File(it.path)) } as ArrayList
Intent().apply {
action = Intent.ACTION_SEND_MULTIPLE
type = "image/* video/*"
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
startActivity(Intent.createChooser(this, shareTitle))
}
}
fun Activity.trySetAs(file: File) {
try {
//var uri = Uri.fromFile(file)
var uri=FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file)
if (!setAs(uri, file)) {
uri = getFileContentUri(file)
setAs(uri, file, false)
}
} catch (e: Exception) {
toast(com.amar.NoteDirector.R.string.unknown_error_occurred)
}
}
fun Activity.setAs(uri: Uri, file: File, showToast: Boolean = true): Boolean {
var success = false
Intent().apply {
action = Intent.ACTION_ATTACH_DATA
setDataAndType(uri, file.getMimeType("image/*"))
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val chooser = Intent.createChooser(this, getString(com.amar.NoteDirector.R.string.set_as))
if (resolveActivity(packageManager) != null) {
startActivityForResult(chooser, REQUEST_SET_AS)
success = true
} else {
if (showToast) {
toast(com.amar.NoteDirector.R.string.no_capable_app_found)
}
success = false
}
}
return success
}
fun Activity.getFileContentUri(file: File): Uri? {
val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(MediaStore.Images.Media._ID)
val selection = "${MediaStore.Images.Media.DATA} = ?"
val selectionArgs = arrayOf(file.absolutePath)
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
if (cursor?.moveToFirst() == true) {
val id = cursor.getIntValue(MediaStore.Images.Media._ID)
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "$id")
}
} finally {
cursor?.close()
}
return null
}
fun Activity.openWith(file: File, forceChooser: Boolean = true) {
//val uri = Uri.fromFile(file)
val uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file)
Intent().apply {
action = Intent.ACTION_VIEW
setDataAndType(uri, file.getMimeType())
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
if (resolveActivity(packageManager) != null) {
val chooser = Intent.createChooser(this, getString(com.amar.NoteDirector.R.string.open_with))
startActivity(if (forceChooser) chooser else this)
} else {
toast(com.amar.NoteDirector.R.string.no_app_found)
}
}
}
fun Activity.openEditor(uri: Uri, forceChooser: Boolean = false) {
Intent().apply {
action = Intent.ACTION_EDIT
setDataAndType(uri, "image/*")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
if (resolveActivity(packageManager) != null) {
val chooser = Intent.createChooser(this, getString(com.amar.NoteDirector.R.string.edit_image_with))
startActivityForResult(if (forceChooser) chooser else this, REQUEST_EDIT_IMAGE)
} else {
toast(com.amar.NoteDirector.R.string.no_editor_found)
}
}
}
fun Activity.hasNavBar(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
val display = windowManager.defaultDisplay
val realDisplayMetrics = DisplayMetrics()
display.getRealMetrics(realDisplayMetrics)
val realHeight = realDisplayMetrics.heightPixels
val realWidth = realDisplayMetrics.widthPixels
val displayMetrics = DisplayMetrics()
display.getMetrics(displayMetrics)
val displayHeight = displayMetrics.heightPixels
val displayWidth = displayMetrics.widthPixels
realWidth - displayWidth > 0 || realHeight - displayHeight > 0
} else {
val hasMenuKey = ViewConfiguration.get(applicationContext).hasPermanentMenuKey()
val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
!hasMenuKey && !hasBackKey
}
}
fun AppCompatActivity.showSystemUI() {
supportActionBar?.show()
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
fun AppCompatActivity.hideSystemUI() {
supportActionBar?.hide()
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_LOW_PROFILE or
View.SYSTEM_UI_FLAG_FULLSCREEN or
View.SYSTEM_UI_FLAG_IMMERSIVE
}
fun SimpleActivity.addNoMedia(path: String, callback: () -> Unit) {
val file = File(path, NOMEDIA)
if (file.exists())
return
if (needsStupidWritePermissions(path)) {
handleSAFDialog(file) {
try {
getFileDocument(path)?.createFile("", NOMEDIA)
} catch (e: Exception) {
toast(com.amar.NoteDirector.R.string.unknown_error_occurred)
}
}
} else {
try {
file.createNewFile()
} catch (e: Exception) {
toast(com.amar.NoteDirector.R.string.unknown_error_occurred)
}
}
scanFile(file) {
callback()
}
}
fun SimpleActivity.removeNoMedia(path: String, callback: () -> Unit) {
val file = File(path, NOMEDIA)
deleteFile(file) {
callback()
}
}
fun SimpleActivity.toggleFileVisibility(oldFile: File, hide: Boolean, callback: (newFile: File) -> Unit) {
val path = oldFile.parent
var filename = oldFile.name
filename = if (hide) {
".${filename.trimStart('.')}"
} else {
filename.substring(1, filename.length)
}
val newFile = File(path, filename)
renameFile(oldFile, newFile) {
newFile.setLastModified(System.currentTimeMillis())
callback(newFile)
}
}
fun Activity.loadImage(path: String, target: MySquareImageView, verticalScroll: Boolean) {
target.isVerticalScrolling = verticalScroll
if (path.isImageFast() || path.isVideoFast()) {
if (path.isPng()) {
loadPng(path, target)
} else {
loadJpg(path, target)
}
} else if (path.isGif()) {
if (config.animateGifs) {
loadAnimatedGif(path, target)
} else {
loadStaticGif(path, target)
}
}
}
fun Activity.loadPng(path: String, target: MySquareImageView) {
val options = RequestOptions()
.signature(path.getFileSignature())
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.format(DecodeFormat.PREFER_ARGB_8888)
val builder = Glide.with(applicationContext)
.asBitmap()
.load(path)
if (config.cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options).into(target)
}
fun Activity.loadJpg(path: String, target: MySquareImageView) {
val options = RequestOptions()
.signature(path.getFileSignature())
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
val builder = Glide.with(applicationContext)
.load(path)
if (config.cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options).transition(DrawableTransitionOptions.withCrossFade()).into(target)
}
fun Activity.loadAnimatedGif(path: String, target: MySquareImageView) {
val options = RequestOptions()
.signature(path.getFileSignature())
.diskCacheStrategy(DiskCacheStrategy.NONE)
val builder = Glide.with(applicationContext)
.asGif()
.load(path)
if (config.cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options).transition(DrawableTransitionOptions.withCrossFade()).into(target)
}
fun Activity.loadStaticGif(path: String, target: MySquareImageView) {
val options = RequestOptions()
.signature(path.getFileSignature())
.diskCacheStrategy(DiskCacheStrategy.DATA)
val builder = Glide.with(applicationContext)
.asBitmap()
.load(path)
if (config.cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options).into(target)
}
fun Activity.getCachedDirectories(): ArrayList<Directory> {
val token = object : TypeToken<List<Directory>>() {}.type
return Gson().fromJson<ArrayList<Directory>>(config.directories, token) ?: ArrayList<Directory>(1)
}
| apache-2.0 | d3602c0f269d536e43c29901ff85369b | 34.820588 | 150 | 0.6838 | 4.264356 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt | 1 | 1085 | package eu.kanade.tachiyomi.source.model
import java.io.Serializable
interface SManga : Serializable {
var url: String
var title: String
var artist: String?
var author: String?
var description: String?
var genre: String?
var status: Int
var thumbnail_url: String?
var initialized: Boolean
fun copyFrom(other: SManga) {
if (other.author != null)
author = other.author
if (other.artist != null)
artist = other.artist
if (other.description != null)
description = other.description
if (other.genre != null)
genre = other.genre
if (other.thumbnail_url != null)
thumbnail_url = other.thumbnail_url
status = other.status
if (!initialized)
initialized = other.initialized
}
companion object {
const val UNKNOWN = 0
const val ONGOING = 1
const val COMPLETED = 2
const val LICENSED = 3
fun create(): SManga {
return SMangaImpl()
}
}
} | apache-2.0 | f7ef77c94deac022eb0a7a06a0aeb46f | 17.724138 | 47 | 0.573272 | 4.656652 | false | false | false | false |
42f87d89/KotlinSynth | src/Main.kt | 1 | 3578 | import org.lwjgl.glfw.GLFW
var window: Long = 0
var freqs: Array<Float> = Array(64) { 0f }
fun main(args: Array<String>) {
initWindow()
val s = Synth(44100f, 16, 1, 64)
while (!GLFW.glfwWindowShouldClose(window)) {
GLFW.glfwPollEvents()
getInputs()
s.write(freqs) { x, y -> s.generateSine(x, y) }
s.play()
}
s.close()
}
fun initWindow() {
// Initialize GLFW. Most GLFW functions will not work before doing this.
if (!GLFW.glfwInit())
throw IllegalStateException("Unable to initialize GLFW")
// Create the window
window = GLFW.glfwCreateWindow(300, 300, "Hit Some Keys!", 0, 0)
GLFW.glfwShowWindow(window)
}
val keyMap = arrayOf(
Pair(arrayOf(GLFW.GLFW_KEY_A), 110f * Math.pow(2.0, 11.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_Z), 220f),
Pair(arrayOf(GLFW.GLFW_KEY_S), 220f * Math.pow(2.0, 1.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_X), 220f * Math.pow(2.0, 2.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_D), 220f * Math.pow(2.0, 3.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_C), 220f * Math.pow(2.0, 4.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_F), 220f * Math.pow(2.0, 5.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_V), 220f * Math.pow(2.0, 6.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_G), 220f * Math.pow(2.0, 7.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_B), 220f * Math.pow(2.0, 8.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_1, GLFW.GLFW_KEY_H), 220f * Math.pow(2.0, 9.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_Q, GLFW.GLFW_KEY_N), 220f * Math.pow(2.0, 10.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_2, GLFW.GLFW_KEY_J), 220f * Math.pow(2.0, 11.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_W, GLFW.GLFW_KEY_M), 440f),
Pair(arrayOf(GLFW.GLFW_KEY_3, GLFW.GLFW_KEY_K), 440f * Math.pow(2.0, 1.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_E, GLFW.GLFW_KEY_COMMA), 440f * Math.pow(2.0, 2.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_4, GLFW.GLFW_KEY_L), 440f * Math.pow(2.0, 3.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_R, GLFW.GLFW_KEY_PERIOD), 440f * Math.pow(2.0, 4.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_5), 440f * Math.pow(2.0, 5.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_T), 440f * Math.pow(2.0, 6.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_6), 440f * Math.pow(2.0, 7.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_Y), 440f * Math.pow(2.0, 8.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_7), 440f * Math.pow(2.0, 9.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_U), 440f * Math.pow(2.0, 10.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_8), 440f * Math.pow(2.0, 11.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_I), 880f),
Pair(arrayOf(GLFW.GLFW_KEY_9), 880f * Math.pow(2.0, 1.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_O), 880f * Math.pow(2.0, 2.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_0), 880f * Math.pow(2.0, 3.0 / 12).toFloat()),
Pair(arrayOf(GLFW.GLFW_KEY_P), 880f * Math.pow(2.0, 4.0 / 12).toFloat()))
fun getInputs() {
for ((i, e) in keyMap.withIndex()) {
var key = 0
for (k in e.first) {
if (GLFW.glfwGetKey(window, k) == 1) {
key = 1
break
}
}
if (key == 1) {
freqs[i] = e.second
} else if (key == 0) {
freqs[i] = 0f
}
}
}
| mit | 98d62051696b0337c5ed1e0ad3059807 | 46.078947 | 103 | 0.567915 | 2.76507 | false | false | false | false |
yichiuan/android-common-libs | CommonView/src/main/java/com/yichiuan/common/view/BadgeDrawable.kt | 1 | 2249 | package com.yichiuan.common.view
import android.graphics.*
import android.graphics.drawable.Drawable
import android.text.TextPaint
class BadgeDrawable(val original : Drawable) : Drawable() {
companion object {
const val TEXT_FACTOR = 0.8f
}
private val circlePaint = Paint().apply {
color = Color.RED
isAntiAlias = true
style = Paint.Style.FILL
}
private val textPaint = TextPaint().apply {
color = Color.WHITE
isAntiAlias = true
}
var count = 0
// ActionMenuItemView.setIcon() needs this to calculate the size of icon
override fun getIntrinsicWidth(): Int {
return original.intrinsicWidth
}
// ActionMenuItemView.setIcon() needs this to calculate the size of icon
override fun getIntrinsicHeight(): Int {
return original.intrinsicHeight
}
override fun draw(canvas: Canvas?) {
if (count == 0) return
canvas?.let {
original.draw(it)
drawBadge(it)
}
}
private fun drawBadge(canvas: Canvas) {
val bounds = bounds
val badgeWidth = (bounds.width() shr 1).toFloat()
val badgeHeight = (bounds.height() shr 1).toFloat()
val radius = Math.max(badgeWidth, badgeHeight) * 0.5f
val countText = count.toString()
val textBound = Rect()
textPaint.getTextBounds(countText, 0, 1, textBound)
val fontWidth = textBound.width().toFloat()
with(canvas) {
drawCircle(badgeWidth + radius, radius, radius, circlePaint)
drawText(countText,
badgeWidth + (badgeWidth - fontWidth) * 0.5f,
badgeHeight - textBound.height() * 0.5f,
textPaint)
}
}
override fun onBoundsChange(bounds: Rect?) {
super.onBoundsChange(bounds)
bounds?.let {
original.bounds = it
textPaint.textSize = (it.bottom - it.top) * 0.5f * TEXT_FACTOR
}
}
override fun setColorFilter(colorFilter: ColorFilter?) {
TODO("not implemented")
}
override fun getOpacity(): Int = PixelFormat.UNKNOWN
override fun setAlpha(alpha: Int) {
TODO("not implemented")
}
} | apache-2.0 | 1000dc9af9d6c4aaa30591925aaccfc7 | 24.862069 | 76 | 0.602045 | 4.534274 | false | false | false | false |
ylimit/PrivacyStreams | privacystreams-app/src/main/java/io/github/privacystreams/app/db/TableBgPhoto.kt | 2 | 4017 | package io.github.privacystreams.app.db
import android.Manifest
import android.content.ContentValues
import android.util.Log
import io.github.privacystreams.app.Config
import io.github.privacystreams.app.R
import io.github.privacystreams.core.Callback
import io.github.privacystreams.core.Item
import io.github.privacystreams.core.exceptions.PSException
import io.github.privacystreams.image.Image
import io.github.privacystreams.image.ImageOperators
import io.github.privacystreams.utils.StorageUtils
import io.github.privacystreams.utils.TimeUtils
import java.io.File
class TableBgPhoto(dbHelper: PStreamDBHelper) : PStreamTable(dbHelper) {
companion object {
val TABLE_NAME = "BgPhoto"
val ICON_RES_ID = R.drawable.camera;
/* Fields */
val _ID = "_id" // Long
val TIME_CREATED = Image.TIME_CREATED // Long
val IMAGE_PATH = "image_path" // Long
}
override val tableName: String = TABLE_NAME
override val iconResId: Int = ICON_RES_ID
override val sqlCreateEntries = listOf<String>(
"CREATE TABLE $TABLE_NAME (" +
"$_ID INTEGER PRIMARY KEY," +
"$TIME_CREATED INTEGER," +
"$IMAGE_PATH TEXT)",
"CREATE INDEX ${TABLE_NAME}_time_created_index on $TABLE_NAME ($TIME_CREATED)"
)
override val sqlDeleteEntries = listOf<String>(
"DROP TABLE IF EXISTS $TABLE_NAME"
)
override fun collectStreamToTable() {
val db = dbHelper.writableDatabase
this.uqi.getData(Image.takePhotoBgPeriodic(Config.COLLECT_IMAGE_CAMERA_ID, Config.COLLECT_IMAGE_INTERVAL), this.purpose)
.setField("tempPath", ImageOperators.getFilepath(Image.IMAGE_DATA))
.logAs(this.tableName)
.forEach(object : Callback<Item>() {
init {
addRequiredPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
override fun onInput(input: Item) {
val values = ContentValues()
try {
val tempPath : String = input.getValueByField("tempPath")
val tempFile = File(tempPath)
val imagePath = Config.DATA_DIR + "/image_" + TimeUtils.getTimeTag() + ".jpg"
val imageFile : File = StorageUtils.getValidFile(uqi.context, imagePath, true)
tempFile.copyTo(imageFile, true)
tempFile.delete()
values.put(IMAGE_PATH, imageFile.absolutePath)
} catch (e: Exception) {
Log.e(TABLE_NAME, "fail to write image")
e.printStackTrace()
}
values.put(TIME_CREATED, input.getAsLong(Image.TIME_CREATED))
db.insert(tableName, null, values)
increaseNumItems()
}
override fun onFail(exception: PSException) {
stopCollectService()
if (exception.isPermissionDenied) {
message.set("Denied")
}
}
})
}
class PROVIDER(): PStreamTableProvider() {
override fun provide() {
val dbHelper = PStreamDBHelper.getInstance(context)
val db = dbHelper.readableDatabase
val cur = db.query(TABLE_NAME, null, null, null, null, null, null)
while (cur.moveToNext()) {
val item = Item()
item.setFieldValue(TIME_CREATED, cur.getLong(cur.getColumnIndex(TIME_CREATED)))
item.setFieldValue(IMAGE_PATH, cur.getString(cur.getColumnIndex(IMAGE_PATH)))
output(item)
}
cur.close()
}
}
}
| apache-2.0 | 1bfce28cb7e1fadbd5196ab9ea05aa98 | 39.989796 | 128 | 0.554643 | 4.753846 | false | false | false | false |
spinnaker/kork | kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/remote/extension/RemoteExtensionTest.kt | 3 | 2121 | package com.netflix.spinnaker.kork.plugins.remote.extension
import com.netflix.spinnaker.kork.plugins.remote.extension.transport.RemoteExtensionPayload
import com.netflix.spinnaker.kork.plugins.remote.extension.transport.RemoteExtensionQuery
import com.netflix.spinnaker.kork.plugins.remote.extension.transport.RemoteExtensionResponse
import com.netflix.spinnaker.kork.plugins.remote.extension.transport.RemoteExtensionTransport
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.every
import io.mockk.mockk
import strikt.api.expectThat
import strikt.assertions.isA
class RemoteExtensionTest : JUnit5Minutests {
fun tests() = rootContext<Fixture> {
fixture {
Fixture()
}
test ("Get config type") {
val result = subject.getTypedConfig<ConfigType>()
expectThat(result).isA<ConfigType>()
}
test("Invoke is void") {
val result = subject.invoke(remoteExtensionPayload)
expectThat(result).isA<Unit>()
}
test("Returns the write response") {
every { transport.write(any()) } returns writeResponse
val result = subject.write<WriteResponse>(remoteExtensionPayload)
expectThat(result).isA<WriteResponse>()
}
test("Returns the read response") {
every { transport.read(any()) } returns readResponse
val result = subject.read<ReadResponse>(remoteExtensionQuery)
expectThat(result).isA<ReadResponse>()
}
}
private class Fixture {
val writeResponse = WriteResponse()
val readResponse = ReadResponse()
val remoteExtensionPayload = Payload()
val remoteExtensionQuery = Query()
val transport: RemoteExtensionTransport = mockk(relaxed = true)
val subject: RemoteExtension = RemoteExtension(
"remote.stage",
"netflix.remote",
"stage",
ConfigType(),
transport
)
}
private class Payload: RemoteExtensionPayload
private class Query: RemoteExtensionQuery
private class ConfigType: RemoteExtensionPointConfig
private class WriteResponse: RemoteExtensionResponse
private class ReadResponse: RemoteExtensionResponse
}
| apache-2.0 | f23f90320b786dd2e27273a931183394 | 31.630769 | 93 | 0.745875 | 4.661538 | false | true | false | false |
derkork/test-data-builder | src/main/kotlin/de/janthomae/databuilder/serialization/ColumnSelector.kt | 1 | 979 | package de.janthomae.databuilder.serialization
import kotlin.text.Regex
public class ColumnSelector(val include: Array<out String>, val exclude: Array<out String>) {
public fun accept(column: String): Boolean {
var matches = false
for (i in include) {
if (Regex(i).matches(column)) {
matches = true
break
}
}
if (!matches) return false
for (e in exclude) {
if (Regex(e).matches(column)) {
return false
}
}
return true
}
public fun include(vararg selection: String) = ColumnSelector(arrayOf(*selection) + include, exclude)
companion object {
public fun only(vararg patterns: String) = ColumnSelector(patterns, emptyArray())
public fun allBut(vararg patterns: String) = ColumnSelector(arrayOf(".*"), patterns)
public fun all() = ColumnSelector(arrayOf(".*"), emptyArray())
}
} | mit | d23ab37617565515763110f75dc820c4 | 27 | 105 | 0.590398 | 4.596244 | false | false | false | false |
bropane/Job-Seer | app/src/main/java/com/taylorsloan/jobseer/view/ViewExtension.kt | 1 | 2009 | package com.taylorsloan.jobseer.view
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.Transformation
/**
* View extensions for expanding and collapsing
*/
fun View.expand() {
val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
this.measure(widthSpec, heightSpec)
val targetHeight = this.measuredHeight
// Older versions of android (pre API 21) cancel animations for views with a height of 0.
this.layoutParams.height = 1
this.visibility = View.VISIBLE
val a = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
[email protected] = if (interpolatedTime == 1f)
ViewGroup.LayoutParams.WRAP_CONTENT
else
(targetHeight * interpolatedTime).toInt() + 1
[email protected]()
}
override fun willChangeBounds(): Boolean {
return true
}
}
// 1dp/ms
a.duration = ((targetHeight / this.context.resources.displayMetrics.density).toInt()).toLong()
this.startAnimation(a)
}
fun View.collapse() {
val initialHeight = this.measuredHeight
val a = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
if (interpolatedTime == 1f) {
[email protected] = View.GONE
} else {
[email protected] = initialHeight - (initialHeight * interpolatedTime).toInt()
[email protected]()
}
}
override fun willChangeBounds(): Boolean {
return true
}
}
// 1dp/ms
a.duration = ((initialHeight / this.context.resources.displayMetrics.density).toInt()).toLong()
this.startAnimation(a)
} | mit | e924d9a4f49dbc8b017007a872a6c832 | 31.95082 | 110 | 0.658537 | 4.876214 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/kotlin/KotlinGDXAssetsInspection.kt | 1 | 6815 | package com.gmail.blueboxware.libgdxplugin.inspections.kotlin
import com.gmail.blueboxware.libgdxplugin.inspections.checkFilename
import com.gmail.blueboxware.libgdxplugin.inspections.checkSkinFilename
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.utils.*
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.impl.VariableDescriptorImpl
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
/*
* Copyright 2017 Blue Box Ware
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class KotlinGDXAssetsInspection : LibGDXKotlinBaseInspection() {
override fun getStaticDescription() = message("gdxassets.annotation.inspection.descriptor")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
annotationEntry.analyzePartial().get(BindingContext.ANNOTATION, annotationEntry)?.type?.fqName()
?.let { fqName ->
if (fqName != ASSET_ANNOTATION_NAME) return
val classNamesOfOwningVariable = annotationEntry.getClassNamesOfOwningVariable()
annotationEntry.valueArgumentList?.arguments?.forEach { ktValueArgument ->
val name = ktValueArgument.getArgumentName()?.asName?.identifier
val arguments = ktValueArgument.getArgumentExpression().let { argumentExpression ->
if (argumentExpression is KtCallExpression) {
argumentExpression.valueArgumentList?.arguments?.map { it.getArgumentExpression() }
} else {
(argumentExpression as? KtCollectionLiteralExpression)?.getInnerExpressions()
}
}
if (name == ASSET_ANNOTATION_SKIN_PARAM_NAME) {
if (SKIN_CLASS_NAME !in classNamesOfOwningVariable) {
registerUselessParameterProblem(
holder,
ktValueArgument,
ASSET_ANNOTATION_SKIN_PARAM_NAME,
SKIN_CLASS_NAME
)
}
} else if (name == ASSET_ANNOTATION_ATLAS_PARAM_NAME) {
if (SKIN_CLASS_NAME !in classNamesOfOwningVariable && TEXTURE_ATLAS_CLASS_NAME !in classNamesOfOwningVariable) {
registerUselessParameterProblem(
holder,
ktValueArgument,
ASSET_ANNOTATION_ATLAS_PARAM_NAME,
"$SKIN_CLASS_NAME or $TEXTURE_ATLAS_CLASS_NAME"
)
}
} else if (name == ASSET_ANNOTATION_PROPERTIES_PARAM_NAME) {
if (I18NBUNDLE_CLASS_NAME !in classNamesOfOwningVariable) {
registerUselessParameterProblem(
holder,
ktValueArgument,
ASSET_ANNOTATION_PROPERTIES_PARAM_NAME,
I18NBUNDLE_CLASS_NAME
)
}
}
arguments?.forEach { argument ->
(argument as? KtStringTemplateExpression)?.asPlainString()?.let { value ->
when (name) {
ASSET_ANNOTATION_SKIN_PARAM_NAME -> checkSkinFilename(argument, value, holder)
ASSET_ANNOTATION_ATLAS_PARAM_NAME -> checkFilename(argument, value, holder)
ASSET_ANNOTATION_PROPERTIES_PARAM_NAME -> checkFilename(argument, value, holder)
}
Unit
}
}
}
if ((annotationEntry.context as? KtModifierList)?.owner is KtVariableDeclaration) {
if (classNamesOfOwningVariable.none { it in TARGETS_FOR_GDXANNOTATION }) {
holder.registerProblem(
annotationEntry,
message("gdxassets.annotation.problem.descriptor.wrong.target"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
}
}
}
}
companion object {
private fun KtAnnotationEntry.getClassNamesOfOwningVariable(): List<String> {
((context as? KtModifierList)?.owner as? KtVariableDeclaration)?.let { ktVariableDeclaration ->
(ktVariableDeclaration.descriptor as? VariableDescriptorImpl)?.type?.let { type ->
(type.constructor.declarationDescriptor as? ClassDescriptor)?.let { classDescriptor ->
return classDescriptor.supersAndThis().map { it.fqNameSafe.asString() }
}
}
}
return listOf()
}
}
private fun registerUselessParameterProblem(
holder: ProblemsHolder,
ktValueArgument: KtValueArgument,
parameterName: String,
className: String
) {
ktValueArgument.getArgumentName()?.let { argumentName ->
holder.registerProblem(
argumentName,
message(
"gdxassets.annotation.problem.descriptor.useless.parameter",
parameterName,
className
)
)
}
}
}
| apache-2.0 | 4fc164135a2ebd0df4a824d514490eb9 | 42.407643 | 140 | 0.548349 | 6.275322 | false | false | false | false |
tonyofrancis/Fetch | fetch2core/src/main/java/com/tonyodev/fetch2core/FetchFileServerUriBuilder.kt | 1 | 2154 | package com.tonyodev.fetch2core
import android.net.Uri
/**
* Builder used to create a Fetch File Server url.
* */
class FetchFileServerUriBuilder {
private var host = "00:00:00:00"
private var port = 0
private var identifier = ""
/** Set the IP address of the fetch file server
* @param hostAddress ip address
* @return builder
* */
fun setHostAddress(hostAddress: String): FetchFileServerUriBuilder {
this.host = hostAddress
return this
}
/** Set the port of the fetch file server
* @param port port
* @return builder
* */
fun setHostPort(port: Int): FetchFileServerUriBuilder {
this.port = port
return this
}
/** Set the IP address and port of the fetch file server
* @param hostAddress ip address
* @param port port
* @return builder
* */
fun setHostInetAddress(hostAddress: String, port: Int): FetchFileServerUriBuilder {
this.port = port
this.host = hostAddress
return this
}
/** Set the file resource identifier. This could be the content file id or content file name.
* @param fileResourceName resource identifier
* @return builder
* */
fun setFileResourceIdentifier(fileResourceName: String): FetchFileServerUriBuilder {
this.identifier = fileResourceName
return this
}
/** Set the file resource id identifier.
* @param fileResourceId resource id identifier
* @return builder
* */
fun setFileResourceIdentifier(fileResourceId: Long): FetchFileServerUriBuilder {
this.identifier = fileResourceId.toString()
return this
}
/**
* Create Fetch file server URI.
* */
fun build(): Uri {
return Uri.Builder()
.scheme(FETCH_URI_SCHEME)
.encodedAuthority("$host:$port")
.appendPath(identifier)
.build()
}
override fun toString(): String {
return build().toString()
}
companion object {
/** Fetch File Server Url Scheme*/
const val FETCH_URI_SCHEME = "fetchlocal"
}
} | apache-2.0 | f4ec4fff2a0f6ddb87a741fa521b335b | 24.963855 | 97 | 0.619313 | 4.642241 | false | false | false | false |
willowtreeapps/assertk | assertk/src/commonMain/kotlin/assertk/assertions/array.kt | 1 | 6831 | package assertk.assertions
import assertk.Assert
import assertk.all
import assertk.assertions.support.*
/**
* Returns an assert on the Arrays's size.
*/
fun Assert<Array<*>>.size() = prop("size") { it.size }
/**
* Asserts the array contents are equal to the expected one, using [contentDeepEquals].
* @see isNotEqualTo
*/
fun <T> Assert<Array<T>>.isEqualTo(expected: Array<T>) = given { actual ->
if (actual.contentDeepEquals(expected)) return
fail(expected, actual)
}
/**
* Asserts the array contents are not equal to the expected one, using [contentDeepEquals].
* @see isEqualTo
*/
fun <T> Assert<Array<T>>.isNotEqualTo(expected: Array<T>) = given { actual ->
if (!(actual.contentDeepEquals(expected))) return
val showExpected = show(expected)
val showActual = show(actual)
// if they display the same, only show one.
if (showExpected == showActual) {
expected("to not be equal to:$showActual")
} else {
expected(":$showExpected not to be equal to:$showActual")
}
}
/**
* Asserts the array is empty.
* @see [isNotEmpty]
* @see [isNullOrEmpty]
*/
fun Assert<Array<*>>.isEmpty() = given { actual ->
if (actual.isEmpty()) return
expected("to be empty but was:${show(actual)}")
}
/**
* Asserts the array is not empty.
* @see [isEmpty]
*/
fun Assert<Array<*>>.isNotEmpty() = given { actual ->
if (actual.isNotEmpty()) return
expected("to not be empty")
}
/**
* Asserts the array is null or empty.
* @see [isEmpty]
*/
fun Assert<Array<*>?>.isNullOrEmpty() = given { actual ->
if (actual == null || actual.isEmpty()) return
expected("to be null or empty but was:${show(actual)}")
}
/**
* Asserts the array has the expected size.
*/
fun Assert<Array<*>>.hasSize(size: Int) {
size().isEqualTo(size)
}
/**
* Asserts the array has the same size as the expected array.
*/
fun Assert<Array<*>>.hasSameSizeAs(other: Array<*>) = given { actual ->
val actualSize = actual.size
val otherSize = other.size
if (actualSize == otherSize) return
expected("to have same size as:${show(other)} ($otherSize) but was size:($actualSize)")
}
/**
* Asserts the array contains the expected element, using `in`.
* @see [doesNotContain]
*/
fun Assert<Array<*>>.contains(element: Any?) = given { actual ->
if (element in actual) return
expected("to contain:${show(element)} but was:${show(actual)}")
}
/**
* Asserts the array does not contain the expected element, using `!in`.
* @see [contains]
*/
fun Assert<Array<*>>.doesNotContain(element: Any?) = given { actual ->
if (element !in actual) return
expected("to not contain:${show(element)} but was:${show(actual)}")
}
/**
* Asserts the collection does not contain any of the expected elements.
* @see [containsAll]
*/
fun Assert<Array<*>>.containsNone(vararg elements: Any?) = given { actual ->
if (elements.none { it in actual }) {
return
}
val notExpected = elements.filter { it in actual }
expected("to contain none of:${show(elements)} but was:${show(actual)}\n elements not expected:${show(notExpected)}")
}
/**
* Asserts the array contains all the expected elements, in any order. The array may also contain
* additional elements.
* @see [containsExactly]
*/
fun Assert<Array<*>>.containsAll(vararg elements: Any?) = given { actual ->
if (elements.all { actual.contains(it) }) return
val notFound = elements.filterNot { it in actual }
expected("to contain all:${show(elements)} but was:${show(actual)}\n elements not found:${show(notFound)}")
}
/**
* Asserts the array contains only the expected elements, in any order.
* @see [containsNone]
* @see [containsExactly]
* @see [containsAll]
*/
fun Assert<Array<*>>.containsOnly(vararg elements: Any?) = given { actual ->
val notInActual = elements.filterNot { it in actual }
val notInExpected = actual.filterNot { it in elements }
if (notInExpected.isEmpty() && notInActual.isEmpty()) {
return
}
expected(StringBuilder("to contain only:${show(elements)} but was:${show(actual)}").apply {
if (notInActual.isNotEmpty()) {
append("\n elements not found:${show(notInActual)}")
}
if (notInExpected.isNotEmpty()) {
append("\n extra elements found:${show(notInExpected)}")
}
}.toString())
}
/**
* Returns an assert that assertion on the value at the given index in the array.
*
* ```
* assertThat(arrayOf(0, 1, 2)).index(1).isPositive()
* ```
*/
fun <T> Assert<Array<T>>.index(index: Int): Assert<T> =
transform(appendName(show(index, "[]"))) { actual ->
if (index in actual.indices) {
actual[index]
} else {
expected("index to be in range:[0-${actual.size}) but was:${show(index)}")
}
}
/**
* Asserts the array contains exactly the expected elements. They must be in the same order and
* there must not be any extra elements.
* @see [containsAll]
*/
fun Assert<Array<*>>.containsExactly(vararg elements: Any?) = given { actual ->
if (actual.contentEquals(elements)) return
expectedListDiff(elements.asList(), actual.asList())
}
/**
* Asserts on each item in the array. The given lambda will be run for each item.
*
* ```
* assertThat(arrayOf("one", "two")).each {
* it.hasLength(3)
* }
* ```
*/
fun <T> Assert<Array<T>>.each(f: (Assert<T>) -> Unit) = given { actual ->
all {
actual.forEachIndexed { index, item ->
f(assertThat(item, name = appendName(show(index, "[]"))))
}
}
}
/**
* Extracts a value of from each item in the array, allowing you to assert on a list of those values.
*
* ```
* assertThat(people)
* .extracting(Person::name)
* .contains("Sue", "Bob")
* ```
*/
fun <E, R> Assert<Array<E>>.extracting(f1: (E) -> R): Assert<List<R>> = transform { actual ->
actual.map(f1)
}
/**
* Extracts two values of from each item in the array, allowing you to assert on a list of paris of those values.
*
* ```
* assertThat(people)
* .extracting(Person::name, Person::age)
* .contains("Sue" to 20, "Bob" to 22)
* ```
*/
fun <E, R1, R2> Assert<Array<E>>.extracting(f1: (E) -> R1, f2: (E) -> R2): Assert<List<Pair<R1, R2>>> =
transform { actual ->
actual.map { f1(it) to f2(it) }
}
/**
* Extracts three values from each item in the array, allowing you to assert on a list of triples of those values.
*
* ```
* assertThat(people)
* .extracting(Person::name, Person::age, Person::address)
* .contains(Triple("Sue", 20, "123 Street"), Triple("Bob", 22, "456 Street")
* ```
*/
fun <E, R1, R2, R3> Assert<Array<E>>.extracting(
f1: (E) -> R1,
f2: (E) -> R2,
f3: (E) -> R3
): Assert<List<Triple<R1, R2, R3>>> = transform { actual ->
actual.map { Triple(f1(it), f2(it), f3(it)) }
}
| mit | 8ce9b8d9418305b4c22bc34cd2982492 | 28.443966 | 121 | 0.632704 | 3.604749 | false | false | false | false |
universum-studios/gradle_github_plugin | plugin/src/test/kotlin/universum/studios/gradle/github/service/api/TestChain.kt | 1 | 2357 | /*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License")
* -------------------------------------------------------------------------------------------------
* You may not use this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
* *************************************************************************************************
*/
package universum.studios.gradle.github.service.api
import okhttp3.*
import java.util.concurrent.TimeUnit
/**
* @author Martin Albedinsky
*/
class TestChain(private val request: Request, private val responseBuilder: Response.Builder = Response.Builder()
.protocol(Protocol.HTTP_1_1)
.code(200)
.message("Response message")) : Interceptor.Chain {
override fun request(): Request = request
override fun proceed(request: Request?): Response = responseBuilder.request(request!!).build()
override fun connection(): Connection? = throw UnsupportedOperationException()
override fun withConnectTimeout(timeout: Int, unit: TimeUnit?): Interceptor.Chain = throw UnsupportedOperationException()
override fun connectTimeoutMillis(): Int = throw UnsupportedOperationException()
override fun withWriteTimeout(timeout: Int, unit: TimeUnit?): Interceptor.Chain = throw UnsupportedOperationException()
override fun writeTimeoutMillis(): Int = throw UnsupportedOperationException()
override fun withReadTimeout(timeout: Int, unit: TimeUnit?): Interceptor.Chain = throw UnsupportedOperationException()
override fun readTimeoutMillis(): Int = throw UnsupportedOperationException()
override fun call(): Call = throw UnsupportedOperationException()
} | apache-2.0 | 3d17f02bf443637659b0235057e6b62d | 45.235294 | 125 | 0.610098 | 6.04359 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut10/fragmentPointLighting.kt | 2 | 9917 | package glNext.tut10
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.MouseEvent
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL3
import glNext.*
import glm.f
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import glm.quat.Quat
import glm.mat.Mat4
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import uno.buffer.intBufferBig
import uno.glm.MatrixStack
import uno.mousePole.*
import uno.time.Timer
import glm.glm
import uno.buffer.destroy
import uno.glsl.programOf
/**
* Created by GBarbieri on 23.03.2017.
*/
fun main(args: Array<String>) {
FragmentPointLighting_Next().setup("Tutorial 10 - Fragment Point Lighting")
}
class FragmentPointLighting_Next : Framework() {
lateinit var whiteDiffuseColor: ProgramData
lateinit var vertexDiffuseColor: ProgramData
lateinit var fragWhiteDiffuseColor: ProgramData
lateinit var fragVertexDiffuseColor: ProgramData
lateinit var unlit: UnlitProgData
val initialViewData = ViewData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f),
5.0f,
0.0f)
val viewScale = ViewScale(
3.0f, 20.0f,
1.5f, 0.5f,
0.0f, 0.0f, //No camera movement.
90.0f / 250.0f)
val initialObjectData = ObjectData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(1.0f, 0.0f, 0.0f, 0.0f))
val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1)
val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole)
lateinit var cylinder: Mesh
lateinit var plane: Mesh
lateinit var cube: Mesh
val projectionUniformBuffer = intBufferBig(1)
var useFragmentLighting = true
var drawColoredCyl = false
var drawLight = false
var scaleCyl = false
var lightHeight = 1.5f
var lightRadius = 1.0f
val lightTimer = Timer(Timer.Type.Loop, 5.0f)
override fun init(gl: GL3) = with(gl) {
initializePrograms(gl)
cylinder = Mesh(gl, javaClass, "tut10/UnitCylinder.xml")
plane = Mesh(gl, javaClass, "tut10/LargePlane.xml")
cube = Mesh(gl, javaClass, "tut10/UnitCube.xml")
cullFace {
enable()
cullFace = back
frontFace = cw
}
depth {
test = true
mask = true
func = lEqual
range = 0.0 .. 1.0
clamp = true
}
initUniformBuffer(projectionUniformBuffer) {
data(Mat4.SIZE, GL_DYNAMIC_DRAW)
//Bind the static buffers.
range(Semantic.Uniform.PROJECTION, 0, Mat4.SIZE)
}
}
fun initializePrograms(gl: GL3) {
whiteDiffuseColor = ProgramData(gl, "model-pos-vertex-lighting-PN.vert", "color-passthrough.frag")
vertexDiffuseColor = ProgramData(gl, "model-pos-vertex-lighting-PCN.vert", "color-passthrough.frag")
fragWhiteDiffuseColor = ProgramData(gl, "fragment-lighting-PN.vert", "fragment-lighting.frag")
fragVertexDiffuseColor = ProgramData(gl, "fragment-lighting-PCN.vert", "fragment-lighting.frag")
unlit = UnlitProgData(gl, "pos-transform.vert", "uniform-color.frag")
}
override fun display(gl: GL3) = with(gl) {
lightTimer.update()
clear {
color(0)
depth()
}
val modelMatrix = MatrixStack()
modelMatrix.setMatrix(viewPole.calcMatrix())
val worldLightPos = calcLightPosition()
val lightPosCameraSpace = modelMatrix.top() * worldLightPos
val whiteProgram = if (useFragmentLighting) fragWhiteDiffuseColor else whiteDiffuseColor
val vertColorProgram = if (useFragmentLighting) fragVertexDiffuseColor else vertexDiffuseColor
usingProgram(whiteProgram.theProgram) {
glUniform4f(whiteProgram.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f)
glUniform4f(whiteProgram.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f)
name = vertColorProgram.theProgram
glUniform4f(vertColorProgram.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f)
glUniform4f(vertColorProgram.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f)
}
modelMatrix run {
//Render the ground plane.
run {
usingProgram(whiteProgram.theProgram) {
whiteProgram.modelToCameraMatrixUnif.mat4 = top()
val invTransform = top().inverse()
val lightPosModelSpace = invTransform * lightPosCameraSpace
glUniform3f(whiteProgram.modelSpaceLightPosUnif, lightPosModelSpace)
plane.render(gl)
}
}
//Render the Cylinder
run {
applyMatrix(objectPole.calcMatrix())
if (scaleCyl)
scale(1.0f, 1.0f, 0.2f)
val invTransform = top().inverse()
val lightPosModelSpace = invTransform * lightPosCameraSpace
usingProgram {
if (drawColoredCyl) {
name = vertColorProgram.theProgram
vertColorProgram.modelToCameraMatrixUnif.mat4 = top()
glUniform3f(vertColorProgram.modelSpaceLightPosUnif, lightPosModelSpace)
cylinder.render(gl, "lit-color")
} else {
name = whiteProgram.theProgram
whiteProgram.modelToCameraMatrixUnif.mat4 = top()
glUniform3f(whiteProgram.modelSpaceLightPosUnif, lightPosModelSpace)
cylinder.render(gl, "lit")
}
}
}
if (drawLight)
run {
translate(worldLightPos)
scale(0.1f, 0.1f, 0.1f)
usingProgram(unlit.theProgram) {
unlit.modelToCameraMatrixUnif.mat4 = top()
glUniform4f(unlit.objectColorUnif, 0.8078f, 0.8706f, 0.9922f, 1.0f)
cube.render(gl, "flat")
}
}
}
}
fun calcLightPosition(): Vec4 {
val currentTimeThroughLoop = lightTimer.getAlpha()
val ret = Vec4(0.0f, lightHeight, 0.0f, 1.0f)
ret.x = glm.cos(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius
ret.z = glm.sin(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius
return ret
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val zNear = 1.0f
val zFar = 1_000f
val perspMatrix = MatrixStack()
perspMatrix.perspective(45.0f, w.f / h, zNear, zFar)
withUniformBuffer(projectionUniformBuffer) { subData(perspMatrix.top()) }
glViewport(w, h)
}
override fun mousePressed(e: MouseEvent) {
viewPole.mousePressed(e)
objectPole.mousePressed(e)
}
override fun mouseDragged(e: MouseEvent) {
viewPole.mouseDragged(e)
objectPole.mouseDragged(e)
}
override fun mouseReleased(e: MouseEvent) {
viewPole.mouseReleased(e)
objectPole.mouseReleased(e)
}
override fun mouseWheelMoved(e: MouseEvent) {
viewPole.mouseWheel(e)
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> drawColoredCyl = !drawColoredCyl
KeyEvent.VK_I -> lightHeight += if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_K -> lightHeight -= if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_L -> lightRadius += if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_J -> lightRadius -= if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_Y -> drawLight = !drawLight
KeyEvent.VK_T -> scaleCyl = !scaleCyl
KeyEvent.VK_H -> useFragmentLighting = !useFragmentLighting
KeyEvent.VK_B -> lightTimer.togglePause()
}
if (lightRadius < 0.2f)
lightRadius = 0.2f
}
override fun end(gl: GL3) = with(gl) {
glDeletePrograms(vertexDiffuseColor.theProgram, whiteDiffuseColor.theProgram, fragVertexDiffuseColor.theProgram,
fragWhiteDiffuseColor.theProgram, unlit.theProgram)
glDeleteBuffer(projectionUniformBuffer)
cylinder.dispose(gl)
plane.dispose(gl)
cube.dispose(gl)
projectionUniformBuffer.destroy()
}
inner class ProgramData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut10", vertex, fragment)
val modelSpaceLightPosUnif = gl.glGetUniformLocation(theProgram, "modelSpaceLightPos")
val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity")
val ambientIntensityUnif = gl.glGetUniformLocation(theProgram, "ambientIntensity")
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
inner class UnlitProgData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut10", vertex, fragment)
val objectColorUnif = gl.glGetUniformLocation(theProgram, "objectColor")
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
} | mit | eed905c693a8b534df04e121581fe5fa | 31.097087 | 120 | 0.608954 | 4.111526 | false | false | false | false |
ujpv/intellij-rust | src/test/kotlin/org/rust/ide/annotator/RustLineMarkerProviderTestBase.kt | 1 | 1424 | package org.rust.ide.annotator
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.rust.lang.RustFileType
import org.rust.lang.RustTestCaseBase
abstract class RustLineMarkerProviderTestBase : RustTestCaseBase() {
override val dataPath = ""
protected fun doTestByText(source: String) {
myFixture.configureByText(RustFileType, source)
myFixture.doHighlighting()
val expected = markersFrom(source)
val actual = markersFrom(myFixture.editor, myFixture.project)
assertEquals(expected.joinToString(COMPARE_SEPARATOR), actual.joinToString(COMPARE_SEPARATOR))
}
private fun markersFrom(text: String) =
text.split('\n')
.withIndex()
.filter { it.value.contains(MARKER) }
.map { Pair(it.index, it.value.substring(it.value.indexOf(MARKER) + MARKER.length).trim()) }
.toList()
private fun markersFrom(editor: Editor, project: Project) =
DaemonCodeAnalyzerImpl.getLineMarkers(editor.document, project)
.map { Pair(editor.document.getLineNumber(it.element?.textRange?.startOffset as Int),
it.lineMarkerTooltip) }
.sortedBy { it.first }
.toList()
private companion object {
val MARKER = "// - "
val COMPARE_SEPARATOR = " | "
}
}
| mit | 9d5d1f0f11469f7f50f644a03d0d116d | 36.473684 | 104 | 0.683287 | 4.477987 | false | true | false | false |
andrei-heidelbacher/algostorm | algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/physics2d/geometry2d/Rectangle.kt | 1 | 4079 | /*
* Copyright 2017 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.andreihh.algostorm.systems.physics2d.geometry2d
/**
* A rectangle which covers the area `[x, x + width - 1] x [y, y + height - 1]`.
*
* @property x the x-axis coordinate of the upper-left corner of the rectangle
* @property y the y-axis coordinate of the upper-left corner of the rectangle
* @property width the width of the rectangle
* @property height the height of the rectangle
* @throws IllegalArgumentException if [width] or [height] are not positive
*/
data class Rectangle(val x: Int, val y: Int, val width: Int, val height: Int) {
init {
require(width > 0) { "$this width must be positive!" }
require(height > 0) { "$this height must be positive!" }
}
/**
* Returns whether the two rectangles intersect (that is, there is at least
* one point `(x, y)` which is contained in both rectangles).
*
* @param other the rectangle with which the intersection is checked
* @return `true` if the two rectangles intersect, `false` otherwise
*/
fun intersects(other: Rectangle): Boolean = intersects(
x = x,
y = y,
width = width,
height = height,
otherX = other.x,
otherY = other.y,
otherWidth = other.width,
otherHeight = other.height
)
/**
* Returns whether the two rectangles intersect (that is, there is at least
* one point `(x, y)` which is contained in both rectangles).
*
* @param x the x-axis coordinate of the top-left corner of the other
* rectangle
* @param y the y-axis coordinate of the top-left corner of the other
* rectangle
* @param width the width of the other rectangle
* @param height the height of the other rectangle
* @return `true` if the two rectangles intersect, `false` otherwise
* @throws IllegalArgumentException if [width] or [height] are not positive
*/
fun intersects(x: Int, y: Int, width: Int, height: Int): Boolean =
intersects(
x = this.x,
y = this.y,
width = this.width,
height = this.height,
otherX = x,
otherY = y,
otherWidth = width,
otherHeight = height
)
/**
* Checks if the given point is inside this rectangle.
*
* @param x the x-axis coordinate of the point
* @param y the y-axis coordinate of the point
* @return `true` if the given point is contained in this rectangle, `false`
* otherwise
*/
fun contains(x: Int, y: Int): Boolean =
this.x <= x && x < this.x + width &&
this.y <= y && y < this.y + height
/**
* Checks if the given point is inside this rectangle.
*
* @param point the point which should be checked
* @return `true` if the given point is contained in this rectangle, `false`
* otherwise
*/
operator fun contains(point: Point): Boolean = contains(point.x, point.y)
/**
* Returns a copy of this rectangle with the top-left corner translated by
* the given amount.
*
* @param dx the horizontal translation amount
* @param dy the vertical translation amount (positive is down)
* @return the translated rectangle
*/
fun translate(dx: Int, dy: Int): Rectangle = copy(x = x + dx, y = y + dy)
}
| apache-2.0 | d49e229854bb74bf7322085eab23d6be | 37.121495 | 80 | 0.617798 | 4.257829 | false | false | false | false |
robinverduijn/gradle | .teamcity/Gradle_Check/configurations/GradleBuildConfigurationDefaults.kt | 1 | 7710 | package configurations
import common.Os
import common.applyDefaultSettings
import common.buildToolGradleParameters
import common.buildToolParametersString
import common.checkCleanM2
import common.compileAllDependency
import common.gradleWrapper
import common.verifyTestFilesCleanup
import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildFeatures
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildStep
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildSteps
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2018_2.FailureAction
import jetbrains.buildServer.configs.kotlin.v2018_2.ProjectFeatures
import jetbrains.buildServer.configs.kotlin.v2018_2.buildFeatures.commitStatusPublisher
import model.CIBuildModel
val killAllGradleProcesses = """
free -m
ps aux | egrep 'Gradle(Daemon|Worker)'
ps aux | egrep 'Gradle(Daemon|Worker)' | awk '{print ${'$'}2}' | xargs kill -9
free -m
ps aux | egrep 'Gradle(Daemon|Worker)' | awk '{print ${'$'}2}'
""".trimIndent()
val m2CleanScriptUnixLike = """
REPO=%teamcity.agent.jvm.user.home%/.m2/repository
if [ -e ${'$'}REPO ] ; then
tree ${'$'}REPO
rm -rf ${'$'}REPO
echo "${'$'}REPO was polluted during the build"
exit 1
else
echo "${'$'}REPO does not exist"
fi
""".trimIndent()
val m2CleanScriptWindows = """
IF exist %teamcity.agent.jvm.user.home%\.m2\repository (
TREE %teamcity.agent.jvm.user.home%\.m2\repository
RMDIR /S /Q %teamcity.agent.jvm.user.home%\.m2\repository
EXIT 1
)
""".trimIndent()
fun BuildFeatures.publishBuildStatusToGithub(model: CIBuildModel) {
if (model.publishStatusToGitHub) {
publishBuildStatusToGithub()
}
}
fun BuildFeatures.publishBuildStatusToGithub() {
commitStatusPublisher {
vcsRootExtId = "Gradle_Branches_GradlePersonalBranches"
publisher = github {
githubUrl = "https://api.github.com"
authType = personalToken {
token = "credentialsJSON:5306bfc7-041e-46e8-8d61-1d49424e7b04"
}
}
}
}
fun ProjectFeatures.buildReportTab(title: String, startPage: String) {
feature {
type = "ReportTab"
param("startPage", startPage)
param("title", title)
param("type", "BuildReportTab")
}
}
private
fun BuildSteps.tagBuild(tagBuild: Boolean = true, daemon: Boolean = true) {
if (tagBuild) {
gradleWrapper {
name = "TAG_BUILD"
executionMode = BuildStep.ExecutionMode.ALWAYS
tasks = "tagBuild"
gradleParams = "${buildToolParametersString(daemon)} -PteamCityUsername=%teamcity.username.restbot% -PteamCityPassword=%teamcity.password.restbot% -PteamCityBuildId=%teamcity.build.id% -PgithubToken=%github.ci.oauth.token%"
}
}
}
fun BuildSteps.tagBuild(model: CIBuildModel, daemon: Boolean = true) {
tagBuild(tagBuild = model.tagBuilds, daemon = daemon)
}
private
fun BaseGradleBuildType.gradleRunnerStep(model: CIBuildModel, gradleTasks: String, os: Os = Os.linux, extraParameters: String = "", daemon: Boolean = true) {
val buildScanTags = model.buildScanTags + listOfNotNull(stage?.id)
steps {
gradleWrapper {
name = "GRADLE_RUNNER"
tasks = "clean $gradleTasks"
gradleParams = (
buildToolGradleParameters(daemon) +
[email protected](os) +
listOf(extraParameters) +
"-PteamCityUsername=%teamcity.username.restbot%" +
"-PteamCityPassword=%teamcity.password.restbot%" +
"-PteamCityBuildId=%teamcity.build.id%" +
buildScanTags.map { buildScanTag(it) }
).joinToString(separator = " ")
}
}
}
private
fun BaseGradleBuildType.gradleRerunnerStep(model: CIBuildModel, gradleTasks: String, os: Os = Os.linux, extraParameters: String = "", daemon: Boolean = true) {
val buildScanTags = model.buildScanTags + listOfNotNull(stage?.id)
steps {
gradleWrapper {
name = "GRADLE_RERUNNER"
tasks = "$gradleTasks tagBuild"
executionMode = BuildStep.ExecutionMode.RUN_ON_FAILURE
gradleParams = (
buildToolGradleParameters(daemon) +
[email protected](os) +
listOf(extraParameters) +
"-PteamCityUsername=%teamcity.username.restbot%" +
"-PteamCityPassword=%teamcity.password.restbot%" +
"-PteamCityBuildId=%teamcity.build.id%" +
buildScanTags.map { buildScanTag(it) } +
"-PonlyPreviousFailedTestClasses=true" +
"-Dscan.tag.RERUN_TESTS" +
"-PgithubToken=%github.ci.oauth.token%"
).joinToString(separator = " ")
}
}
}
private
fun BaseGradleBuildType.killProcessStepIfNecessary(stepName: String, os: Os = Os.linux, daemon: Boolean = true) {
if (os == Os.windows) {
steps {
gradleWrapper {
name = stepName
executionMode = BuildStep.ExecutionMode.ALWAYS
tasks = "killExistingProcessesStartedByGradle"
gradleParams = buildToolParametersString(daemon)
}
}
}
}
fun applyDefaults(model: CIBuildModel, buildType: BaseGradleBuildType, gradleTasks: String, notQuick: Boolean = false, os: Os = Os.linux, extraParameters: String = "", timeout: Int = 90, extraSteps: BuildSteps.() -> Unit = {}, daemon: Boolean = true) {
buildType.applyDefaultSettings(os, timeout)
buildType.gradleRunnerStep(model, gradleTasks, os, extraParameters, daemon)
buildType.steps {
extraSteps()
checkCleanM2(os)
verifyTestFilesCleanup(daemon)
}
applyDefaultDependencies(model, buildType, notQuick)
}
fun applyTestDefaults(model: CIBuildModel, buildType: BaseGradleBuildType, gradleTasks: String, notQuick: Boolean = false, os: Os = Os.linux, extraParameters: String = "", timeout: Int = 90, extraSteps: BuildSteps.() -> Unit = {}, daemon: Boolean = true) {
buildType.applyDefaultSettings(os, timeout)
buildType.gradleRunnerStep(model, gradleTasks, os, extraParameters, daemon)
buildType.killProcessStepIfNecessary("KILL_PROCESSES_STARTED_BY_GRADLE", os)
buildType.gradleRerunnerStep(model, gradleTasks, os, extraParameters, daemon)
buildType.killProcessStepIfNecessary("KILL_PROCESSES_STARTED_BY_GRADLE_RERUN", os)
buildType.steps {
extraSteps()
checkCleanM2(os)
verifyTestFilesCleanup(daemon)
}
applyDefaultDependencies(model, buildType, notQuick)
}
fun buildScanTag(tag: String) = """"-Dscan.tag.$tag""""
fun buildScanCustomValue(key: String, value: String) = """"-Dscan.value.$key=$value""""
fun applyDefaultDependencies(model: CIBuildModel, buildType: BuildType, notQuick: Boolean = false) {
if (notQuick) {
// wait for quick feedback phase to finish successfully
buildType.dependencies {
dependency(AbsoluteId("${model.projectPrefix}Stage_QuickFeedback_Trigger")) {
snapshot {
onDependencyFailure = FailureAction.CANCEL
onDependencyCancel = FailureAction.CANCEL
}
}
}
}
if (buildType !is CompileAll) {
buildType.dependencies {
compileAllDependency(CompileAll.buildTypeId(model))
}
}
}
| apache-2.0 | 113d6357caf08d88d2b7adf1755c3eb2 | 36.794118 | 256 | 0.65668 | 4.30967 | false | false | false | false |
tom-kita/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/adapter/account/AccountAdapter.kt | 1 | 3535 | package com.bl_lia.kirakiratter.presentation.adapter.account
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import com.bl_lia.kirakiratter.domain.entity.Account
import com.bl_lia.kirakiratter.domain.entity.Status
import com.bl_lia.kirakiratter.presentation.adapter.timeline.TimelineItemViewHolder
import io.reactivex.subjects.PublishSubject
class AccountAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val onClickReply = PublishSubject.create<Status>()
val onClickReblog = PublishSubject.create<Status>()
val onClickFavourite = PublishSubject.create<Status>()
val onClickTranslate = PublishSubject.create<Status>()
val onClickMedia = PublishSubject.create<Triple<Status, Int, ImageView>>()
val onClickAccount = PublishSubject.create<Pair<Account, ImageView>>()
private val list: MutableList<Status> = mutableListOf()
val maxId: Int?
get() {
if (list.isEmpty()) {
return null
}
return list.last().id
}
val sinceId: String?
get() {
if (list.isEmpty()) {
return null
}
return list.first().id.toString()
}
override fun getItemCount(): Int = list.size
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(TimelineItemViewHolder.LAYOUT, parent, false)
return TimelineItemViewHolder.newInstance(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is TimelineItemViewHolder) {
holder.bind(list[position])
holder.onClickReply.subscribe(onClickReply)
holder.onClickReblog.subscribe(onClickReblog)
holder.onClickFavourite.subscribe(onClickFavourite)
holder.onClickTranslate.subscribe(onClickTranslate)
holder.onClickImage.subscribe(onClickMedia)
holder.onClickAccount.subscribe(onClickAccount)
}
}
fun reset(newList: List<Status>) {
list.clear()
list.addAll(newList)
notifyDataSetChanged()
}
fun add(newList: List<Status>) {
list.addAll(newList)
notifyDataSetChanged()
}
fun update(status: Status) {
list.indexOfFirst {
val target = it.reblog ?: it
target.id == status.id
}
.also { index ->
if (index > -1) {
list.set(index, status)
notifyItemChanged(index)
}
}
}
fun addTranslatedText(status: Status, translatedText: String) {
list.indexOfFirst {
it.id == status.id
}.also { index ->
if (index > -1) {
val s = if (status.reblog != null) {
status.copy(
reblog = status.reblog.copy(
content = status.reblog.content?.copy(translatedText = translatedText)
)
)
} else {
status.copy(
content = status.content?.copy(translatedText = translatedText)
)
}
list.set(index, s)
notifyItemChanged(index)
}
}
}
} | mit | 14e00de22a7e25159afc7ac5c009d5a7 | 32.67619 | 109 | 0.587836 | 5.086331 | false | false | false | false |
DadosAbertosBrasil/android-radar-politico | app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/miscellaneous/adapters/DeputadoRecyclerViewAdapter.kt | 1 | 5695 | package br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.adapters
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import br.edu.ifce.engcomp.francis.radarpolitico.R
import br.edu.ifce.engcomp.francis.radarpolitico.controllers.DeputadoActivity
import br.edu.ifce.engcomp.francis.radarpolitico.helpers.VolleySharedQueue
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.CDUrlFormatter
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.connection.parsers.CDXmlParser
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.connection.parsers.FrequenciaParser
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.helpers.IndexPath
import br.edu.ifce.engcomp.francis.radarpolitico.models.Deputado
import com.android.volley.Request
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import com.squareup.picasso.Picasso
import org.apache.commons.lang3.text.WordUtils
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by francisco on 11/03/16.
*/
class DeputadoRecyclerViewAdapter(val context: Context, private val dataSource: ArrayList<Deputado>) : RecyclerView.Adapter<DeputadoRecyclerViewAdapter.ViewHolder>() {
fun getItem(position: Int): Deputado {
return this.dataSource[position]
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeputadoRecyclerViewAdapter.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.adapter_politico, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: DeputadoRecyclerViewAdapter.ViewHolder, position: Int) {
val deputado = this.dataSource[position]
holder.nomePoliticoTextView.text = WordUtils.capitalize(deputado.nomeParlamentar!!.toLowerCase())
holder.partidoPoliticoTextView.text = deputado.partido
holder.fotoPoliticoImageView.loadImage(deputado.urlFoto)
holder.indexPath.setPath(0, position)
val currentCalendar = Calendar.getInstance()
val firstDayCalendar = Calendar.getInstance()
val formatter = SimpleDateFormat("dd/MM/yyyy")
firstDayCalendar.set(Calendar.DAY_OF_MONTH, 1)
val dataInicio = formatter.format(firstDayCalendar.time)
val dataFim = formatter.format(currentCalendar.time)
val urlRequest = CDUrlFormatter.listarPresencasParlamentar(dataInicio, dataFim, deputado.matricula)
val request = StringRequest(Request.Method.GET, urlRequest, {
stringResponse: String ->
val dias = CDXmlParser.parseFrequenciaFromXML(stringResponse.byteInputStream())
val diasPresente = dias.filter { it.frequencia!!.equals("Presença") }
val percentualFrequencia = (diasPresente.size.toFloat() / dias.size) * 100
holder.frasePresencasTextView.text = String.format("%4.1f%% de Presença no mês atual", percentualFrequencia)
holder.presencaMensalProgressBar.isIndeterminate = false
holder.presencaMensalProgressBar.progress = percentualFrequencia.toInt()
holder.numeroVotacoesTextView.text = diasPresente.size.toString()
}, {
volleyError: VolleyError ->
holder.frasePresencasTextView.text = "Não foi possível carregar frequencias"
holder.presencaMensalProgressBar.isIndeterminate =false
holder.presencaMensalProgressBar.progress = 0
holder.numeroVotacoesTextView.text = ""
})
VolleySharedQueue.getQueue(context)?.add(request)
}
override fun getItemCount(): Int {
return this.dataSource.size
}
fun ImageView.loadImage(url: String?){
if (!url.isNullOrBlank()) {
Picasso.with(this.context).load(url).error(R.drawable.image_icon).into(this)
}
else {
this.setImageDrawable(resources.getDrawable(R.drawable.ic_smile))
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val nomePoliticoTextView: TextView
val partidoPoliticoTextView: TextView
val fotoPoliticoImageView: ImageView
val numeroVotacoesTextView: TextView
val frasePresencasTextView: TextView
val presencaMensalProgressBar: ProgressBar
val indexPath: IndexPath
init {
this.nomePoliticoTextView = itemView.findViewById(R.id.politico_nome_text_view) as TextView
this.partidoPoliticoTextView = itemView.findViewById(R.id.politico_part_text_view) as TextView
this.fotoPoliticoImageView = itemView.findViewById(R.id.politico_image_view) as ImageView
this.numeroVotacoesTextView = itemView.findViewById(R.id.total_votacoes_text_view) as TextView
this.frasePresencasTextView = itemView.findViewById(R.id.politico_percentual_presenca_text_view) as TextView
this.presencaMensalProgressBar = itemView.findViewById(R.id.politico_presenca_progressbar) as ProgressBar
this.indexPath = IndexPath()
itemView.setOnClickListener(this)
}
override fun onClick(v: View) {
val intent = Intent(v.context, DeputadoActivity::class.java)
intent.putExtra("DEPUTADO_INFOS", dataSource[indexPath.row])
v.context.startActivity(intent)
}
}
}
| gpl-2.0 | 3957f825f86a790cbc32b3a4a331bf7d | 42.435115 | 167 | 0.734974 | 4.193073 | false | false | false | false |
JavaEden/OrchidCore | languageExtensions/OrchidDiagrams/src/main/kotlin/com/eden/orchid/languages/diagrams/PlantUmlCompiler.kt | 1 | 2962 | package com.eden.orchid.languages.diagrams
import com.eden.orchid.api.compilers.OrchidCompiler
import net.sourceforge.plantuml.FileFormat
import net.sourceforge.plantuml.FileFormatOption
import net.sourceforge.plantuml.SourceStringReader
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.nio.charset.Charset
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PlantUmlCompiler
@Inject
constructor() : OrchidCompiler(800) {
private val tags = arrayOf("uml", "salt", "math", "latex", "gantt")
override fun compile(extension: String, source: String, data: Map<String, Any>?): String {
return compileMultipleDiagrams(source)
}
override fun getOutputExtension(): String {
return "svg"
}
override fun getSourceExtensions(): Array<String> {
return arrayOf("uml")
}
private fun wrapDiagram(input: String): String {
var isWrapped = false
val source = input.trim()
for (tag in tags) {
if (source.contains("@start$tag") && source.contains("@end$tag")) {
isWrapped = true
break
}
}
return if (!isWrapped) "@startuml\n$source\n@enduml" else source
}
private fun compileMultipleDiagrams(input: String): String {
var formattedInput = wrapDiagram(input.trim())
for(tag in tags) {
val templateResult = StringBuffer(formattedInput.length)
val matcher = "@start$tag(.+?)@end$tag"
.toRegex(setOf(RegexOption.DOT_MATCHES_ALL, RegexOption.MULTILINE, RegexOption.IGNORE_CASE))
.toPattern()
.matcher(formattedInput)
while(matcher.find()) {
val content = matcher.group(1)
val replacement = compileSingleDiagram(content, tag)
matcher.appendReplacement(templateResult, "")
templateResult.append(replacement)
}
matcher.appendTail(templateResult)
formattedInput = templateResult.toString()
}
return formattedInput
}
private fun compileSingleDiagram(input: String, tag: String): String {
val formattedInput = """
@start$tag
${input.trim()}
@end$tag
""".trimIndent()
try {
// compile string to SVG
val os = ByteArrayOutputStream(1024)
val fileFormat = FileFormatOption(FileFormat.SVG)
fileFormat.hideMetadata()
val reader = SourceStringReader(formattedInput, "UTF-8")
reader.outputImage(os, fileFormat)
os.close()
var s = String(os.toByteArray(), Charset.forName("UTF-8"))
s = s.replace("<\\?(.*)\\?>".toRegex(), "") // remove XML declaration
return s
} catch (e: IOException) {
e.printStackTrace()
return ""
}
}
}
| mit | 58143337b949a3dd8006e33dafa62a61 | 28.919192 | 108 | 0.604321 | 4.599379 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/viewHolder/DiffHeaderViewHolder.kt | 2 | 2636 | package com.commit451.gitlab.viewHolder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import coil.api.load
import coil.transform.CircleCropTransformation
import com.commit451.addendum.recyclerview.bindView
import com.commit451.gitlab.R
import com.commit451.gitlab.model.api.RepositoryCommit
import com.commit451.gitlab.util.DateUtil
import com.commit451.gitlab.util.ImageUtil
/**
* Header that gives the details of a merge request
*/
class DiffHeaderViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): DiffHeaderViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.header_diff, parent, false)
return DiffHeaderViewHolder(view)
}
}
private val image: ImageView by bindView(R.id.commit_author_image)
private val textAuthor: TextView by bindView(R.id.commit_author)
private val textTime: TextView by bindView(R.id.commit_time)
private val textTitle: TextView by bindView(R.id.commit_title)
private val textMessage: TextView by bindView(R.id.commit_message)
fun bind(commit: RepositoryCommit) {
image.load(ImageUtil.getAvatarUrl(commit.authorEmail, itemView.resources.getDimensionPixelSize(R.dimen.image_size))) {
transformations(CircleCropTransformation())
}
textAuthor.text = commit.authorName
if (commit.createdAt == null) {
textTime.text = null
} else {
textTime.text = DateUtil.getRelativeTimeSpanString(itemView.context, commit.createdAt)
}
textTitle.text = commit.title
val message = extractMessage(commit.title!!, commit.message)
textMessage.text = message
textMessage.visibility = if (message.isEmpty()) View.GONE else View.VISIBLE
}
/**
* This extracts the trailing part of the textTitle as it is displayed in the GitLabService web interface
* (the commit message also contains the commit textTitle)
*/
private fun extractMessage(title: String, message: String?): String {
if (!message.isNullOrEmpty()) {
val ellipsis = title.endsWith("\u2026") && message[title.length - 1] != '\u2026'
val trailing = message.substring(title.length - if (ellipsis) 1 else 0)
return if (trailing == "\u2026") "" else ((if (ellipsis) "\u2026" else "") + trailing).trim { it <= ' ' }
}
return title
}
}
| apache-2.0 | 74aa4adbf8ba360df6e9f9e9fd7ff56f | 38.343284 | 126 | 0.698027 | 4.393333 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/module/Module.kt | 1 | 3417 | package me.mrkirby153.KirBot.module
import io.sentry.Sentry
import me.mrkirby153.KirBot.Bot
import net.dv8tion.jda.api.sharding.ShardManager
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
abstract class Module(val name: String) {
var loaded = false
val dependencies = mutableListOf<Class<out Module>>()
private val periodicTasks = mutableMapOf<Method, Int>()
abstract fun onLoad()
open fun onUnload() {}
fun load(registerListeners: Boolean = true) {
log("Starting load")
debug("Calling onLoad()")
onLoad()
debug("Registering listener")
if (registerListeners)
Bot.applicationContext.get(ShardManager::class.java).addEventListener(this)
debug("Registering periodic tasks")
this.javaClass.declaredMethods.filter {
it.getAnnotation(Periodic::class.java) != null
}.forEach { method ->
if (method.parameterCount > 0) {
log("Method ${method.name} has parameters. Periodic tasks must not have parameters")
return@forEach
}
method.isAccessible = true
periodicTasks[method] = method.getAnnotation(Periodic::class.java).interval
}
if (periodicTasks.count() > 0)
debug("Registered ${periodicTasks.count()} periodic tasks")
debug("Load complete")
loaded = true
}
fun unload(unregisterListener: Boolean = true) {
log("Starting unload")
if (!loaded) {
throw IllegalStateException(
"Attempting to unload a module that has already been unloaded")
}
debug("Calling onUnload()")
onUnload()
debug("Removing listener")
if (unregisterListener)
Bot.applicationContext.get(ShardManager::class.java).removeEventListener(this)
periodicTasks.clear()
log("Unloading complete")
loaded = false
}
fun log(message: Any) {
Bot.LOG.info("[${name.toUpperCase()}] $message")
}
fun debug(message: Any) {
Bot.LOG.debug("[${name.toUpperCase()}] $message")
}
override fun toString(): String {
return "Module(name='$name', loaded=$loaded)"
}
fun getProp(string: String, default: String? = null): String? = Bot.properties.getProperty(
string) ?: default
fun triggerPeriodicTasks(count: Int) {
if (count > 0) {
this.periodicTasks.forEach { method, interval ->
if ((count % interval) == 0) {
try {
method.invoke(this@Module)
} catch (e: InvocationTargetException) {
log("An error occurred when executing ${method.name}: ${e.targetException}")
Sentry.getContext().addExtra("method", method.name)
Sentry.capture(e.targetException)
Sentry.clearContext()
} catch (e: Throwable) {
log("An error occurred when executing ${method.name}: $e")
Sentry.getContext().addExtra("method", method.name)
Sentry.capture(e)
Sentry.clearContext()
}
}
}
}
}
protected annotation class Periodic(val interval: Int)
} | mit | 93dc360fd215c7d74fc54d31c84a711c | 33.18 | 100 | 0.574773 | 4.96657 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/modules/Database.kt | 1 | 955 | package me.mrkirby153.KirBot.modules
import com.mrkirby153.bfs.connection.ConnectionFactory
import com.mrkirby153.bfs.query.QueryBuilder
import me.mrkirby153.KirBot.database.DatabaseConnection
import me.mrkirby153.KirBot.module.Module
class Database : Module("database") {
lateinit var database: DatabaseConnection
lateinit var db: Database
override fun onLoad() {
val host = getProp("database-host") ?: "localhost"
val port = getProp("database-port")?.toInt() ?: 3306
val database = getProp("database") ?: "KirBot"
val username = getProp("database-username") ?: "root"
val password = getProp("database-password") ?: ""
log("Connecting to database $database at $host:$port ($username)")
this.database = DatabaseConnection(host, port, database, username, password)
QueryBuilder.defaultConnectionFactory = ConnectionFactory { [email protected]() }
}
} | mit | aba113bed5b5b5871753fd772b3fbe61 | 35.769231 | 108 | 0.710995 | 4.613527 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/search/view/SearchInputUi.kt | 1 | 16821 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.search.view
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.speech.RecognizerIntent
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.model.OptionMenu
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.search.SearchCategory
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.libs.db.DatabaseFinder
import jp.toastkid.yobidashi.libs.network.NetworkChecker
import jp.toastkid.yobidashi.search.SearchAction
import jp.toastkid.yobidashi.search.favorite.FavoriteSearchListUi
import jp.toastkid.yobidashi.search.history.SearchHistoryListUi
import jp.toastkid.yobidashi.search.trend.TrendApi
import jp.toastkid.yobidashi.search.url_suggestion.UrlItemQueryUseCase
import jp.toastkid.yobidashi.search.usecase.QueryingUseCase
import jp.toastkid.yobidashi.search.viewmodel.SearchUiViewModel
import jp.toastkid.yobidashi.search.voice.VoiceSearchIntentFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.IOException
@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
@Composable
fun SearchInputUi(
inputQuery: String? = null,
currentTitle: String? = null,
currentUrl: String? = null
) {
val context = LocalContext.current as? ComponentActivity ?: return
val preferenceApplier = PreferenceApplier(context)
val activityViewModelProvider = ViewModelProvider(context)
val contentViewModel = activityViewModelProvider.get(ContentViewModel::class.java)
val categoryName = remember {
mutableStateOf(
(SearchCategory.findByUrlOrNull(currentUrl)?.name
?: PreferenceApplier(context).getDefaultSearchEngine())
?: SearchCategory.getDefaultCategoryName()
)
}
val viewModel = viewModel(SearchUiViewModel::class.java)
val queryingUseCase = remember {
val database = DatabaseFinder().invoke(context)
QueryingUseCase(
viewModel,
preferenceApplier,
UrlItemQueryUseCase(
{
viewModel.urlItems.clear()
viewModel.urlItems.addAll(it)
},
database.bookmarkRepository(),
database.viewHistoryRepository(),
{ }
),
database.favoriteSearchRepository(),
database.searchHistoryRepository()
)
}
val keyboardController = LocalSoftwareKeyboardController.current
val localLifecycleOwner = LocalLifecycleOwner.current
if (viewModel.openFavoriteSearch.value.not()) {
LaunchedEffect(key1 = localLifecycleOwner, block = {
contentViewModel.replaceAppBarContent {
val focusRequester = remember { FocusRequester() }
val spinnerOpen = remember { mutableStateOf(false) }
val useVoice = remember { mutableStateOf(false) }
val voiceSearchLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
if (activityResult.resultCode != Activity.RESULT_OK) {
return@rememberLauncherForActivityResult
}
val result =
activityResult.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
if (result == null || result.size == 0) {
return@rememberLauncherForActivityResult
}
viewModel.suggestions.clear()
viewModel.suggestions.addAll(result)
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.height(dimensionResource(id = R.dimen.toolbar_height))
) {
SearchCategorySpinner(spinnerOpen, categoryName)
TextField(
value = viewModel.input.value,
onValueChange = { text ->
viewModel.setInput(text)
useVoice.value = text.text.isBlank()
queryingUseCase.send(text.text)
},
label = {
Text(
stringResource(id = R.string.title_search),
color = MaterialTheme.colors.onPrimary
)
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
cursorColor = MaterialTheme.colors.onPrimary,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
singleLine = true,
textStyle = TextStyle(
color = MaterialTheme.colors.onPrimary,
textAlign = TextAlign.Start,
),
trailingIcon = {
Icon(
Icons.Filled.Clear,
contentDescription = "clear text",
tint = MaterialTheme.colors.onPrimary,
modifier = Modifier
.clickable {
viewModel.setInput(TextFieldValue())
}
)
},
maxLines = 1,
keyboardActions = KeyboardActions {
keyboardController?.hide()
search(context, contentViewModel, currentUrl, categoryName.value, viewModel.input.value.text)
},
keyboardOptions = KeyboardOptions(
autoCorrect = true,
imeAction = ImeAction.Search
),
modifier = Modifier
.weight(1f)
.padding(end = 4.dp)
.background(Color.Transparent)
.focusRequester(focusRequester)
)
Icon(
painterResource(id = if (useVoice.value) R.drawable.ic_mic else R.drawable.ic_search_white),
contentDescription = stringResource(id = R.string.title_search_action),
tint = MaterialTheme.colors.onPrimary,
modifier = Modifier
.width(32.dp)
.fillMaxHeight()
.align(Alignment.CenterVertically)
.combinedClickable(
true,
onClick = {
keyboardController?.hide()
if (useVoice.value) {
try {
voiceSearchLauncher.launch(VoiceSearchIntentFactory().invoke())
} catch (e: ActivityNotFoundException) {
Timber.e(e)
}
return@combinedClickable
}
search(
context,
contentViewModel,
currentUrl,
categoryName.value,
viewModel.input.value.text
)
},
onLongClick = {
search(
context,
contentViewModel,
currentUrl,
categoryName.value,
viewModel.input.value.text,
true
)
}
)
)
}
LaunchedEffect(key1 = queryingUseCase, block = {
val text = inputQuery ?: ""
viewModel.setInput(TextFieldValue(text, TextRange(0, text.length), TextRange(text.length)))
focusRequester.requestFocus()
CoroutineScope(Dispatchers.IO).launch {
val trendItems = try {
TrendApi()()
} catch (e: IOException) {
Timber.e(e)
null
}
viewModel.trends.clear()
val taken = trendItems?.take(10)
if (taken.isNullOrEmpty()) {
return@launch
}
viewModel.trends.addAll(taken)
}
queryingUseCase.withDebounce()
})
}
})
}
if (viewModel.enableBackHandler().not()) {
SearchContentsUi(viewModel, currentTitle, currentUrl)
}
if (viewModel.openSearchHistory.value) {
SearchHistoryListUi()
}
if (viewModel.openFavoriteSearch.value) {
FavoriteSearchListUi()
}
BackHandler(viewModel.enableBackHandler()) {
viewModel.closeOption()
}
viewModel.search
.observe(localLifecycleOwner, Observer { event ->
val searchEvent = event?.getContentIfNotHandled() ?: return@Observer
keyboardController?.hide()
search(
context,
contentViewModel,
currentUrl,
searchEvent.category ?: categoryName.value,
searchEvent.query,
searchEvent.background
)
})
/*LaunchedEffect(key1 = queryingUseCase.hashCode(), block = {
val text = inputQuery ?: ""
viewModel.setInput(TextFieldValue(text, TextRange(0, text.length), TextRange(text.length)))
queryingUseCase.withDebounce()
CoroutineScope(Dispatchers.IO).launch {
val trendItems = try {
TrendApi()()
} catch (e: IOException) {
Timber.e(e)
null
}
viewModel.trends.clear()
val taken = trendItems?.take(10)
if (taken.isNullOrEmpty()) {
return@launch
}
viewModel.trends.addAll(taken)
}
})*/
DisposableEffect(key1 = localLifecycleOwner, effect = {
onDispose {
queryingUseCase.dispose()
}
})
val isEnableSuggestion = remember { mutableStateOf(preferenceApplier.isEnableSuggestion) }
val isEnableSearchHistory = remember { mutableStateOf(preferenceApplier.isEnableSearchHistory) }
contentViewModel.optionMenus(
OptionMenu(
titleId = R.string.title_context_editor_double_quote,
action = {
val queryOrEmpty = viewModel.input.value.text
if (queryOrEmpty.isNotBlank()) {
viewModel.putQuery("\"$queryOrEmpty\"")
}
}
),
OptionMenu(
titleId = R.string.title_context_editor_set_default_search_category,
action = {
categoryName.value = preferenceApplier.getDefaultSearchEngine()
?: SearchCategory.getDefaultCategoryName()
}
),
OptionMenu(
titleId = R.string.title_enable_suggestion,
action = {
preferenceApplier.switchEnableSuggestion()
isEnableSuggestion.value = preferenceApplier.isEnableSuggestion
if (preferenceApplier.isEnableSuggestion.not()) {
viewModel.suggestions.clear()
}
},
checkState = isEnableSuggestion
),
OptionMenu(
titleId = R.string.title_use_search_history,
action = {
preferenceApplier.switchEnableSearchHistory()
isEnableSearchHistory.value = preferenceApplier.isEnableSearchHistory
if (preferenceApplier.isEnableSearchHistory.not()) {
viewModel.searchHistories.clear()
}
},
checkState = isEnableSearchHistory
),
OptionMenu(
titleId = R.string.title_favorite_search,
action = {
viewModel.openFavoriteSearch()
}
),
OptionMenu(
titleId = R.string.title_search_history,
action = {
viewModel.openSearchHistory()
}
)
)
}
private inline fun search(
context: Context,
contentViewModel: ContentViewModel?,
currentUrl: String?,
category: String,
query: String,
onBackground: Boolean = false
) {
if (NetworkChecker.isNotAvailable(context)) {
contentViewModel?.snackShort("Network is not available...")
return
}
if (query.isBlank()) {
contentViewModel?.snackShort(R.string.message_should_input_keyword)
return
}
SearchAction(context, category, query, currentUrl, onBackground).invoke()
} | epl-1.0 | 16834b6151f164f48c36635f72f4be01 | 38.957245 | 123 | 0.559776 | 6.132337 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/rankings/RankingsViewModel.kt | 1 | 10626 | package com.garpr.android.features.rankings
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.garpr.android.data.models.AbsPlayer
import com.garpr.android.data.models.FavoritePlayer
import com.garpr.android.data.models.Optional
import com.garpr.android.data.models.PreviousRank
import com.garpr.android.data.models.RankingsBundle
import com.garpr.android.data.models.Region
import com.garpr.android.extensions.takeSingle
import com.garpr.android.extensions.truncate
import com.garpr.android.features.common.viewModels.BaseViewModel
import com.garpr.android.features.player.SmashRosterAvatarUrlHelper
import com.garpr.android.misc.Schedulers
import com.garpr.android.misc.Searchable
import com.garpr.android.misc.ThreadUtils
import com.garpr.android.misc.Timber
import com.garpr.android.repositories.IdentityRepository
import com.garpr.android.repositories.RankingsRepository
import com.garpr.android.sync.roster.SmashRosterStorage
import com.garpr.android.sync.roster.SmashRosterSyncManager
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import java.text.NumberFormat
import java.util.Collections
class RankingsViewModel(
private val identityRepository: IdentityRepository,
private val rankingsRepository: RankingsRepository,
private val schedulers: Schedulers,
private val smashRosterAvatarUrlHelper: SmashRosterAvatarUrlHelper,
private val smashRosterStorage: SmashRosterStorage,
private val smashRosterSyncManager: SmashRosterSyncManager,
private val threadUtils: ThreadUtils,
private val timber: Timber
) : BaseViewModel(), Searchable {
private val _stateLiveData = MutableLiveData<State>()
val stateLiveData: LiveData<State> = _stateLiveData
private var state: State = State()
set(value) {
field = value
_stateLiveData.postValue(value)
}
init {
initListeners()
}
@WorkerThread
private fun createList(bundle: RankingsBundle?, identity: FavoritePlayer?): List<ListItem>? {
val rankings = bundle?.rankings
if (rankings.isNullOrEmpty()) {
return null
}
val previousRankSupported = rankings.any { it.previousRank != null }
val list = mutableListOf<ListItem>()
bundle.rankings.mapTo(list) { player ->
val previousRank = if (previousRankSupported) {
checkNotNull(player.previousRank) {
"This is impossible here if RankedPlayerConverter does its job correctly."
}
if (player.rank == player.previousRank || player.previousRank == Int.MIN_VALUE) {
PreviousRank.INVISIBLE
} else if (player.rank < player.previousRank) {
PreviousRank.INCREASE
} else {
PreviousRank.DECREASE
}
} else {
PreviousRank.GONE
}
ListItem.Player(
player = player,
isIdentity = AbsPlayer.safeEquals(identity, player),
previousRank = previousRank,
rank = NUMBER_FORMAT.format(player.rank),
rating = player.rating.truncate()
)
}
insertOrRemoveIdentityAtFrontOfList(
list = list,
identity = identity
)
return list
}
fun fetchRankings(region: Region) {
state = state.copy(isFetching = true)
disposables.add(rankingsRepository.getRankings(region)
.zipWith(identityRepository.identityObservable.takeSingle(),
BiFunction<RankingsBundle, Optional<FavoritePlayer>,
Pair<RankingsBundle, Optional<FavoritePlayer>>> { t1, t2 ->
Pair(t1, t2)
})
.subscribeOn(schedulers.background)
.observeOn(schedulers.background)
.subscribe({ (bundle, identity) ->
val list = createList(bundle, identity.orNull())
state = state.copy(
hasError = false,
isEmpty = list.isNullOrEmpty(),
isFetching = false,
list = list,
searchResults = null,
rankingsBundle = bundle
)
}, {
timber.e(TAG, "Error fetching rankings", it)
state = state.copy(
hasError = true,
isEmpty = false,
isFetching = false,
list = null,
searchResults = null,
rankingsBundle = null
)
}))
}
private fun initListeners() {
disposables.add(Observable.combineLatest(
identityRepository.identityObservable,
smashRosterSyncManager.isSyncingObservable
.filter { isSyncing -> !isSyncing },
BiFunction<Optional<FavoritePlayer>, Boolean,
Optional<FavoritePlayer>> { t1, t2 ->
t1
})
.subscribeOn(schedulers.background)
.observeOn(schedulers.background)
.subscribe { identity ->
refreshListItems(identity.orNull())
})
}
@WorkerThread
private fun insertOrRemoveIdentityAtFrontOfList(
list: MutableList<ListItem>,
identity: FavoritePlayer?
) {
list.removeAll { listItem -> listItem is ListItem.Identity }
if (identity == null) {
return
}
val listItem = list.filterIsInstance(ListItem.Player::class.java)
.firstOrNull { listItem -> listItem.isIdentity }
val smashCompetitor = smashRosterStorage.getSmashCompetitor(
region = identity.region,
playerId = identity.id
)
val avatar = smashRosterAvatarUrlHelper.getAvatarUrl(
avatarPath = smashCompetitor?.avatar?.largeButFallbackToMediumThenOriginalThenSmall
)
val tag: String = if (smashCompetitor?.tag?.isNotBlank() == true) {
smashCompetitor.tag
} else if (listItem?.player?.name?.isNotBlank() == true) {
listItem.player.name
} else {
identity.name
}
list.add(0, if (listItem == null) {
// the user's identity does not exist in the rankings list
ListItem.Identity(
player = identity,
previousRank = PreviousRank.GONE,
avatar = avatar,
tag = tag
)
} else {
ListItem.Identity(
player = identity,
previousRank = listItem.previousRank,
avatar = avatar,
rank = listItem.rank,
rating = listItem.rating,
tag = tag
)
})
}
@WorkerThread
private fun refreshListItems(identity: FavoritePlayer?) {
val list = refreshListItems(state.list, identity)
val searchResults = refreshListItems(state.searchResults, identity)
state = state.copy(
list = list,
searchResults = searchResults
)
}
@WorkerThread
private fun refreshListItems(list: List<ListItem>?, identity: FavoritePlayer?): List<ListItem>? {
return if (list.isNullOrEmpty()) {
list
} else {
val newList = mutableListOf<ListItem>()
list.mapTo(newList) { listItem ->
if (listItem is ListItem.Player) {
listItem.copy(isIdentity = listItem.player == identity)
} else {
listItem
}
}
insertOrRemoveIdentityAtFrontOfList(
list = newList,
identity = identity
)
newList
}
}
override fun search(query: String?) {
threadUtils.background.submit {
val results = search(query, state.list)
state = state.copy(searchResults = results)
}
}
@WorkerThread
private fun search(query: String?, list: List<ListItem>?): List<ListItem>? {
if (query.isNullOrBlank() || list.isNullOrEmpty()) {
return null
}
val trimmedQuery = query.trim()
val results = list
.filterIsInstance(ListItem.Player::class.java)
.filter { listItem ->
listItem.player.name.contains(trimmedQuery, ignoreCase = true)
}
return if (results.isEmpty()) {
Collections.singletonList(ListItem.NoResults(trimmedQuery))
} else {
results
}
}
companion object {
private const val TAG = "RankingsViewModel"
private val NUMBER_FORMAT = NumberFormat.getInstance()
}
sealed class ListItem {
abstract val listId: Long
class Identity(
val player: FavoritePlayer,
val previousRank: PreviousRank,
val avatar: String? = null,
val rank: String? = null,
val rating: String? = null,
val tag: String
) : ListItem() {
override val listId: Long = Long.MIN_VALUE + 1L
}
class NoResults(
val query: String
) : ListItem() {
override val listId: Long = Long.MIN_VALUE + 2L
}
data class Player(
val player: AbsPlayer,
val isIdentity: Boolean,
val previousRank: PreviousRank,
val rank: String,
val rating: String
) : ListItem() {
override val listId: Long = player.hashCode().toLong()
}
}
data class State(
val hasError: Boolean = false,
val isEmpty: Boolean = false,
val isFetching: Boolean = false,
val list: List<ListItem>? = null,
val searchResults: List<ListItem>? = null,
val rankingsBundle: RankingsBundle? = null
)
}
| unlicense | 750632c73d7db14ac01542cbf997b19b | 33.38835 | 101 | 0.556465 | 5.525741 | false | false | false | false |
jtlalka/fiszki | app/src/main/kotlin/net/tlalka/fiszki/domain/services/CacheService.kt | 1 | 1122 | package net.tlalka.fiszki.domain.services
import android.util.Log
import net.tlalka.fiszki.core.annotations.SessionScope
import net.tlalka.fiszki.model.entities.Lesson
import net.tlalka.fiszki.model.entities.Word
import java.util.WeakHashMap
import javax.inject.Inject
@SessionScope
class CacheService @Inject constructor() {
@Inject
lateinit var lessonService: LessonService
@Inject
lateinit var wordService: WordService
private val lessons = WeakHashMap<Long, Lesson>()
private val words = WeakHashMap<Long, List<Word>>()
fun getLesson(lessonId: Long): Lesson {
if (lessons[lessonId] == null) {
lessons[lessonId] = lessonService.getLesson(lessonId)
Log.i(CacheService::class.java.simpleName, "Cache for lessons: $lessonId")
}
return lessons[lessonId]!!
}
fun getWords(lesson: Lesson): List<Word> {
if (words[lesson.id] == null) {
words[lesson.id] = wordService.getWords(lesson)
Log.i(CacheService::class.java.simpleName, "Cache for words")
}
return this.words[lesson.id]!!
}
}
| mit | be03686eb990ebec57221d6328921efe | 29.324324 | 86 | 0.684492 | 4.10989 | false | false | false | false |
rei-m/android_hyakuninisshu | feature/examresult/src/main/java/me/rei_m/hyakuninisshu/feature/examresult/ui/widget/ExamResultView.kt | 1 | 4350 | /*
* Copyright (c) 2020. Rei Matsushita.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.rei_m.hyakuninisshu.feature.examresult.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import me.rei_m.hyakuninisshu.feature.examresult.R
import me.rei_m.hyakuninisshu.state.question.model.QuestionResult
class ExamResultView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
init {
initialize(context)
}
var questionResultList: List<QuestionResult>? = null
set(value) {
field = value
questionResultList?.forEachIndexed { index, questionResult ->
with(findViewById<CellView>(cellViewIdList[index])) {
setResult(questionResult.karutaNoText, questionResult.isCorrect)
setOnClickListener {
listener?.onClick(questionResult.karutaNo)
}
}
}
}
var listener: OnClickItemListener? = null
interface OnClickItemListener {
fun onClick(karutaNo: Int)
}
private fun initialize(context: Context) {
orientation = VERTICAL
for (i in 0 until NUMBER_OF_KARUTA_ROW) {
addView(createRow(context, i))
}
}
private fun createRow(context: Context, rowIndex: Int): LinearLayout {
val linearLayout = LinearLayout(context).apply {
orientation = HORIZONTAL
}
val layoutParams = LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
val currentRowTopIndex = rowIndex * NUMBER_OF_KARUTA_PER_ROW
for (i in 0 until NUMBER_OF_KARUTA_PER_ROW) {
val totalIndex = currentRowTopIndex + i
val cellView = CellView(context).apply {
id = cellViewIdList[totalIndex]
gravity = Gravity.CENTER
}
linearLayout.addView(cellView, layoutParams)
}
return linearLayout
}
inner class CellView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
init {
initialize(context)
}
private lateinit var textKarutaNo: TextView
private lateinit var imageCorrect: ImageView
private lateinit var imageIncorrect: ImageView
private fun initialize(context: Context) {
val view = View.inflate(context, R.layout.view_karuta_exam_result_cell, this)
textKarutaNo = view.findViewById(R.id.text_karuta_no)
imageCorrect = view.findViewById(R.id.image_quiz_result_correct)
imageIncorrect = view.findViewById(R.id.image_quiz_result_incorrect)
}
fun setResult(karutaNoText: String, isCorrect: Boolean) {
textKarutaNo.text = karutaNoText
if (isCorrect) {
imageCorrect.visibility = View.VISIBLE
} else {
imageIncorrect.visibility = View.VISIBLE
}
}
}
companion object {
private const val NUMBER_OF_KARUTA_PER_ROW = 5
private const val NUMBER_OF_CELL = 100
private const val NUMBER_OF_KARUTA_ROW = NUMBER_OF_CELL / NUMBER_OF_KARUTA_PER_ROW
private val cellViewIdList = IntArray(NUMBER_OF_CELL)
init {
for (i in 0 until NUMBER_OF_CELL) {
cellViewIdList[i] = View.generateViewId()
}
}
}
}
| apache-2.0 | 1a61a6f2959ca89cce2d4a93916a6177 | 30.751825 | 90 | 0.642529 | 4.53125 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.