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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/selfAssignment/applyCorrect.kt | 9 | 287 | // PROBLEM: none
// WITH_STDLIB
// Minimized from KT-20714 itself
class ServerUser {
var id = ""
var city = ""
fun toClientUser() = ClientUser().apply {
id = <caret>[email protected]
city = [email protected]
}
}
class ClientUser {
var id = ""
} | apache-2.0 | 0ab06d09ee448632266f1312a3cd7637 | 15.941176 | 45 | 0.58885 | 3.376471 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/checker/ClassObjectInEnum.kt | 2 | 386 | // FIR_COMPARISON
enum class E {
ENTRY;
companion object {
fun foo(): E = ENTRY
fun bar(): Array<E> = values()
fun baz(): E = valueOf("ENTRY")
val valuez = values()
}
fun oof(): E = ENTRY
fun rab(): Array<E> = values()
fun zab(): E = valueOf("ENTRY")
}
fun foo() = E.ENTRY
fun bar() = E.values()
fun baz() = E.valueOf("ENTRY")
| apache-2.0 | 1fde5b0de550b10b89d746372cb29d97 | 19.315789 | 39 | 0.518135 | 3.327586 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/shadermodel/ShadowMapNode.kt | 1 | 16526 | package de.fabmax.kool.pipeline.shadermodel
import de.fabmax.kool.KoolException
import de.fabmax.kool.math.Vec2f
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.math.Vec4f
import de.fabmax.kool.pipeline.ShaderStage
import de.fabmax.kool.pipeline.UniformMat4f
import de.fabmax.kool.pipeline.UniformMat4fv
import de.fabmax.kool.util.CascadedShadowMap
import de.fabmax.kool.util.SimpleShadowMap
abstract class ShadowMapNode {
var lightIndex = 0
open var depthMap: Texture2dNode? = null
abstract val outShadowFac: ShaderNodeIoVar
}
class SimpleShadowMapNode(shadowMap: SimpleShadowMap, vertexGraph: ShaderGraph, fragmentGraph: ShaderGraph) : ShadowMapNode() {
private val ifPosLightSpace = StageInterfaceNode("posLightSpace_${vertexGraph.nextNodeId}", vertexGraph, fragmentGraph)
private val ifNrmZLightSpace = StageInterfaceNode("nrmZLightSpace_${vertexGraph.nextNodeId}", vertexGraph, fragmentGraph)
val vertexNode = SimpleShadowMapTransformNode(shadowMap, vertexGraph)
val fragmentNode = SimpleShadowMapFragmentNode(shadowMap, fragmentGraph)
var inWorldPos: ShaderNodeIoVar
get() = vertexNode.inWorldPos
set(value) { vertexNode.inWorldPos = value }
var inWorldNrm: ShaderNodeIoVar
get() = vertexNode.inWorldNrm
set(value) { vertexNode.inWorldNrm = value }
var inDepthOffset: ShaderNodeIoVar
get() = fragmentNode.inDepthOffset
set(value) { fragmentNode.inDepthOffset = value }
override var depthMap: Texture2dNode?
get() = fragmentNode.depthMap
set(value) { fragmentNode.depthMap = value }
override val outShadowFac: ShaderNodeIoVar
get() = fragmentNode.outShadowFac
init {
this.lightIndex = shadowMap.lightIndex
vertexGraph.addNode(ifPosLightSpace.vertexNode)
vertexGraph.addNode(ifNrmZLightSpace.vertexNode)
fragmentGraph.addNode(ifPosLightSpace.fragmentNode)
fragmentGraph.addNode(ifNrmZLightSpace.fragmentNode)
ifPosLightSpace.input = vertexNode.outPosLightSpace
fragmentNode.inPosLightSpace = ifPosLightSpace.output
ifNrmZLightSpace.input = vertexNode.outNrmZLightSpace
fragmentNode.inNrmZLightSpace = ifNrmZLightSpace.output
}
}
class SimpleShadowMapTransformNode(val shadowMap: SimpleShadowMap, graph: ShaderGraph) : ShaderNode("lightSpaceTf_${graph.nextNodeId}", graph) {
val uShadowMapVP = UniformMat4f("${name}_shadowMapVP")
var inWorldPos: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO))
var inWorldNrm: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO))
val outPosLightSpace = ShaderNodeIoVar(ModelVar4f("${name}_posLightSpace"), this)
val outNrmZLightSpace = ShaderNodeIoVar(ModelVar1f("${name}_nrmZLightSpace"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inWorldPos, inWorldNrm)
shaderGraph.descriptorSet.apply {
uniformBuffer(name, shaderGraph.stage) {
+{ uShadowMapVP }
onUpdate = { _, _ ->
uShadowMapVP.value.set(shadowMap.lightViewProjMat)
}
}
}
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("""
${outPosLightSpace.declare()} = ${uShadowMapVP.name} * vec4(${inWorldPos.ref3f()}, 1.0);
${outNrmZLightSpace.declare()} = (${uShadowMapVP.name} * vec4(${inWorldNrm.ref3f()}, 0.0)).z;
""")
}
}
class SimpleShadowMapFragmentNode(shadowMap: SimpleShadowMap, graph: ShaderGraph) : ShaderNode("shadowMap_${graph.nextNodeId}", graph, ShaderStage.FRAGMENT_SHADER.mask) {
var depthMap: Texture2dNode? = null
var inDepthOffset: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar1fConst(shadowMap.shaderDepthOffset))
var inPosLightSpace: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO))
var inNrmZLightSpace: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO))
val outShadowFac = ShaderNodeIoVar(ModelVar1f("${name}_shadowFac"), this)
var useDithering = false
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inDepthOffset, inPosLightSpace, inNrmZLightSpace)
dependsOn(depthMap ?: throw KoolException("Depth map input not set"))
}
override fun generateCode(generator: CodeGenerator) {
val depthTex = depthMap ?: throw KoolException("Depth map input not set")
val sampleBuilder = StringBuilder()
var nSamples = 0
if (useDithering) {
// dithered pcf shadow map sampling
// https://developer.nvidia.com/gpugems/gpugems/part-ii-lighting-and-shadows/chapter-11-shadow-map-antialiasing
// sample only 4 positions with varying offset, depending on screen position
sampleBuilder.append("vec2 ${name}_offset = vec2(float(fract(gl_FragCoord.x * 0.5) > 0.25), float(fract(gl_FragCoord.y * 0.5) > 0.25));")
val samplePattern = listOf(Vec2f(-1.5f, 0.5f), Vec2f(0.5f, 0.5f), Vec2f(-1.5f, -1.5f), Vec2f(0.5f, -1.5f))
samplePattern.forEach { off ->
val projCoord = "vec4(${name}_pos.xy + (${name}_offset + vec2(${off.x}, ${off.y})) * ${name}_scale * ${name}_pos.w, ${name}_pos.z, ${name}_pos.w)"
sampleBuilder.append("${outShadowFac.name} += ${generator.sampleTexture2dDepth(depthTex.name, projCoord)};\n")
nSamples++
}
} else {
// regular 16 sample smooth shadow map sampling
val samplePattern = mutableListOf<Vec2f>()
for (y in 0..3) {
for (x in 0..3) {
samplePattern += Vec2f(-1.5f + x, -1.5f + y)
}
}
samplePattern.forEach { off ->
val projCoord = "vec4(${name}_pos.xy + (vec2(${off.x}, ${off.y})) * ${name}_scale * ${name}_pos.w, ${name}_pos.z, ${name}_pos.w)"
sampleBuilder.append("${outShadowFac.name} += ${generator.sampleTexture2dDepth(depthTex.name, projCoord)};\n")
nSamples++
}
}
generator.appendMain("""
vec4 ${name}_pos = ${inPosLightSpace.ref4f()};
// check shadow map bounds
${outShadowFac.declare()} = 1.0;
vec3 ${name}_posW = ${name}_pos.xyz / ${name}_pos.w;
if (${name}_posW.x > 0.0 && ${name}_posW.x < 1.0
&& ${name}_posW.y > 0.0 && ${name}_posW.y < 1.0
&& ${name}_posW.z > -1.0 && ${name}_posW.z < 1.0) {
if (${inNrmZLightSpace.ref1f()} > 0.05) {
${outShadowFac.name} = 0.0;
} else {
float ${name}_size = float(textureSize(${depthTex.name}, 0).x);
float ${name}_scale = 1.0 / float(${name}_size);
${name}_pos.z += ${inDepthOffset.ref1f()};
${outShadowFac.name} = 0.0;
$sampleBuilder
${outShadowFac.name} *= ${1f / nSamples};
if (${inNrmZLightSpace.ref1f()} > 0.0) {
${outShadowFac.name} *= 1.0 - smoothstep(0.0, 0.05, ${inNrmZLightSpace.ref1f()});
}
}
}
""")
}
}
class CascadedShadowMapNode(val shadowMap: CascadedShadowMap, val vertexGraph: ShaderGraph, val fragmentGraph: ShaderGraph) : ShadowMapNode() {
var inViewPosition: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO))
var inWorldPos: ShaderNodeIoVar
get() = vertexNode.inWorldPos
set(value) { vertexNode.inWorldPos = value }
var inWorldNrm: ShaderNodeIoVar
get() = vertexNode.inWorldNrm
set(value) { vertexNode.inWorldNrm = value }
override var depthMap: Texture2dNode?
get() = fragmentNode.depthMap
set(value) { fragmentNode.depthMap = value }
override val outShadowFac: ShaderNodeIoVar
get() = fragmentNode.outShadowFac
val vertexNode = CascadedShadowMapTransformNode(shadowMap, vertexGraph)
val fragmentNode = CascadedShadowMapFragmentNode(shadowMap, fragmentGraph)
private val helperNd = CascadedShadowHelperNd(vertexGraph)
private val posLightSpace = ShaderNodeIoVar(ModelVar4f("ifPosLightSpace_${vertexGraph.nextNodeId}[${shadowMap.numCascades}]"))
private val nrmZLightSpace = ShaderNodeIoVar(ModelVar1f("ifNrmZLightSpace_${vertexGraph.nextNodeId}[${shadowMap.numCascades}]"))
private val ifViewZ = ShaderNodeIoVar(ModelVar1f("outViewZ_${helperNd.nodeId}"))
init {
this.lightIndex = shadowMap.lightIndex
vertexGraph.addNode(helperNd)
fragmentNode.inPosLightSpace = posLightSpace
fragmentNode.inNrmZLightSpace = nrmZLightSpace
fragmentNode.inViewZ = ifViewZ
}
private inner class CascadedShadowHelperNd(graph: ShaderGraph) : ShaderNode("cascadedShadowHelper_${graph.nextNodeId}", graph) {
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inViewPosition, vertexNode.outPosLightSpace)
fragmentGraph.inputs += vertexGraph.addStageOutput(posLightSpace.variable, false, shadowMap.numCascades)
fragmentGraph.inputs += vertexGraph.addStageOutput(nrmZLightSpace.variable, false, shadowMap.numCascades)
fragmentGraph.inputs += vertexGraph.addStageOutput(ifViewZ.variable, false)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("${ifViewZ.name} = $inViewPosition.z;")
for (i in 0 until shadowMap.numCascades) {
generator.appendMain("${posLightSpace.name.substringBefore('[')}[$i] = ${vertexNode.outPosLightSpace.name.substringBefore('[')}[$i];")
generator.appendMain("${nrmZLightSpace.name.substringBefore('[')}[$i] = ${vertexNode.outNrmZLightSpace.name.substringBefore('[')}[$i];")
}
}
}
}
class CascadedShadowMapTransformNode(val shadowMap: CascadedShadowMap, graph: ShaderGraph) : ShaderNode("lightSpaceTf_${graph.nextNodeId}", graph) {
val uShadowMapVP = UniformMat4fv("${name}_shadowMapVPs", shadowMap.numCascades)
var inWorldPos: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO))
var inWorldNrm: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO))
val outPosLightSpace = ShaderNodeIoVar(ModelVar4f("${name}_posLightSpace[${shadowMap.numCascades}]"), this)
val outNrmZLightSpace = ShaderNodeIoVar(ModelVar1f("${name}_nrmZLightSpace[${shadowMap.numCascades}]"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inWorldPos)
shaderGraph.descriptorSet.apply {
uniformBuffer(name, shaderGraph.stage) {
+{ uShadowMapVP }
onUpdate = { _, _ ->
for (i in 0 until shadowMap.numCascades) {
uShadowMapVP.value[i].set(shadowMap.cascades[i].lightViewProjMat)
}
}
}
}
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("""
${outPosLightSpace.declare()};
${outNrmZLightSpace.declare()};
vec3 ${name}_nrmLightSpace;
""")
for (i in 0 until shadowMap.numCascades) {
generator.appendMain("""
${outPosLightSpace.name.substringBefore('[')}[$i] = ${uShadowMapVP.name}[$i] * vec4(${inWorldPos.ref3f()}, 1.0);
${name}_nrmLightSpace = normalize((${uShadowMapVP.name}[$i] * vec4(${inWorldNrm.ref3f()}, 0.0)).xyz);
${outNrmZLightSpace.name.substringBefore('[')}[$i] = ${name}_nrmLightSpace.z;
""")
}
}
}
class CascadedShadowMapFragmentNode(val shadowMap: CascadedShadowMap, graph: ShaderGraph) : ShaderNode("cascadedShadowMap_${graph.nextNodeId}", graph, ShaderStage.FRAGMENT_SHADER.mask) {
var depthMap: Texture2dNode? = null
var inPosLightSpace: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO))
var inNrmZLightSpace: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar1fConst(0f))
var inViewZ: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar1fConst(0f))
val outShadowFac = ShaderNodeIoVar(ModelVar1f("${name}_shadowFac"), this)
var useDithering = false
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(depthMap ?: throw KoolException("Depth map input not set"))
dependsOn(inPosLightSpace, inNrmZLightSpace, inViewZ)
}
override fun generateCode(generator: CodeGenerator) {
val depthTex = depthMap ?: throw KoolException("Depth map input not set")
val sampleBuilder = StringBuilder()
var nSamples = 0
if (useDithering) {
// dithered pcf shadow map sampling
// https://developer.nvidia.com/gpugems/gpugems/part-ii-lighting-and-shadows/chapter-11-shadow-map-antialiasing
// sample only 4 positions with varying offset, depending on screen position
sampleBuilder.append("vec2 offset = vec2(float(fract(gl_FragCoord.x * 0.5) > 0.25), float(fract(gl_FragCoord.y * 0.5) > 0.25));")
val samplePattern = listOf(Vec2f(-1.5f, 0.5f), Vec2f(0.5f, 0.5f), Vec2f(-1.5f, -1.5f), Vec2f(0.5f, -1.5f))
samplePattern.forEach { off ->
val projCoord = "vec4(projPos.xy + (offset + vec2(${off.x}, ${off.y})) * texScale * projPos.w, projPos.z, projPos.w)"
sampleBuilder.append("shadowFac += ${generator.sampleTexture2dDepth("shadowTex", projCoord)};\n")
nSamples++
}
} else {
// regular 16 sample smooth shadow map sampling
val samplePattern = mutableListOf<Vec2f>()
for (y in 0..3) {
for (x in 0..3) {
samplePattern += Vec2f(-1.5f + x, -1.5f + y)
}
}
samplePattern.forEach { off ->
val projCoord = "vec4(projPos.xy + (vec2(${off.x}, ${off.y})) * texScale * projPos.w, projPos.z, projPos.w)"
sampleBuilder.append("shadowFac += ${generator.sampleTexture2dDepth("shadowTex", projCoord)};\n")
nSamples++
}
}
generator.appendFunction("cascadedShadowFac", """
float cascadedShadowFac(sampler2DShadow shadowTex, vec4 projPos, float depthOffset) {
float texSize = float(textureSize(shadowTex, 0).x);
float texScale = 1.0 / float(texSize);
projPos.z += depthOffset;
float shadowFac = 0.0;
if (projPos.z >= 1.0) {
shadowFac = 1.0;
} else {
$sampleBuilder
shadowFac *= ${1f / nSamples};
}
return shadowFac;
}
""")
generator.appendMain("""
${outShadowFac.declare()} = 1.0;
bool ${name}_hasSampled = false;
""")
for (i in 0 until shadowMap.numCascades) {
generator.appendMain("""
if (!${name}_hasSampled) {
vec3 ${name}_samplePos = ${inPosLightSpace.name.substringBefore('[')}[$i].xyz / ${inPosLightSpace.name.substringBefore('[')}[$i].w;
if (${name}_samplePos.x > 0.0 && ${name}_samplePos.x < 1.0
&& ${name}_samplePos.y > 0.0 && ${name}_samplePos.y < 1.0
&& ${name}_samplePos.z > -1.0 && ${name}_samplePos.z < 1.0) {
if (${inNrmZLightSpace.name.substringBefore('[')}[$i] > 0.05) {
${outShadowFac.name} = 0.0;
} else {
${outShadowFac.name} = cascadedShadowFac(${depthTex.name}[$i], ${inPosLightSpace.name.substringBefore('[')}[$i], float(${shadowMap.cascades[i].shaderDepthOffset}));
if (${inNrmZLightSpace.name.substringBefore('[')}[$i] > 0.0) {
${outShadowFac.name} *= 1.0 - smoothstep(0.0, 0.05, ${inNrmZLightSpace.name.substringBefore('[')}[$i]);
}
}
${name}_hasSampled = true;
}
}
""")
}
}
}
| apache-2.0 | 5824e783f10f93a97b9c914ed144d3c4 | 45.552113 | 192 | 0.616241 | 3.97642 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/utils/extensions/JSONObjectExt.kt | 1 | 2281 | package info.nightscout.androidaps.utils.extensions
import androidx.annotation.StringRes
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONObject
fun JSONObject.putInt(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject =
if (sp.contains(key)) put(resourceHelper.gs(key), sp.getInt(key, 0)) else this
fun JSONObject.putLong(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject =
if (sp.contains(key)) put(resourceHelper.gs(key), sp.getLong(key, 0)) else this
fun JSONObject.putDouble(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject =
if (sp.contains(key)) put(resourceHelper.gs(key), sp.getDouble(key, 0.0)) else this
fun JSONObject.putString(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject =
if (sp.contains(key)) put(resourceHelper.gs(key), sp.getString(key, "")) else this
fun JSONObject.putBoolean(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject =
if (sp.contains(key)) put(resourceHelper.gs(key), sp.getBoolean(key, false)) else this
fun JSONObject.storeInt(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject {
if (has(resourceHelper.gs(key))) sp.putString(key, getInt(resourceHelper.gs(key)).toString())
return this
}
fun JSONObject.storeLong(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject {
if (has(resourceHelper.gs(key))) sp.putString(key, getLong(resourceHelper.gs(key)).toString())
return this
}
fun JSONObject.storeDouble(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject {
if (has(resourceHelper.gs(key))) sp.putString(key, getDouble(resourceHelper.gs(key)).toString())
return this
}
fun JSONObject.storeString(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject {
if (has(resourceHelper.gs(key))) sp.putString(key, getString(resourceHelper.gs(key)).toString())
return this
}
fun JSONObject.storeBoolean(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject {
if (has(resourceHelper.gs(key))) sp.putString(key, getBoolean(resourceHelper.gs(key)).toString())
return this
}
| agpl-3.0 | 5b01a44970da3880d4c4182b5994f643 | 46.520833 | 102 | 0.754932 | 3.980803 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineNamedFunctionHandler.kt | 1 | 2825 | // 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.idea.refactoring.inline
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.refactoring.RefactoringBundle
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.util.isAnonymousFunction
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
class KotlinInlineNamedFunctionHandler : AbstractKotlinInlineFunctionHandler<KtNamedFunction>() {
override fun canInlineKotlinFunction(function: KtFunction): Boolean = function is KtNamedFunction && !function.isAnonymousFunction
override fun inlineKotlinFunction(project: Project, editor: Editor?, function: KtNamedFunction) {
val nameReference = editor?.findSimpleNameReference()
val recursive = function.isRecursive()
if (recursive && nameReference == null) {
val message = RefactoringBundle.getCannotRefactorMessage(
KotlinBundle.message("text.inline.recursive.function.is.supported.only.on.references")
)
return showErrorHint(project, editor, message)
}
val dialog = KotlinInlineNamedFunctionDialog(
function,
nameReference,
allowToInlineThisOnly = recursive,
editor = editor,
)
if (!ApplicationManager.getApplication().isUnitTestMode) {
dialog.show()
} else {
try {
dialog.doAction()
} finally {
dialog.close(DialogWrapper.OK_EXIT_CODE, true)
}
}
}
private fun KtNamedFunction.isRecursive(): Boolean {
val context = analyzeWithContent()
return bodyExpression?.includesCallOf(context[BindingContext.FUNCTION, this] ?: return false, context) ?: false
}
private fun KtExpression.includesCallOf(descriptor: FunctionDescriptor, context: BindingContext): Boolean {
val refDescriptor = getResolvedCall(context)?.resultingDescriptor
return descriptor == refDescriptor || anyDescendantOfType<KtExpression> {
it !== this && descriptor == it.getResolvedCall(context)?.resultingDescriptor
}
}
}
| apache-2.0 | b28220d4efc2ef6f26fce369810499ce | 43.140625 | 158 | 0.72885 | 5.183486 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/CastExpressionFix.kt | 1 | 3450 | // 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.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.asFlexibleType
import org.jetbrains.kotlin.types.isDefinitelyNotNullType
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.makeNullable
class CastExpressionFix(element: KtExpression, type: KotlinType) : KotlinQuickFixAction<KtExpression>(element) {
private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type)
private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type).let {
if (type.isDefinitelyNotNullType) "($it)" else it
}
private val upOrDownCast: Boolean = run {
val expressionType = element.analyze(BodyResolveMode.PARTIAL).getType(element)
expressionType != null && (type.isSubtypeOf(expressionType) || expressionType.isSubtypeOf(type))
&& expressionType != type.makeNullable() //covered by AddExclExclCallFix
}
override fun getFamilyName() = KotlinBundle.message("fix.cast.expression.family")
override fun getText() = element?.let { KotlinBundle.message("fix.cast.expression.text", it.text, typePresentation) } ?: ""
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = upOrDownCast
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val expressionToInsert = KtPsiFactory(file).createExpressionByPattern("$0 as $1", element, typeSourceCode)
val newExpression = element.replaced(expressionToInsert)
ShortenReferences.DEFAULT.process((KtPsiUtil.safeDeparenthesize(newExpression) as KtBinaryExpressionWithTypeRHS).right!!)
editor?.caretModel?.moveToOffset(newExpression.endOffset)
}
abstract class Factory : KotlinSingleIntentionActionFactoryWithDelegate<KtExpression, KotlinType>() {
override fun getElementOfInterest(diagnostic: Diagnostic) = diagnostic.psiElement as? KtExpression
override fun createFix(originalElement: KtExpression, data: KotlinType) = CastExpressionFix(originalElement, data)
}
object SmartCastImpossibleFactory : Factory() {
override fun extractFixData(element: KtExpression, diagnostic: Diagnostic) = Errors.SMARTCAST_IMPOSSIBLE.cast(diagnostic).a
}
object GenericVarianceConversion : Factory() {
override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): KotlinType? {
return ErrorsJvm.JAVA_TYPE_MISMATCH.cast(diagnostic).b.asFlexibleType().upperBound
}
}
}
| apache-2.0 | a4da9de63c1d93cd33fe388550ee4b6f | 53.761905 | 158 | 0.777971 | 4.805014 | false | false | false | false |
jwren/intellij-community | python/src/com/jetbrains/python/sdk/add/target/PyAddVirtualEnvPanel.kt | 1 | 13684 | // 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 com.jetbrains.python.sdk.add.target
import com.intellij.execution.ExecutionException
import com.intellij.execution.target.TargetEnvironmentConfiguration
import com.intellij.execution.target.joinTargetPaths
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.dsl.builder.bind
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.builder.selected
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.layout.*
import com.intellij.util.PathUtil
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PySdkBundle
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.packaging.PyPackageManagers
import com.jetbrains.python.run.PythonInterpreterTargetEnvironmentFactory
import com.jetbrains.python.run.PythonInterpreterTargetEnvironmentFactory.Companion.projectSyncRows
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.add.ExistingPySdkComboBoxItem
import com.jetbrains.python.sdk.add.PySdkPathChoosingComboBox
import com.jetbrains.python.sdk.add.addBaseInterpretersAsync
import com.jetbrains.python.sdk.add.addInterpretersAsync
import com.jetbrains.python.target.PyTargetAwareAdditionalData
import com.jetbrains.python.target.PythonLanguageRuntimeConfiguration
import icons.PythonIcons
import java.awt.BorderLayout
import java.util.function.Supplier
/**
* Panel with a control that allows to add either new or selecting existing virtualenv.
*/
class PyAddVirtualEnvPanel constructor(project: Project?,
module: Module?,
private val existingSdks: List<Sdk> = emptyList(),
allowAddNewVirtualenv: Boolean = false,
private val context: UserDataHolder,
targetSupplier: Supplier<TargetEnvironmentConfiguration>?,
config: PythonLanguageRuntimeConfiguration)
: PyAddSdkPanelBase(project, module, targetSupplier) {
override val panelName = PyBundle.message("python.add.sdk.panel.name.virtualenv.environment")
override val icon = PythonIcons.Python.Virtualenv
private val interpreterCombobox: PySdkPathChoosingComboBox
private val locationField: TextFieldWithBrowseButton
private val baseInterpreterCombobox: PySdkPathChoosingComboBox
private var isCreateNewVirtualenv: Boolean = false
private var isInheritSitePackages: Boolean = false
/**
* Encapsulates the work with the files synchronization options.
*/
private var projectSync: ProjectSync? = null
private val contentPanel: DialogPanel
private lateinit var newEnvironmentModeSelected: ComponentPredicate
override var newProjectPath: String? = null
set(value) {
field = value
if (isUnderLocalTarget) {
locationField.text = FileUtil.toSystemDependentName(PySdkSettings.instance.getPreferredVirtualEnvBasePath(projectBasePath))
}
}
init {
layout = BorderLayout()
interpreterCombobox = PySdkPathChoosingComboBox(targetEnvironmentConfiguration = targetEnvironmentConfiguration)
locationField = TextFieldWithBrowseButton().apply {
val targetEnvironmentConfiguration = targetEnvironmentConfiguration
if (targetEnvironmentConfiguration == null) {
text = FileUtil.toSystemDependentName(PySdkSettings.instance.getPreferredVirtualEnvBasePath(projectBasePath))
}
else {
val projectBasePath = projectBasePath
text = when {
projectBasePath.isNullOrEmpty() -> config.userHome
// TODO [run.targets] ideally we want to use '/' or '\' file separators based on the target's OS (which is not available yet)
else -> joinTargetPaths(config.userHome, DEFAULT_VIRTUALENVS_DIR, PathUtil.getFileName(projectBasePath), fileSeparator = '/')
}
}
addBrowseFolderListener(PySdkBundle.message("python.venv.location.chooser"), project, targetEnvironmentConfiguration,
FileChooserDescriptorFactory.createSingleFolderDescriptor())
}
baseInterpreterCombobox = PySdkPathChoosingComboBox(targetEnvironmentConfiguration = targetEnvironmentConfiguration)
contentPanel = panel {
if (allowAddNewVirtualenv && isMutableTarget) {
isCreateNewVirtualenv = true
buttonsGroup {
row {
label(PyBundle.message("sdk.create.venv.environment.label"))
radioButton(PyBundle.message("sdk.create.venv.existing.option.label"), false)
radioButton(PyBundle.message("sdk.create.venv.new.option.label"), true).apply {
newEnvironmentModeSelected = selected
}
}
}.bind(getter = { isCreateNewVirtualenv }, setter = { isCreateNewVirtualenv = it })
}
else {
newEnvironmentModeSelected = ConstantComponentPredicate.FALSE
}
row(PyBundle.message("sdk.create.venv.dialog.interpreter.label")) {
cell(interpreterCombobox).horizontalAlign(HorizontalAlign.FILL)
}.visibleIf(newEnvironmentModeSelected.not())
row(PyBundle.message("sdk.create.venv.dialog.location.label")) {
cell(locationField).horizontalAlign(HorizontalAlign.FILL)
}.visibleIf(newEnvironmentModeSelected)
row(PyBundle.message("sdk.create.venv.dialog.base.interpreter.label")) {
cell(baseInterpreterCombobox).horizontalAlign(HorizontalAlign.FILL)
}.visibleIf(newEnvironmentModeSelected)
row {
checkBox(PyBundle.message("sdk.create.venv.dialog.label.inherit.global.site.packages"))
.bindSelected(::isInheritSitePackages)
}.visibleIf(newEnvironmentModeSelected)
projectSync = projectSyncRows(project, targetEnvironmentConfiguration)
}
add(contentPanel, BorderLayout.NORTH)
if (targetEnvironmentConfiguration.isLocal()) {
// asynchronously fill the combobox
addInterpretersAsync(
interpreterCombobox,
sdkObtainer = {
detectVirtualEnvs(module, existingSdks, context)
.filterNot { it.isAssociatedWithAnotherModule(module) }
},
onAdded = { sdks ->
val associatedVirtualEnv = sdks.find { it.isAssociatedWithModule(module) }
associatedVirtualEnv?.let { interpreterCombobox.selectedSdk = associatedVirtualEnv }
}
)
addBaseInterpretersAsync(baseInterpreterCombobox, existingSdks, module, context)
}
else {
config.pythonInterpreterPath.let { introspectedPythonPath ->
if (introspectedPythonPath.isNotBlank()) {
baseInterpreterCombobox.addSdkItem(createDetectedSdk(introspectedPythonPath, isLocal = false))
}
}
}
}
override fun validateAll(): List<ValidationInfo> =
if (isUnderLocalTarget) {
when (newEnvironmentModeSelected()) {
true -> listOfNotNull(validateEnvironmentDirectoryLocation(locationField),
validateSdkComboBox(baseInterpreterCombobox, this))
false -> listOfNotNull(validateSdkComboBox(interpreterCombobox, this))
}
}
else emptyList()
override fun getOrCreateSdk(): Sdk? = getOrCreateSdk(targetEnvironmentConfiguration = null)
override fun getOrCreateSdk(targetEnvironmentConfiguration: TargetEnvironmentConfiguration?): Sdk? {
// applies components' states for bound properties (e.g. selected radio button to `isCreateNewVirtualenv` field)
contentPanel.apply()
// TODO [targets] Refactor this workaround
applyOptionalProjectSyncConfiguration(targetEnvironmentConfiguration)
if (isCreateNewVirtualenv) return createNewVirtualenvSdk(targetEnvironmentConfiguration)
val item = interpreterCombobox.selectedItem
// there should *not* be other items other than `ExistingPySdkComboBoxItem`
return if (item is ExistingPySdkComboBoxItem) configureExistingVirtualenvSdk(targetEnvironmentConfiguration, item.sdk) else null
}
/**
* Note: there is a careful work with SDK names because of the caching of Python package managers in
* [com.jetbrains.python.packaging.PyPackageManagersImpl.forSdk].
*/
private fun createNewVirtualenvSdk(targetEnvironmentConfiguration: TargetEnvironmentConfiguration?): Sdk? {
// TODO [targets] Do *not* silently `return null`
val baseSelectedSdk = baseInterpreterCombobox.selectedSdk ?: return null
val root = locationField.text
// TODO [targets] Use `targetEnvironmentConfiguration` to create `baseSdk`
val baseSdk: Sdk = if (targetEnvironmentConfiguration == null) {
installSdkIfNeeded(baseSelectedSdk, module, existingSdks, context) ?: return null
}
else {
val sdkAdditionalData = PyTargetAwareAdditionalData(virtualEnvSdkFlavor)
sdkAdditionalData.targetEnvironmentConfiguration = targetEnvironmentConfiguration
val homePath = baseSelectedSdk.homePath ?: return null
// suggesting the proper name for the base SDK fixes the problem with clashing caching key of Python package manager
val customSdkSuggestedName = PythonInterpreterTargetEnvironmentFactory.findDefaultSdkName(project, sdkAdditionalData, version = null)
sdkAdditionalData.interpreterPath = homePath
SdkConfigurationUtil.createSdk(existingSdks, homePath, PythonSdkType.getInstance(), sdkAdditionalData, customSdkSuggestedName)
}
val task = object : Task.WithResult<String, ExecutionException>(project, PySdkBundle.message("python.creating.venv.title"), false) {
override fun compute(indicator: ProgressIndicator): String {
indicator.isIndeterminate = true
try {
val packageManager = PyPackageManager.getInstance(baseSdk)
return packageManager.createVirtualEnv(root, isInheritSitePackages)
}
finally {
// this fixes the issue with unsuccessful attempts to create the new SDK after removing the underlying Web Deployment
PyPackageManagers.getInstance().clearCache(baseSdk)
}
}
}
// TODO [targets] Restore `makeSharedField` flag
val shared = false
val associatedPath = if (!shared) projectBasePath else null
val sdk = targetEnvironmentConfiguration.let {
if (it == null) {
// `targetEnvironmentConfiguration.isLocal() == true`
createSdkByGenerateTask(task, existingSdks, baseSdk, associatedPath, null) ?: return null
}
else {
// TODO [targets] Utilize smth like `createSdkFromExistingServerConfiguration` method in `SshSdkCreationUtil.kt`
val homePath = ProgressManager.getInstance().run(task)
createSdkForTarget(project, it, homePath, existingSdks)
}
}
if (!shared) {
sdk.associateWithModule(module, newProjectPath)
}
project.excludeInnerVirtualEnv(sdk)
if (isUnderLocalTarget) {
// The method `onVirtualEnvCreated(..)` stores preferred base path to virtual envs. Storing here the base path from the non-local
// target (e.g. a path from SSH machine or a Docker image) ends up with a meaningless default for the local machine.
// If we would like to store preferred paths for non-local targets we need to use some key to identify the exact target.
PySdkSettings.instance.onVirtualEnvCreated(baseSdk, FileUtil.toSystemIndependentName(root), projectBasePath)
}
return sdk
}
private fun configureExistingVirtualenvSdk(targetEnvironmentConfiguration: TargetEnvironmentConfiguration?, selectedSdk: Sdk): Sdk? {
if (targetEnvironmentConfiguration == null) {
return when (selectedSdk) {
is PyDetectedSdk -> selectedSdk.setupAssociated(existingSdks, newProjectPath ?: project?.basePath)?.apply {
// TODO [targets] Restore `makeSharedField` flag
associateWithModule(module, newProjectPath)
}
else -> selectedSdk
}
}
else {
// TODO get rid of `!!`
val homePath = selectedSdk.homePath!!
return createSdkForTarget(project, targetEnvironmentConfiguration, homePath, existingSdks)
}
}
private fun applyOptionalProjectSyncConfiguration(targetConfiguration: TargetEnvironmentConfiguration?) {
if (targetConfiguration != null) projectSync?.apply(targetConfiguration)
}
private class ConstantComponentPredicate(private val value: Boolean) : ComponentPredicate() {
override fun addListener(listener: (Boolean) -> Unit) = Unit
override fun invoke(): Boolean = value
companion object {
val FALSE = ConstantComponentPredicate(value = false)
}
}
companion object {
/**
* We assume this is the default name of the directory that is located in user home and which contains user virtualenv Python
* environments.
*
* @see com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor.getDefaultLocation
*/
private const val DEFAULT_VIRTUALENVS_DIR = ".virtualenvs"
}
} | apache-2.0 | 7680f19dd53c8250f3b495e30b58189f | 45.233108 | 158 | 0.7386 | 5.408696 | false | true | false | false |
androidx/androidx | tv/tv-material/src/main/java/androidx/tv/material/carousel/Carousel.kt | 3 | 13898 | /*
* Copyright 2022 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.tv.material.carousel
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.with
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.FocusState
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.tv.material.ExperimentalTvMaterialApi
import java.lang.Math.floorMod
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.yield
/**
* Composes a hero card rotator to highlight a piece of content.
*
* @param slideCount total number of slides present in the carousel.
* @param carouselState state associated with this carousel.
* @param timeToDisplaySlideMillis duration for which slide should be visible before moving to
* the next slide.
* @param enterTransition transition used to bring a slide into view.
* @param exitTransition transition used to remove a slide from view.
* @param carouselIndicator indicator showing the position of the current slide among all slides.
* @param content defines the slides for a given index.
*/
@Suppress("IllegalExperimentalApiUsage")
@OptIn(ExperimentalComposeUiApi::class, ExperimentalAnimationApi::class)
@ExperimentalTvMaterialApi
@Composable
fun Carousel(
slideCount: Int,
modifier: Modifier = Modifier,
carouselState: CarouselState = remember { CarouselState() },
timeToDisplaySlideMillis: Long = CarouselDefaults.TimeToDisplaySlideMillis,
enterTransition: EnterTransition = CarouselDefaults.EnterTransition,
exitTransition: ExitTransition = CarouselDefaults.ExitTransition,
carouselIndicator:
@Composable BoxScope.() -> Unit = {
CarouselDefaults.Indicator(
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp),
carouselState = carouselState,
slideCount = slideCount)
},
content: @Composable (index: Int) -> Unit
) {
CarouselStateUpdater(carouselState, slideCount)
var focusState: FocusState? by remember { mutableStateOf(null) }
val focusManager = LocalFocusManager.current
val isLtr = LocalLayoutDirection.current == LayoutDirection.Ltr
val carouselOuterBoxFocusRequester = remember { FocusRequester() }
var isAutoScrollActive by remember { mutableStateOf(false) }
AutoScrollSideEffect(
timeToDisplaySlideMillis,
slideCount,
carouselState,
focusState,
onAutoScrollChange = { isAutoScrollActive = it })
Box(modifier = modifier
.focusRequester(carouselOuterBoxFocusRequester)
.onFocusChanged {
focusState = it
if (it.isFocused && isAutoScrollActive) {
focusManager.moveFocus(FocusDirection.Enter)
}
}
.manualScrolling(carouselState, slideCount, isLtr)
.focusable()) {
AnimatedContent(
targetState = carouselState.slideIndex,
transitionSpec = { enterTransition.with(exitTransition) }
) {
LaunchedEffect(Unit) {
[email protected] {
if (isAutoScrollActive.not()) {
carouselOuterBoxFocusRequester.requestFocus()
focusManager.moveFocus(FocusDirection.Enter)
}
}
}
content.invoke(it)
}
this.carouselIndicator()
}
}
@Suppress("IllegalExperimentalApiUsage")
@OptIn(ExperimentalAnimationApi::class)
private suspend fun AnimatedVisibilityScope.onAnimationCompletion(action: suspend () -> Unit) {
snapshotFlow { transition.currentState == transition.targetState }.first { it }
action.invoke()
}
@OptIn(ExperimentalTvMaterialApi::class)
@Composable
private fun AutoScrollSideEffect(
timeToDisplaySlideMillis: Long,
slideCount: Int,
carouselState: CarouselState,
focusState: FocusState?,
onAutoScrollChange: (isAutoScrollActive: Boolean) -> Unit = {},
) {
val currentTimeToDisplaySlideMillis by rememberUpdatedState(timeToDisplaySlideMillis)
val currentSlideCount by rememberUpdatedState(slideCount)
val carouselIsFocused = focusState?.isFocused ?: false
val carouselHasFocus = focusState?.hasFocus ?: false
val doAutoScroll = (carouselIsFocused || carouselHasFocus).not()
if (doAutoScroll) {
LaunchedEffect(carouselState) {
while (true) {
yield()
delay(currentTimeToDisplaySlideMillis)
if (carouselState.activePauseHandlesCount > 0) {
snapshotFlow { carouselState.activePauseHandlesCount }
.first { pauseHandleCount -> pauseHandleCount == 0 }
}
carouselState.moveToNextSlide(currentSlideCount)
}
}
}
onAutoScrollChange(doAutoScroll)
}
@Suppress("IllegalExperimentalApiUsage")
@OptIn(ExperimentalTvMaterialApi::class, ExperimentalComposeUiApi::class)
private fun Modifier.manualScrolling(
carouselState: CarouselState,
slideCount: Int,
isLtr: Boolean
): Modifier =
this.focusProperties {
exit = {
val showPreviousSlideAndGetFocusRequester = {
if (carouselState.isFirstSlide().not()) {
carouselState.moveToPreviousSlide(slideCount)
FocusRequester.Cancel
} else {
FocusRequester.Default
}
}
val showNextSlideAndGetFocusRequester = {
if (carouselState.isLastSlide(slideCount).not()) {
carouselState.moveToNextSlide(slideCount)
FocusRequester.Cancel
} else {
FocusRequester.Default
}
}
when (it) {
FocusDirection.Left -> {
if (isLtr) {
showPreviousSlideAndGetFocusRequester()
} else {
showNextSlideAndGetFocusRequester()
}
}
FocusDirection.Right -> {
if (isLtr) {
showNextSlideAndGetFocusRequester()
} else {
showPreviousSlideAndGetFocusRequester()
}
}
else -> FocusRequester.Default
}
}
}
@OptIn(ExperimentalTvMaterialApi::class)
@Composable
private fun CarouselStateUpdater(carouselState: CarouselState, slideCount: Int) {
LaunchedEffect(carouselState, slideCount) {
if (slideCount != 0) {
carouselState.slideIndex = floorMod(carouselState.slideIndex, slideCount)
}
}
}
/**
* State of the Carousel which allows the user to specify the first slide that is shown when the
* Carousel is instantiated in the constructor.
*
* It also provides the user with support to pause and resume the auto-scroll behaviour of the
* Carousel.
* @param initialSlideIndex the index of the first slide that is displayed.
*/
@Stable
@ExperimentalTvMaterialApi
class CarouselState(initialSlideIndex: Int = 0) {
internal var activePauseHandlesCount by mutableStateOf(0)
/**
* The index of the slide that is currently displayed by the carousel
*/
var slideIndex by mutableStateOf(initialSlideIndex)
internal set
/**
* Pauses the auto-scrolling behaviour of Carousel.
* The pause request is ignored if [slideIndex] is not the current slide that is visible.
* Returns a [ScrollPauseHandle] that can be used to resume
*/
fun pauseAutoScroll(slideIndex: Int): ScrollPauseHandle {
if (this.slideIndex != slideIndex) {
return NoOpScrollPauseHandle
}
return ScrollPauseHandleImpl(this)
}
internal fun isFirstSlide() = slideIndex == 0
internal fun isLastSlide(slideCount: Int) = slideIndex == slideCount - 1
internal fun moveToPreviousSlide(slideCount: Int) {
// No slides available for carousel
if (slideCount == 0) return
// Go to previous slide
slideIndex = floorMod(slideIndex - 1, slideCount)
}
internal fun moveToNextSlide(slideCount: Int) {
// No slides available for carousel
if (slideCount == 0) return
// Go to next slide
slideIndex = floorMod(slideIndex + 1, slideCount)
}
}
@ExperimentalTvMaterialApi
/**
* Handle returned by [CarouselState.pauseAutoScroll] that can be used to resume auto-scroll.
*/
sealed interface ScrollPauseHandle {
/**
* Resumes the auto-scroll behaviour if there are no other active [ScrollPauseHandle]s.
*/
fun resumeAutoScroll()
}
@OptIn(ExperimentalTvMaterialApi::class)
internal object NoOpScrollPauseHandle : ScrollPauseHandle {
/**
* Resumes the auto-scroll behaviour if there are no other active [ScrollPauseHandle]s.
*/
override fun resumeAutoScroll() {}
}
@OptIn(ExperimentalTvMaterialApi::class)
internal class ScrollPauseHandleImpl(private val carouselState: CarouselState) : ScrollPauseHandle {
private var active by mutableStateOf(true)
init {
carouselState.activePauseHandlesCount += 1
}
/**
* Resumes the auto-scroll behaviour if there are no other active [ScrollPauseHandle]s.
*/
override fun resumeAutoScroll() {
if (active) {
active = false
carouselState.activePauseHandlesCount -= 1
}
}
}
@ExperimentalTvMaterialApi
object CarouselDefaults {
/**
* Default time for which the slide is visible to the user.
*/
val TimeToDisplaySlideMillis: Long = 5000
/**
* Default transition used to bring the slide into view
*/
val EnterTransition: EnterTransition = fadeIn(animationSpec = tween(900))
/**
* Default transition used to remove the slide from view
*/
val ExitTransition: ExitTransition = fadeOut(animationSpec = tween(900))
/**
* An indicator showing the position of the current slide among the slides of the carousel.
*
* @param carouselState is the state associated with the carousel of which this indicator is a
* part.
* @param slideCount total number of slides in the carousel
*/
@ExperimentalTvMaterialApi
@Composable
fun Indicator(
carouselState: CarouselState,
slideCount: Int,
modifier: Modifier = Modifier
) {
if (slideCount <= 0) {
Box(modifier = modifier)
} else {
val defaultSize = remember { 8.dp }
val inactiveColor = remember { Color.LightGray }
val activeColor = remember { Color.White }
val shape = remember { CircleShape }
val indicatorModifier = remember { Modifier.size(defaultSize) }
Box(modifier = modifier) {
Row(
horizontalArrangement = Arrangement.spacedBy(defaultSize),
verticalAlignment = Alignment.CenterVertically,
) {
repeat(slideCount) {
Box(indicatorModifier.background(
color =
if (it == carouselState.slideIndex) {
activeColor
} else {
inactiveColor
},
shape = shape
))
}
}
}
}
}
}
| apache-2.0 | d89a666583d47b2b7348ee2e35b17dba | 35.098701 | 100 | 0.669593 | 4.993891 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceMapIndexedWithListGeneratorInspection.kt | 3 | 6660 | // 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.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.idea.inspections.collections.isCollection
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.hasUsages
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceMapIndexedWithListGeneratorInspection : AbstractKotlinInspection() {
private companion object {
private const val MAP_INDEXED_FUNCTION_NAME = "mapIndexed"
private val MAP_INDEXED_FQ_NAME = FqName("kotlin.collections.mapIndexed")
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(callExpression) {
val callee = callExpression.calleeExpression ?: return
if (callee.text != MAP_INDEXED_FUNCTION_NAME
&& (callee.mainReference?.resolve() as? KtNamedFunction)?.fqName != MAP_INDEXED_FQ_NAME
) return
val context = callExpression.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = callExpression.getResolvedCall(context) ?: return
if (!resolvedCall.isCalling(MAP_INDEXED_FQ_NAME)) return
val receiver = callExpression.getQualifiedExpressionForSelector()?.receiverExpression
val receiverType = receiver?.getResolvedCall(context)?.resultingDescriptor?.returnType
?: resolvedCall.getImplicitReceiverValue()?.type ?: return
if (!receiverType.isCollection(DefaultBuiltIns.Instance)) return
val valueArgument = callExpression.valueArguments.singleOrNull() ?: callExpression.lambdaArguments.singleOrNull() ?: return
val valueParameters = when (val argumentExpression = valueArgument.getLambdaOrNamedFunction()) {
is KtLambdaExpression -> argumentExpression.valueParameters
is KtNamedFunction -> argumentExpression.valueParameters
else -> return
}
if (valueParameters.size != 2) return
val secondParameter = valueParameters[1]
val destructuringDeclaration = secondParameter.destructuringDeclaration
if (destructuringDeclaration != null) {
if (destructuringDeclaration.entries.any { entry -> entry.hasUsages(callExpression) }) return
} else if (secondParameter.hasUsages(callExpression)) {
return
}
holder.registerProblem(callee, KotlinBundle.message("should.be.replaced.with.list.generator"), ReplaceWithListGeneratorFix())
})
private class ReplaceWithListGeneratorFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.list.generator.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callExpression = descriptor.psiElement.getStrictParentOfType<KtCallExpression>() ?: return
val qualifiedExpression = callExpression.getQualifiedExpressionForSelector()
val receiverExpression = qualifiedExpression?.receiverExpression
val valueArgument = callExpression.valueArguments.singleOrNull() ?: callExpression.lambdaArguments.singleOrNull() ?: return
val psiFactory = KtPsiFactory(callExpression)
when (val argumentExpression = valueArgument.getLambdaOrNamedFunction()) {
is KtLambdaExpression -> {
val functionLiteral = argumentExpression.functionLiteral
functionLiteral.valueParameterList?.replace(
psiFactory.createLambdaParameterList(argumentExpression.valueParameters.first().text)
)
functionLiteral.collectDescendantsOfType<KtReturnExpression>().forEach {
val returnedExpression = it.returnedExpression ?: return@forEach
if (it.analyze()[BindingContext.LABEL_TARGET, it.getTargetLabel()] == functionLiteral) {
it.replace(psiFactory.createExpressionByPattern("return@List $0", returnedExpression))
}
}
if (receiverExpression != null) {
qualifiedExpression.replace(
psiFactory.createExpressionByPattern("List($0.size) $1", receiverExpression, argumentExpression.text)
)
} else {
callExpression.replace(psiFactory.createExpressionByPattern("List(size) ${argumentExpression.text}"))
}
}
is KtNamedFunction -> {
argumentExpression.valueParameterList?.replace(
psiFactory.createParameterList("(${argumentExpression.valueParameters.first().text})")
)
if (receiverExpression != null) {
qualifiedExpression.replace(
psiFactory.createExpressionByPattern("List($0.size, $1)", receiverExpression, argumentExpression.text)
)
} else {
callExpression.replace(psiFactory.createExpressionByPattern("List(size, ${argumentExpression.text})"))
}
}
else -> return
}
}
}
}
private fun KtValueArgument.getLambdaOrNamedFunction(): KtExpression? {
return when (val argumentExpression = getArgumentExpression()) {
is KtLambdaExpression, is KtNamedFunction -> argumentExpression
is KtLabeledExpression -> argumentExpression.baseExpression as? KtLambdaExpression
else -> null
}
} | apache-2.0 | 9cb9f762469e2226aa93779b22d5d415 | 57.429825 | 158 | 0.691742 | 6.104491 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/caches/resolve/CompositeResolverForModuleFactory.kt | 1 | 11872 | // 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.caches.resolve
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.containers.addIfNotNull
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.analyzer.common.CommonAnalysisParameters
import org.jetbrains.kotlin.analyzer.common.configureCommonSpecificComponents
import org.jetbrains.kotlin.builtins.jvm.JvmBuiltInsPackageFragmentProvider
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.container.*
import org.jetbrains.kotlin.context.ModuleContext
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
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.configureModule
import org.jetbrains.kotlin.frontend.di.configureStandardResolveComponents
import org.jetbrains.kotlin.frontend.java.di.configureJavaSpecificComponents
import org.jetbrains.kotlin.frontend.java.di.initializeJavaSpecificComponents
import org.jetbrains.kotlin.idea.base.projectStructure.IdeBuiltInsLoadingState
import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.CompositeAnalyzerServices
import org.jetbrains.kotlin.idea.compiler.IdeSealedClassInheritorsProvider
import org.jetbrains.kotlin.idea.project.IdeaEnvironment
import org.jetbrains.kotlin.incremental.components.InlineConstTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.java.lazy.ModuleClassResolver
import org.jetbrains.kotlin.load.java.lazy.ModuleClassResolverImpl
import org.jetbrains.kotlin.load.kotlin.PackagePartProvider
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinderFactory
import org.jetbrains.kotlin.platform.*
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.isJs
import org.jetbrains.kotlin.platform.jvm.JvmPlatform
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.platform.konan.NativePlatform
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver
import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters
import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService
import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragmentProvider
import org.jetbrains.kotlin.serialization.deserialization.MetadataPartProvider
import org.jetbrains.kotlin.storage.StorageManager
class CompositeResolverForModuleFactory(
private val commonAnalysisParameters: CommonAnalysisParameters,
private val jvmAnalysisParameters: JvmPlatformParameters,
private val targetPlatform: TargetPlatform,
private val compilerServices: CompositeAnalyzerServices
) : 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 metadataPartProvider = commonAnalysisParameters.metadataPartProviderFactory(moduleContent)
val trace = CodeAnalyzerInitializer.getInstance(project).createTrace()
val moduleClassResolver = ModuleClassResolverImpl { javaClass ->
val referencedClassModule = jvmAnalysisParameters.moduleByJavaClass(javaClass)
// We don't have full control over idea resolve api so we allow for a situation which should not happen in Kotlin.
// For example, type in a java library can reference a class declared in a source root (is valid but rare case)
// Providing a fallback strategy in this case can hide future problems, so we should at least log to be able to diagnose those
@Suppress("UNCHECKED_CAST")
val resolverForReferencedModule = referencedClassModule?.let { resolverForProject.tryGetResolverForModule(it as M) }
val resolverForModule = resolverForReferencedModule?.takeIf {
referencedClassModule.platform.has<JvmPlatform>()
} ?: run {
// in case referenced class lies outside of our resolver, resolve the class as if it is inside our module
// this leads to java class being resolved several times
resolverForProject.resolverForModule(moduleInfo)
}
resolverForModule.componentProvider.get<JavaDescriptorResolver>()
}
val packagePartProvider = jvmAnalysisParameters.packagePartProviderFactory(moduleContent)
val container = createContainerForCompositePlatform(
moduleContext, moduleContentScope, languageVersionSettings, targetPlatform,
compilerServices, trace, declarationProviderFactory, metadataPartProvider,
moduleClassResolver, packagePartProvider
)
val packageFragmentProviders = sequence {
yield(container.get<ResolveSession>().packageFragmentProvider)
yieldAll(getCommonProvidersIfAny(moduleInfo, moduleContext, moduleDescriptor, container)) // todo: module context
yieldAll(getJsProvidersIfAny(moduleInfo, moduleContext, moduleDescriptor, container))
yieldAll(getJvmProvidersIfAny(container))
yieldAll(getNativeProvidersIfAny(moduleInfo, container))
yieldAll(getExtensionsProvidersIfAny(moduleInfo, moduleContext, trace))
}.toList()
return ResolverForModule(
CompositePackageFragmentProvider(
packageFragmentProviders,
"CompositeProvider@CompositeResolver for $moduleDescriptor"
),
container
)
}
private fun getCommonProvidersIfAny(
moduleInfo: ModuleInfo,
moduleContext: ModuleContext,
moduleDescriptor: ModuleDescriptor,
container: StorageComponentContainer
): List<PackageFragmentProvider> {
if (!targetPlatform.isCommon()) return emptyList()
val metadataProvider = container.get<MetadataPackageFragmentProvider>()
val klibMetadataProvider = CommonPlatforms.defaultCommonPlatform.idePlatformKind.resolution.createKlibPackageFragmentProvider(
moduleInfo,
moduleContext.storageManager,
container.get<LanguageVersionSettings>(),
moduleDescriptor
)
return listOfNotNull(metadataProvider, klibMetadataProvider)
}
@OptIn(ExperimentalStdlibApi::class)
private fun getJvmProvidersIfAny(container: StorageComponentContainer): List<PackageFragmentProvider> =
buildList {
if (targetPlatform.has<JvmPlatform>()) add(container.get<JavaDescriptorResolver>().packageFragmentProvider)
// Use JVM built-ins only for completely-JVM modules
addIfNotNull(container.tryGetService(JvmBuiltInsPackageFragmentProvider::class.java))
}
private fun getNativeProvidersIfAny(moduleInfo: ModuleInfo, container: StorageComponentContainer): List<PackageFragmentProvider> {
if (!targetPlatform.has<NativePlatform>()) return emptyList()
return listOfNotNull(
NativePlatforms.unspecifiedNativePlatform.idePlatformKind.resolution.createKlibPackageFragmentProvider(
moduleInfo,
container.get<StorageManager>(),
container.get<LanguageVersionSettings>(),
container.get<ModuleDescriptor>()
)
)
}
private fun <M : ModuleInfo> getExtensionsProvidersIfAny(
moduleInfo: M,
moduleContext: ModuleContext,
trace: BindingTrace,
): Collection<PackageFragmentProvider> = PackageFragmentProviderExtension.getInstances(moduleContext.project)
.mapNotNull {
it.getPackageFragmentProvider(
moduleContext.project,
moduleContext.module,
moduleContext.storageManager,
trace,
moduleInfo,
LookupTracker.DO_NOTHING,
)
}
private fun getJsProvidersIfAny(
moduleInfo: ModuleInfo,
moduleContext: ModuleContext,
moduleDescriptor: ModuleDescriptorImpl,
container: StorageComponentContainer
): List<PackageFragmentProvider> {
if (moduleInfo !is LibraryModuleInfo || !moduleInfo.platform.isJs()) return emptyList()
return createPackageFragmentProvider(moduleInfo, container, moduleContext, moduleDescriptor)
}
private fun createContainerForCompositePlatform(
moduleContext: ModuleContext,
moduleContentScope: GlobalSearchScope,
languageVersionSettings: LanguageVersionSettings,
targetPlatform: TargetPlatform,
analyzerServices: CompositeAnalyzerServices,
trace: BindingTrace,
declarationProviderFactory: DeclarationProviderFactory,
metadataPartProvider: MetadataPartProvider,
// Guaranteed to be non-null for modules with JVM
moduleClassResolver: ModuleClassResolver?,
packagePartProvider: PackagePartProvider?
): StorageComponentContainer = composeContainer("CompositePlatform") {
// Shared by all PlatformConfigurators
configureDefaultCheckers()
// Specific for each PlatformConfigurator
for (configurator in analyzerServices.services.map { it.platformConfigurator as PlatformConfiguratorBase }) {
configurator.configureExtensionsAndCheckers(this)
}
// Called by all normal containers set-ups
configureModule(moduleContext, targetPlatform, analyzerServices, trace, languageVersionSettings, IdeSealedClassInheritorsProvider)
configureStandardResolveComponents()
useInstance(moduleContentScope)
useInstance(declarationProviderFactory)
useInstance(InlineConstTracker.DoNothing)
// Probably, should be in StandardResolveComponents, but
useInstance(VirtualFileFinderFactory.getInstance(moduleContext.project).create(moduleContentScope))
useInstance(packagePartProvider!!)
// JVM-specific
if (targetPlatform.has<JvmPlatform>()) {
configureJavaSpecificComponents(
moduleContext, moduleClassResolver!!,
languageVersionSettings,
configureJavaClassFinder = null,
javaClassTracker = null,
useBuiltInsProvider = IdeBuiltInsLoadingState.isFromDependenciesForJvm && targetPlatform.isJvm() // use JVM BuiltIns only for completely JVM modules
)
}
// Common-specific
if (targetPlatform.isCommon()) {
configureCommonSpecificComponents()
}
IdeaEnvironment.configure(this)
}.apply {
if (targetPlatform.has<JvmPlatform>()) {
initializeJavaSpecificComponents(trace)
}
}
}
| apache-2.0 | b9520e4f7fb602e8885b51ad1586cb91 | 47.457143 | 164 | 0.746294 | 5.880139 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinTasksPropertyUtils.kt | 2 | 4468 | // 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.idea.gradleTooling
import org.gradle.api.Task
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.internal.FactoryNamedDomainObjectContainer
import org.gradle.api.plugins.JavaPluginConvention
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.getSourceSetName
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinPluginWrapper
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinProjectExtensionClass
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinSourceSetClass
import org.jetbrains.kotlin.idea.gradleTooling.compilationFullName
import org.jetbrains.kotlin.idea.projectModel.KotlinTaskProperties
import java.io.File
data class KotlinTaskPropertiesImpl(
override val incremental: Boolean?,
override val packagePrefix: String?,
override val pureKotlinSourceFolders: List<File>?,
override val pluginVersion: String?
) : KotlinTaskProperties {
constructor(kotlinTaskProperties: KotlinTaskProperties) : this(
kotlinTaskProperties.incremental,
kotlinTaskProperties.packagePrefix,
kotlinTaskProperties.pureKotlinSourceFolders?.map { it }?.toList(),
kotlinTaskProperties.pluginVersion
)
}
typealias KotlinTaskPropertiesBySourceSet = MutableMap<String, KotlinTaskProperties>
private fun Task.getPackagePrefix(): String? {
try {
val getJavaPackagePrefix = this.javaClass.getMethod("getJavaPackagePrefix")
@Suppress("UNCHECKED_CAST")
return (getJavaPackagePrefix.invoke(this) as? String)
} catch (e: Exception) {
}
return null
}
private fun Task.getIsIncremental(): Boolean? {
try {
val abstractKotlinCompileClass = javaClass.classLoader.loadClass(AbstractKotlinGradleModelBuilder.ABSTRACT_KOTLIN_COMPILE_CLASS)
val getIncremental = abstractKotlinCompileClass.getDeclaredMethod("getIncremental")
@Suppress("UNCHECKED_CAST")
return (getIncremental.invoke(this) as? Boolean)
} catch (e: Exception) {
}
return null
}
private fun Task.getPureKotlinSourceRoots(sourceSet: String, disambiguationClassifier: String? = null): List<File>? {
try {
val kotlinExtensionClass = project.extensions.findByType(javaClass.classLoader.loadClass(kotlinProjectExtensionClass))
val getKotlinMethod = javaClass.classLoader.loadClass(kotlinSourceSetClass).getMethod("getKotlin")
val classifier = if (disambiguationClassifier == "metadata") "common" else disambiguationClassifier
val kotlinSourceSet = (kotlinExtensionClass?.javaClass?.getMethod("getSourceSets")?.invoke(kotlinExtensionClass)
as? FactoryNamedDomainObjectContainer<Any>)?.asMap?.get(compilationFullName(sourceSet, classifier)) ?: return null
val javaSourceSet =
(project.convention.getPlugin(JavaPluginConvention::class.java) as JavaPluginConvention).sourceSets.asMap[sourceSet]
val pureJava = javaSourceSet?.java?.srcDirs
return (getKotlinMethod.invoke(kotlinSourceSet) as? SourceDirectorySet)?.srcDirs?.filter {
!(pureJava?.contains(it) ?: false)
}?.toList()
} catch (e: Exception) {
}
return null
}
private fun Task.getKotlinPluginVersion(): String? {
try {
val pluginWrapperClass = javaClass.classLoader.loadClass(kotlinPluginWrapper)
val getVersionMethod =
pluginWrapperClass.getMethod("getKotlinPluginVersion", javaClass.classLoader.loadClass("org.gradle.api.Project"))
return getVersionMethod.invoke(null, this.project) as String
} catch (e: Exception) {
}
return null
}
fun KotlinTaskPropertiesBySourceSet.acknowledgeTask(compileTask: Task, classifier: String?) {
this[compileTask.getSourceSetName()] =
getKotlinTaskProperties(compileTask, classifier)
}
fun getKotlinTaskProperties(compileTask: Task, classifier: String?): KotlinTaskPropertiesImpl {
return KotlinTaskPropertiesImpl(
compileTask.getIsIncremental(),
compileTask.getPackagePrefix(),
compileTask.getPureKotlinSourceRoots(compileTask.getSourceSetName(), classifier),
compileTask.getKotlinPluginVersion()
)
}
| apache-2.0 | d2b8e5c42ff1c742ff437f84ffd91c2f | 45.541667 | 158 | 0.766115 | 5.293839 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/checkin/GitCommitOptions.kt | 1 | 9848 | // 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 git4idea.checkin
import com.intellij.openapi.Disposable
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil.escapeXmlEntities
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.LocalChangeList
import com.intellij.openapi.vcs.changes.author
import com.intellij.openapi.vcs.changes.authorDate
import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.GridBag
import com.intellij.util.ui.JBUI
import com.intellij.vcs.commit.*
import com.intellij.vcs.log.VcsUser
import com.intellij.vcs.log.VcsUserEditor
import com.intellij.vcs.log.VcsUserEditor.Companion.getAllUsers
import com.intellij.vcs.log.util.VcsUserUtil
import com.intellij.vcs.log.util.VcsUserUtil.isSamePerson
import com.intellij.xml.util.XmlStringUtil
import git4idea.GitUserRegistry
import git4idea.GitUtil.getRepositoryManager
import git4idea.checkin.GitCheckinEnvironment.collectActiveMovementProviders
import git4idea.config.GitVcsSettings
import git4idea.i18n.GitBundle
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Point
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
import java.awt.event.HierarchyEvent
import java.awt.event.HierarchyListener
import java.awt.event.KeyEvent.VK_G
import java.util.*
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.UIManager
private val COMMIT_AUTHOR_KEY = Key.create<VcsUser>("Git.Commit.Author")
private val COMMIT_AUTHOR_DATE_KEY = Key.create<Date>("Git.Commit.AuthorDate")
private val IS_SIGN_OFF_COMMIT_KEY = Key.create<Boolean>("Git.Commit.IsSignOff")
private val IS_COMMIT_RENAMES_SEPARATELY_KEY = Key.create<Boolean>("Git.Commit.IsCommitRenamesSeparately")
internal var CommitContext.commitAuthor: VcsUser? by commitProperty(COMMIT_AUTHOR_KEY, null)
internal var CommitContext.commitAuthorDate: Date? by commitProperty(COMMIT_AUTHOR_DATE_KEY, null)
internal var CommitContext.isSignOffCommit: Boolean by commitProperty(IS_SIGN_OFF_COMMIT_KEY)
internal var CommitContext.isCommitRenamesSeparately: Boolean by commitProperty(IS_COMMIT_RENAMES_SEPARATELY_KEY)
private val HierarchyEvent.isShowingChanged get() = (changeFlags and HierarchyEvent.SHOWING_CHANGED.toLong()) != 0L
private val HierarchyEvent.isParentChanged get() = (changeFlags and HierarchyEvent.PARENT_CHANGED.toLong()) != 0L
private val CheckinProjectPanel.commitAuthorTracker: CommitAuthorTracker? get() = commitWorkflowHandler as? CommitAuthorTracker
class GitCommitOptionsUi(
private val commitPanel: CheckinProjectPanel,
private val commitContext: CommitContext,
private val showAmendOption: Boolean
) : RefreshableOnComponent,
CheckinChangeListSpecificComponent,
AmendCommitModeListener,
CommitAuthorListener,
Disposable {
private val project get() = commitPanel.project
private val settings = GitVcsSettings.getInstance(project)
private val userRegistry = GitUserRegistry.getInstance(project)
val amendHandler: AmendCommitHandler get() = commitPanel.commitWorkflowHandler.amendCommitHandler
private var authorDate: Date? = null
private val panel = JPanel(GridBagLayout())
private val authorField = VcsUserEditor(project, getKnownCommitAuthors())
private val signOffCommit = JBCheckBox(GitBundle.message("commit.options.sign.off.commit.checkbox"), settings.shouldSignOffCommit()).apply {
mnemonic = VK_G
val user = commitPanel.roots.mapNotNull { userRegistry.getUser(it) }.firstOrNull()
val signature = user?.let { escapeXmlEntities(VcsUserUtil.toExactString(it)) }.orEmpty()
toolTipText = XmlStringUtil.wrapInHtml(GitBundle.message("commit.options.sign.off.commit.message.line", signature))
}
private val commitRenamesSeparately = JBCheckBox(
GitBundle.message("commit.options.create.extra.commit.with.file.movements"),
settings.isCommitRenamesSeparately
)
private var authorWarning: Balloon? = null
init {
authorField.addFocusListener(object : FocusAdapter() {
override fun focusLost(e: FocusEvent) {
updateCurrentCommitAuthor()
clearAuthorWarning()
}
})
authorField.addHierarchyListener(object : HierarchyListener {
override fun hierarchyChanged(e: HierarchyEvent) {
if (e.isShowingChanged && authorField.isShowing && authorField.user != null) {
showAuthorWarning()
authorField.removeHierarchyListener(this)
}
}
})
buildLayout()
amendHandler.addAmendCommitModeListener(this, this)
}
private fun buildLayout() = panel.apply {
val gb = GridBag().setDefaultAnchor(GridBagConstraints.WEST).setDefaultInsets(JBUI.insets(2))
val authorLabel = JBLabel(GitBundle.message("commit.author")).apply { labelFor = authorField }
add(authorLabel, gb.nextLine().next())
add(authorField, gb.next().fillCellHorizontally().weightx(1.0))
val amendOption = if (showAmendOption) ToggleAmendCommitOption(commitPanel, this@GitCommitOptionsUi) else null
amendOption?.let { add(it, gb.nextLine().next().coverLine()) }
add(signOffCommit, gb.nextLine().next().coverLine())
add(commitRenamesSeparately, gb.nextLine().next().coverLine())
}
// called before popup size calculation => changing preferred size here will be correctly reflected by popup
private fun beforeShow() = updateRenamesCheckboxState()
override fun amendCommitModeToggled() = updateRenamesCheckboxState()
override fun dispose() = Unit
override fun getComponent(): JComponent = panel
override fun restoreState() {
if (commitPanel.isNonModalCommit) {
commitPanel.commitAuthorTracker?.addCommitAuthorListener(this, this)
panel.addHierarchyListener { e ->
if (e.isParentChanged && panel == e.changed && panel.parent != null) beforeShow()
}
}
refresh(null)
commitAuthorChanged()
commitAuthorDateChanged()
}
override fun saveState() {
if (commitPanel.isNonModalCommit) updateRenamesCheckboxState()
val author = getAuthor()
commitContext.apply {
commitAuthor = author
commitAuthorDate = authorDate
isSignOffCommit = signOffCommit.isSelected
isCommitRenamesSeparately = commitRenamesSeparately.run { isEnabled && isSelected }
}
settings.apply {
author?.let { saveCommitAuthor(it) }
setSignOffCommit(signOffCommit.isSelected)
isCommitRenamesSeparately = commitRenamesSeparately.isSelected
}
}
override fun onChangeListSelected(list: LocalChangeList) {
refresh(list)
panel.revalidate()
panel.repaint()
}
private fun refresh(changeList: LocalChangeList?) {
updateRenamesCheckboxState()
clearAuthorWarning()
setAuthor(changeList?.author)
authorDate = changeList?.authorDate
}
fun getAuthor(): VcsUser? = authorField.user
private fun setAuthor(author: VcsUser?) {
val isAuthorNullOrDefault = author == null || isDefaultAuthor(author)
authorField.user = author.takeUnless { isAuthorNullOrDefault }
if (!isAuthorNullOrDefault) {
authorField.putClientProperty("JComponent.outline", "warning") // NON-NLS
if (authorField.isShowing) showAuthorWarning()
}
}
private fun updateCurrentCommitAuthor() {
commitPanel.commitAuthorTracker?.commitAuthor = getAuthor()
}
override fun commitAuthorChanged() {
val newAuthor = commitPanel.commitAuthorTracker?.commitAuthor
if (getAuthor() != newAuthor) setAuthor(newAuthor)
}
override fun commitAuthorDateChanged() {
authorDate = commitPanel.commitAuthorTracker?.commitAuthorDate
}
private fun updateRenamesCheckboxState() {
val providers = collectActiveMovementProviders(project)
commitRenamesSeparately.apply {
text = providers.singleOrNull()?.description ?: GitBundle.message("commit.options.create.extra.commit.with.file.movements")
isVisible = providers.isNotEmpty()
isEnabled = isVisible && !amendHandler.isAmendCommitMode
}
}
private fun showAuthorWarning() {
if (authorWarning?.isDisposed == false) return
val builder = JBPopupFactory.getInstance()
.createBalloonBuilder(JLabel(GitBundle.message("commit.author.diffs")))
.setBorderInsets(UIManager.getInsets("Balloon.error.textInsets")) // NON-NLS
.setBorderColor(JBUI.CurrentTheme.Validator.warningBorderColor())
.setFillColor(JBUI.CurrentTheme.Validator.warningBackgroundColor())
.setHideOnClickOutside(true)
.setHideOnFrameResize(false)
authorWarning = builder.createBalloon()
authorWarning?.show(RelativePoint(authorField, Point(authorField.width / 2, authorField.height)), Balloon.Position.below)
}
private fun clearAuthorWarning() {
authorField.putClientProperty("JComponent.outline", null) // NON-NLS
authorWarning?.hide()
authorWarning = null
}
private fun getKnownCommitAuthors(): List<String> = (getAllUsers(project) + settings.commitAuthors).distinct().sorted()
private fun isDefaultAuthor(author: VcsUser): Boolean {
val repositoryManager = getRepositoryManager(project)
val affectedRoots = commitPanel.roots.filter { repositoryManager.getRepositoryForRootQuick(it) != null }
return affectedRoots.isNotEmpty() &&
affectedRoots.map { userRegistry.getUser(it) }.all { it != null && isSamePerson(author, it) }
}
} | apache-2.0 | 7b0d79b993be7aa86b13cc21ffe9d118 | 38.239044 | 142 | 0.768684 | 4.373002 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-junit-engine/src/main/kotlin/org/livingdoc/junit/engine/descriptors/ScenarioTestDescriptor.kt | 2 | 3979 | package org.livingdoc.junit.engine.descriptors
import org.junit.platform.engine.TestDescriptor
import org.junit.platform.engine.TestSource
import org.junit.platform.engine.UniqueId
import org.junit.platform.engine.support.descriptor.AbstractTestDescriptor
import org.junit.platform.engine.support.descriptor.ClassSource
import org.junit.platform.engine.support.descriptor.MethodSource
import org.junit.platform.engine.support.hierarchical.Node
import org.junit.platform.engine.support.hierarchical.Node.SkipResult.doNotSkip
import org.junit.platform.engine.support.hierarchical.Node.SkipResult.skip
import org.livingdoc.junit.engine.LivingDocContext
import org.livingdoc.results.Status
import org.livingdoc.results.examples.scenarios.ScenarioResult
import org.livingdoc.results.examples.scenarios.StepResult
class ScenarioTestDescriptor private constructor(
uniqueId: UniqueId,
displayName: String,
private val scenarioResult: ScenarioResult,
testSource: TestSource?
) : AbstractTestDescriptor(uniqueId, displayName, testSource), Node<LivingDocContext> {
override fun getType() = TestDescriptor.Type.CONTAINER
override fun execute(context: LivingDocContext, dynamicTestExecutor: Node.DynamicTestExecutor): LivingDocContext {
scenarioResult.steps.mapIndexed { index, stepResult ->
StepTestDescriptor(
stepUniqueId(index),
stepDisplayName(stepResult),
stepResult,
stepResult.fixtureMethod?.let { MethodSource.from(it) }
)
}.onEach { it.setParent(this) }.forEach { dynamicTestExecutor.execute(it) }
return context
}
private fun stepUniqueId(index: Int) = uniqueId.append("step", "$index")
private fun stepDisplayName(stepResult: StepResult) = stepResult.value
override fun shouldBeSkipped(context: LivingDocContext): Node.SkipResult {
return when (val result = scenarioResult.status) {
Status.Unknown -> skip("unknown")
is Status.Disabled -> skip(result.reason)
Status.Skipped -> skip("skipped")
Status.Manual -> skip("manual")
else -> doNotSkip()
}
}
companion object {
/**
* Create a new [ScenarioTestDescriptor] from the [uniqueId] and with the given [index] representing the
* [result].
*/
fun from(uniqueId: UniqueId, index: Int, result: ScenarioResult): ScenarioTestDescriptor {
return ScenarioTestDescriptor(
scenarioUniqueId(uniqueId, index),
scenarioDisplayName(index),
result,
result.fixtureSource?.let { ClassSource.from(it) }
)
}
private fun scenarioUniqueId(uniqueId: UniqueId, index: Int) = uniqueId.append("scenario", "$index")
private fun scenarioDisplayName(index: Int) = "Scenario #${index + 1}"
}
class StepTestDescriptor(
uniqueId: UniqueId,
displayName: String,
private val stepResult: StepResult,
testSource: TestSource?
) : AbstractTestDescriptor(uniqueId, displayName, testSource), Node<LivingDocContext> {
override fun getType() = TestDescriptor.Type.TEST
override fun execute(
context: LivingDocContext,
dynamicTestExecutor: Node.DynamicTestExecutor
): LivingDocContext {
when (val result = stepResult.status) {
is Status.Failed -> throw result.reason
is Status.Exception -> throw result.exception
}
return context
}
override fun shouldBeSkipped(context: LivingDocContext): Node.SkipResult {
return when (val result = stepResult.status) {
Status.Unknown -> skip("unknown")
is Status.Disabled -> skip(result.reason)
Status.Skipped -> skip("skipped")
else -> doNotSkip()
}
}
}
}
| apache-2.0 | 672498ae894fbc5b4d822cd28423d0b0 | 39.602041 | 118 | 0.669012 | 4.799759 | false | true | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/matching/MatchingFunctions.kt | 2 | 9732 | package org.livingdoc.engine.execution.examples.scenarios.matching
/**
* All functions used to perform the regex Matching
*/
object MatchingFunctions {
/**
* regex when not at then end of the template
*/
private val regularExpression = "(.*\\s|)"
/**
* regex when at the end of the template
*/
private val endOfStringRegex = "(\\s.*|)"
/**
* regex when there are symbols before/after the variable in the template
*/
private val allRegex = "(.*)"
/**
* characters used by regex that need to be escaped
*/
private val regexCharacters =
listOf('.', '*', '+', '^', '-', '\\', '|', '$', '&', '(', ')', '/', '[', ']', '?', '{', '}')
/**
* change all "an" to "a"
* escape all regex symbols unless it is a variable or a step string
* @param string the template string
* @return prepared string to be used for precalculations for regex
*/
fun filterString(string: String, isStep: Boolean): String {
val tokens = string.split(" ")
val out = tokens.map {
if (it.equals("an")) "a"
else if (isStep || checkIfVar(it)) it
else it.map { character ->
if (regexCharacters.contains(character)) "\\$character"
else "$character"
}.joinToString("")
}
val outputString = out.joinToString(" ")
return outputString
}
/**
* function to consider the length of each variable
* cost is added if variable length is too high
* @return the increase of cost
*/
fun considerVarLength(templatetextTokenized: Map<String, String>): Float {
if (templatetextTokenized.isNotEmpty()) {
val sum = templatetextTokenized.values.sumBy { string -> string.length }.toFloat()
return sum / templatetextTokenized.size
} else
return 0.0f
}
/**
* Postfiltering the blank out of the variable value
* Regex accepted one more blank than needed
* @return Variable value
*/
fun variablevaluePostcalc(it: String): String {
var variableValue = it
// look at the string with condition of being not empty
if (it.toCharArray().isNotEmpty()) {
// last one is a blank or first one is a blank
if (it.toCharArray().last().equals(' ')) {
variableValue = it.toCharArray().dropLast(1).joinToString("")
} else if (it.toCharArray().first().equals(' ')) {
variableValue = it.toCharArray().drop(1).joinToString("")
}
}
return variableValue
}
/**
* check if a variable is in a string
*
* @param st the string to be checked
* @return if it is a variable
*/
fun checkIfVar(st: String): Boolean {
return st.contains("{") && st.contains("}")
}
/**
* getting the variables and creating the regex by replacing the "{variable}"
* with regexes.
*
* variable is in final two strings
* case 1: "string string {variable} string" & "string string {variable}"
*
* variable is at the beginning or at any other position
* case 2: "string {variable} string string"
*
* the template has only one string as component
* case 3: "{variable}" & "string"
*
* @param value the input string(step template)
*
* @return Pair of regex as string and the map with the variable names
*
*/
fun templateStepToRegexString(value: String): Pair<String, List<String>> {
var interntext = value.split(" ")
val variablesMap = mutableListOf<String>()
var singlestring = true
var lineend = ""
var lastentry = ""
var secondlast = ""
// if the template is longer than one string
if (interntext.size >= 2) {
// handle last two strings separately
lastentry = interntext.last()
secondlast = interntext[interntext.size - 2]
singlestring = false
lineend = " "
// for the rest do a mapping
interntext = interntext.dropLast(2)
}
val outmap = interntext.map {
if (checkIfVar(it)) {
val bracketcount = countBrackets(it.toCharArray())
val (before, variable, after) = constructVar(it, bracketcount)
variablesMap.add(variable)
getRegex(before, after, false, singlestring)
} else {
it + lineend
}
}
val outstring = outmap.joinToString("")
// consider last two strings and put all together
if (singlestring)
return Pair(outstring, variablesMap)
return computeRegexAtEndOfString(outstring, lastentry, secondlast, variablesMap)
}
/**
* the final two strings in a template have to be looked at separately
* there are three cases
*
* {variable} string
* and
* string {variable}
* and
* string string
*
* because of an empty string as input the blanks in the strings above have to be
* handled outside of the main string
*
* output will be regex string and the variable added to the variables map
*
* @return Pair of the regex string and the map with variables
*/
private fun computeRegexAtEndOfString(
outstring: String,
lastentry: String,
secondlast: String,
variablesMap: List<String>
): Pair<String, List<String>> {
var inneroutstring = outstring
val innerVariableMap = variablesMap.toMutableList()
// check last one and add them to the outmap
if (checkIfVar(lastentry)) {
val bracketcount = countBrackets(lastentry.toCharArray())
val (before, variable, after) = constructVar(lastentry, bracketcount)
// adding the varibale name
innerVariableMap.add(variable)
// rebuilding the regex string
inneroutstring += secondlast + before +
getRegex(before, after, true, false) + after
} else if (checkIfVar(secondlast)) {
val bracketcount = countBrackets(secondlast.toCharArray())
val (before, variable, after) = constructVar(secondlast, bracketcount)
innerVariableMap.add(variable)
inneroutstring +=
getRegex(before, after, false, false) + lastentry
} else {
inneroutstring += secondlast + " " + lastentry
}
return Pair(inneroutstring, innerVariableMap)
}
/**
* filter out the variable name and set the surrounding symbols around the regex
* builder for the regex
*
* @param variable the input variable the be checked
* @param bracketcount the number of brackets counted in before
* @return a triple containing the string before, after and inside brackets
*/
private fun constructVar(variable: String, bracketcount: Int): Triple<String, String, String> {
var open: Int = bracketcount
var closed: Int = bracketcount
var afterstring = false
var beforestring = true
var mainstring = ""
var beforeconc = ""
var afterconc = ""
variable.forEach {
// order MUST NOT be changed
if (afterstring)
afterconc += it
if (it.equals('}')) {
if (closed == 1)
afterstring = true
closed--
}
// the main string
if (!beforestring && !afterstring)
mainstring += it
// the before string
if (it.equals('{')) {
open--
beforestring = false
}
if (beforestring)
beforeconc += it
}
return Triple(beforeconc, mainstring, afterconc)
}
/**
* simple counter method to count number of brackets
* preparation for the variable check afterwards
*
* opening bracket count must be equal to the closing count
* defined in steptemplate
* @param input the string to be checked as chararray
* @return number of brackets found
*/
private fun countBrackets(input: CharArray): Int {
return input.count { "{".contains(it) }
}
/**
* depending on situation substitute a regex
*
* some text {variable} -> some text(regex)
* some {variable} text text -> some (regex)text text
* {variable} some text -> (regex)some text
* some{variable}text -> some(regex)text
*
* @param before string immediately in front of the brackets
* @param after string immedietaly after the brackets
* @param stringend if we are at the end of the string
* @return the substituted regex
*
*/
private fun getRegex(before: String, after: String, stringend: Boolean, singlestring: Boolean): String {
if (singlestring) {
return before + allRegex + after
}
var regexValue = ""
// depending whether there are symbols right before/after the brackets of the variable
if (before.equals("") && after.equals("")) {
// are we at the end of a string
if (stringend)
regexValue = endOfStringRegex
else
regexValue = regularExpression
} else {
// are we at the end of a string
if (stringend)
regexValue = before + allRegex + after
else
regexValue = before + allRegex + after + " "
}
return regexValue
}
}
| apache-2.0 | 2838cfeb511e66d6366d9d559d9595a6 | 32.909408 | 108 | 0.575216 | 4.654232 | false | false | false | false |
Yorxxx/played-next-kotlin | app/src/main/java/com/piticlistudio/playednext/data/repository/datasource/room/relation/RoomRelationRepositoryImpl.kt | 1 | 2095 | package com.piticlistudio.playednext.data.repository.datasource.room.relation
import com.piticlistudio.playednext.data.entity.mapper.datasources.relation.RoomRelationMapper
import com.piticlistudio.playednext.data.repository.datasource.RelationDatasourceRepository
import com.piticlistudio.playednext.data.repository.datasource.room.game.RoomGameRepositoryImpl
import com.piticlistudio.playednext.data.repository.datasource.room.platform.RoomGamePlatformRepositoryImpl
import com.piticlistudio.playednext.domain.model.GameRelation
import com.piticlistudio.playednext.domain.model.GameRelationStatus
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.functions.Function3
import javax.inject.Inject
class RoomRelationRepositoryImpl @Inject constructor(private val dao: RoomRelationService,
private val gamesRepository: RoomGameRepositoryImpl,
private val platformRepositoryImpl: RoomGamePlatformRepositoryImpl,
private val mapper: RoomRelationMapper) : RelationDatasourceRepository {
override fun save(data: GameRelation): Completable {
return Completable.defer {
val result = dao.insert(mapper.mapIntoDataLayerModel(data).relation)
if (result > 0L) Completable.complete() else Completable.error(RelationSaveException())
}
}
override fun loadForGameAndPlatform(gameId: Int, platformId: Int): Flowable<List<GameRelation>> {
return Flowable.combineLatest(gamesRepository.load(gameId), platformRepositoryImpl.load(platformId), dao.findForGameAndPlatform(gameId, platformId), Function3 { t1, t2, t3 ->
mutableListOf<GameRelation>().apply {
t3.forEach {
add(GameRelation(game = t1, platform = t2, status = GameRelationStatus.values()[it.status], updatedAt = it.updated_at, createdAt = it.created_at))
}
}
})
}
}
class RelationSaveException : RuntimeException() | mit | 855c7fb2a0c59c658181dd77ccadd229 | 55.648649 | 182 | 0.7179 | 5.060386 | false | false | false | false |
aleksanderwozniak/WhatsThatFlag | app/src/main/java/me/wozappz/whatsthatflag/screens/game/AnswerAnimationManager.kt | 1 | 4246 | package me.wozappz.whatsthatflag.screens.game
import android.graphics.PorterDuff
import android.os.CountDownTimer
import android.support.v4.content.ContextCompat
import android.widget.Button
import kotlinx.android.synthetic.main.activity_game.*
import me.wozappz.whatsthatflag.R
/**
* Created by olq on 16.12.17.
*/
class AnswerAnimationManager (private val gameActivity: GameActivity) {
private var answerTimer: CountDownTimer? = null
private var animationTimer: CountDownTimer? = null
fun animateCorrectAnswer(btnName: String, staticAnimation: Boolean) {
val buttons = listOf(gameActivity.mBtnA, gameActivity.mBtnB, gameActivity.mBtnC, gameActivity.mBtnD)
val correctBtn = buttons.find { btn -> btn.text == btnName }!!
val colorGreen = ContextCompat.getColor(gameActivity, R.color.green)
val colorGray = ContextCompat.getColor(gameActivity, R.color.bluishGray)
var isGreenTinted = false
if (staticAnimation) {
correctBtn.background.setColorFilter(colorGreen, PorterDuff.Mode.SRC)
animationTimer = object : CountDownTimer(1500, 1500) {
override fun onFinish() {
correctBtn.background.setColorFilter(colorGray, PorterDuff.Mode.SRC)
gameActivity.presenter.animationTimerFinished()
}
override fun onTick(p0: Long) {}
}.start()
} else {
animationTimer = object : CountDownTimer(1500, 250) {
override fun onFinish() {
correctBtn.background.setColorFilter(colorGray, PorterDuff.Mode.SRC)
gameActivity.presenter.animationTimerFinished()
}
override fun onTick(p0: Long) {
isGreenTinted = blinkingAnimation(correctBtn, colorGray, colorGreen, isGreenTinted)
}
}.start()
}
}
fun animateWrongAnswer(btnSelectedName: String, btnCorrectName: String) {
val buttons = listOf(gameActivity.mBtnA, gameActivity.mBtnB, gameActivity.mBtnC, gameActivity.mBtnD)
val correctBtn = buttons.find { btn -> btn.text == btnCorrectName }!!
val wrongBtn = buttons.find { btn -> btn.text == btnSelectedName }!!
val colorGreen = ContextCompat.getColor(gameActivity, R.color.green)
val colorRed = ContextCompat.getColor(gameActivity, R.color.red)
val colorGray = ContextCompat.getColor(gameActivity, R.color.bluishGray)
var isGreenTinted = false
wrongBtn.background.setColorFilter(colorRed, PorterDuff.Mode.SRC)
animationTimer = object : CountDownTimer(1500, 250) {
override fun onFinish() {
wrongBtn.background.setColorFilter(colorGray, PorterDuff.Mode.SRC)
correctBtn.background.setColorFilter(colorGray, PorterDuff.Mode.SRC)
gameActivity.presenter.animationTimerFinished()
}
override fun onTick(p0: Long) {
isGreenTinted = blinkingAnimation(correctBtn, colorGray, colorGreen, isGreenTinted)
}
}.start()
}
private fun blinkingAnimation(btn: Button, colorNormal: Int, colorTint: Int, isTinted: Boolean): Boolean {
if (isTinted) {
btn.background.setColorFilter(colorNormal, PorterDuff.Mode.SRC)
} else {
btn.background.setColorFilter(colorTint, PorterDuff.Mode.SRC)
}
return !isTinted
}
fun createAnswerTimer(timeForAnswer: Int) {
answerTimer = object : CountDownTimer(timeForAnswer.toLong(), 10) {
override fun onFinish() {
gameActivity.presenter.answerTimerFinished()
}
override fun onTick(timeTillFinished: Long) {
val progress = timeForAnswer - timeTillFinished
gameActivity.updateAnswerTimerProgressBar(progress.toInt())
}
}
}
fun startAnswerTimer() {
answerTimer?.start()
}
fun stopAnswerTimer() {
answerTimer?.cancel()
}
fun stopAnimationTimer() {
animationTimer?.cancel()
}
fun answerTimerExists() : Boolean {
return answerTimer != null
}
} | apache-2.0 | 3d5230d7de44c13d1aba8afc2bf22370 | 33.811475 | 110 | 0.642723 | 4.497881 | false | false | false | false |
vjache/klips | src/main/java/org/klips/engine/rete/db/BindingComparator.kt | 1 | 814 | package org.klips.engine.rete.db
import org.klips.dsl.Facet
import org.klips.engine.Binding
import java.util.*
class BindingComparator(val refs: Collection<Facet.FacetRef<*>>) :Comparator<Binding> {
override fun compare(first: Binding?, second: Binding?): Int {
if (first === second) return 0
if (first == null) return 1
if (second == null) return -1
for(k in refs)
{
val vf = first[k]
val vs = second[k]
if (vf == null) {
if (vs == null) continue
else return 1
} else if (vs == null)
return -1
val cmp = vf.compareTo(vs)
if (cmp == 0)
continue
else
return cmp
}
return 0
}
} | apache-2.0 | 9a8edd18191c46ca080e219004c369a2 | 20.447368 | 87 | 0.493857 | 4.239583 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/search/discover/SearchResultViewHolder.kt | 1 | 2958 | package com.battlelancer.seriesguide.shows.search.discover
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 com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.shows.search.discover.AddFragment.AddAdapter.OnItemClickListener
import com.battlelancer.seriesguide.util.ImageTools
class SearchResultViewHolder(
itemView: View,
onItemClickListener: OnItemClickListener
) : RecyclerView.ViewHolder(itemView) {
private val title = itemView.findViewById<TextView>(R.id.textViewAddTitle)
private val description = itemView.findViewById<TextView>(R.id.textViewAddDescription)
private val poster = itemView.findViewById<ImageView>(R.id.imageViewAddPoster)
private val addIndicator = itemView.findViewById<AddIndicator>(R.id.addIndicatorAddShow)
private val buttonContextMenu = itemView.findViewById<ImageView>(R.id.buttonItemAddMore)
private var item: SearchResult? = null
init {
itemView.setOnClickListener { _ ->
item?.let {
onItemClickListener.onItemClick(it)
}
}
addIndicator.setOnAddClickListener { _ ->
item?.let {
onItemClickListener.onAddClick(it)
}
}
}
fun bindTo(searchResult: SearchResult?) {
this.item = searchResult
// hide watchlist menu
buttonContextMenu.visibility = View.GONE
// display added indicator instead of add button if already added that show
val showTitle = searchResult?.title
if (searchResult != null) {
addIndicator.setState(searchResult.state)
addIndicator.setContentDescriptionAdded(
itemView.context.getString(R.string.add_already_exists, showTitle))
addIndicator.visibility = View.VISIBLE
} else {
addIndicator.visibility = View.GONE
}
title.text = showTitle
description.text = searchResult?.overview
// only local shows will have a poster path set
// try to fall back to the TMDB poster for all others
val posterUrl = if (searchResult != null) {
ImageTools.posterUrlOrResolve(
searchResult.posterPath,
searchResult.tmdbId,
searchResult.language,
itemView.context
)
} else null
ImageTools.loadShowPosterUrlResizeCrop(itemView.context, poster, posterUrl)
}
companion object {
fun create(parent: ViewGroup,
onItemClickListener: OnItemClickListener): SearchResultViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_addshow, parent, false)
return SearchResultViewHolder(view, onItemClickListener)
}
}
} | apache-2.0 | 115ab236f2c1f61d0e6e5c190b6753e4 | 35.9875 | 100 | 0.676809 | 5.135417 | false | false | false | false |
UweTrottmann/SeriesGuide | widgets/src/main/java/com/uwetrottmann/seriesguide/widgets/WrappingViewPager.kt | 1 | 1446 | package com.uwetrottmann.seriesguide.widgets
import android.content.Context
import android.util.AttributeSet
import androidx.viewpager.widget.ViewPager
/**
* [ViewPager] that measures current page height to use as its height.
*/
class WrappingViewPager @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : ViewPager(context, attrs) {
init {
addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
requestLayout() // to measure new current page and adjust height
}
})
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var heightMeasureSpecUpdate = heightMeasureSpec
val child = getChildAt(currentItem)
if (child != null) {
child.measure(
widthMeasureSpec,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
)
val h = child.measuredHeight
heightMeasureSpecUpdate = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY)
}
super.onMeasure(widthMeasureSpec, heightMeasureSpecUpdate)
}
} | apache-2.0 | 99e58e1366d1d5150423f76e3861f08f | 28.530612 | 89 | 0.631397 | 5.715415 | false | false | false | false |
NLPIE/BioMedICUS | biomedicus-core/src/main/kotlin/edu/umn/biomedicus/sentences/SentencesEvaluator.kt | 1 | 2612 | /*
* Copyright (c) 2018 Regents of the University of Minnesota.
*
* 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 edu.umn.biomedicus.sentences
import edu.umn.biomedicus.annotations.ProcessorScoped
import edu.umn.biomedicus.annotations.ComponentSetting
import edu.umn.biomedicus.sentences
import edu.umn.nlpengine.Artifact
import edu.umn.nlpengine.ArtifactTask
import java.io.File
import javax.inject.Inject
/**
* Evaluates sentence segmentation performance using simple accuracy counting the number of
* sentences from the gold standard document that are present in the evaluation document and are not
* present in the evaluation document.
*/
class SentencesEvaluator @Inject internal constructor(
@ComponentSetting("evaluatedDocument") private val evaluatedDocumentName: String,
@ComponentSetting("goldDocument") private val goldDocumentName: String,
private val sentencesEvaluationWriter: SentencesEvaluationWriter
) : ArtifactTask {
override fun run(artifact: Artifact) {
val goldDocument = artifact.documents[goldDocumentName]
?: error("No gold document: $goldDocumentName")
val evaluatedDocument = artifact.documents[evaluatedDocumentName]
?: error("No evaluated document: $evaluatedDocumentName")
var hits = 0
var misses = 0
val evaluatedSentences = evaluatedDocument.sentences()
for (sentence in goldDocument.sentences()) {
if (sentence.sentenceClass == 0) continue
if (evaluatedSentences.contains(sentence)) {
hits++
} else {
misses++
}
}
sentencesEvaluationWriter.write("$hits $misses\n")
}
}
@ProcessorScoped
internal class SentencesEvaluationWriter(private val outputFile: File) {
@Inject internal constructor(
@ComponentSetting("outputFile") outputFile: String
) : this(File(outputFile))
private val lock = Object()
fun write(text: String) {
synchronized(lock) {
outputFile.appendText(text)
}
}
}
| apache-2.0 | e881e4a260036d81e4da045ab6ec49a2 | 34.297297 | 100 | 0.705207 | 4.740472 | false | false | false | false |
tommy-kw/ViewAnimator | app/src/main/java/tokyo/tommy_kw/viewanimator/MainActivity.kt | 2 | 1911 | package tokyo.tommy_kw.viewanimator
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.View
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import android.widget.Toolbar
import tokyo.tommy_kw.viewanimator.fv
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val icon: ImageView = fv(R.id.icon)
icon.anim(5000)
//icon.animTranslationX(0f, 200f)
icon.anim01(100.0, 200f)
val fab:FloatingActionButton = fv(R.id.fab)
fab.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
})
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
| apache-2.0 | 0a6f2fd8940cbea08658e60be867344b | 33.745455 | 122 | 0.692308 | 4.363014 | false | false | false | false |
myfreeweb/freepass | android/app/src/main/java/technology/unrelenting/freepass/EntryFragment.kt | 1 | 3360 | package technology.unrelenting.freepass
import android.app.Activity
import android.app.Fragment
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.view.*
import android.widget.BaseAdapter
//import com.jakewharton.rxbinding2.widget.*
import kotlinx.android.synthetic.main.entry.*
import technology.unrelenting.freepass.databinding.FieldBinding
import java.util.*
class EntryFragment: Fragment() {
companion object {
const val ENTRY_NAME = "entry_name"
}
var entryName = "New entry"
var fieldModels = ArrayList<FieldViewModel>()
val fieldListAdapter = FieldListAdapter(this)
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
entryName = arguments.getString(ENTRY_NAME)
val entryCode = Vault.getEntry(entryName)
if (entryCode != null) {
val entry = Entry.fromCbor(entryCode!!)
entry.fields.forEach {
fieldModels.add(FieldViewModel(it.key, it.value))
}
}
setHasOptionsMenu(true)
return inflater?.inflate(R.layout.entry, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fields_list.adapter = fieldListAdapter
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.entry, menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.add_field -> {
fieldModels.add(FieldViewModel("New field"))
fieldListAdapter.notifyDataSetChanged()
}
}
return false
}
class FieldListAdapter(val fragment: EntryFragment): BaseAdapter() {
var list = fragment.fieldModels
var inflater: LayoutInflater? = null
override fun getView(i: Int, v: View?, parent: ViewGroup?): View? {
if (parent == null) return null
inflater = inflater ?: (parent.context as? Activity)?.layoutInflater
val binding = DataBindingUtil.getBinding<FieldBinding>(v!!)
?: DataBindingUtil.inflate<FieldBinding>(inflater!!, R.layout.field, parent, false)
binding.vm = getItem(i)
return binding.root
// val typeRadio = radioGroup {
// orientation = RadioGroup.HORIZONTAL
// val der = radioButton { text = "Derived" }
// val stor = radioButton { text = "Stored" }
// Log.w("WTF", "WAT")
// check(if (model.field_type.get() == FieldViewModel.FieldType.Derived) der.id else stor.id)
// checkedChanges().subscribe() {
// Log.w("Check", it.toString())
// model.field_type.set(if (it == der.id) FieldViewModel.FieldType.Derived else FieldViewModel.FieldType.Stored)
// }
// }.lparams { width = matchParent; below(nameEdit) }
// val counterLabel = textView {
// text = "Counter"
// }.lparams { below(typeRadio) }
// val counterEdit = editText {
// inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
// filters = arrayOf(NumberLimitsInputFilter(0, 4294967295))
// }.lparams { below(typeRadio); rightOf(counterLabel) }
}
override fun getItem(position: Int): FieldViewModel {
return list[position]
}
override fun getCount(): Int {
return list.size
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
}
} | unlicense | a05e19efd007acee00e3d5be3fe4be8a | 32.277228 | 118 | 0.706845 | 3.708609 | false | false | false | false |
klose911/klose911.github.io | src/kotlin/src/tutorial/collections/operation/CommonOperationSample.kt | 1 | 838 | package tutorial.collections.operation
fun main() {
val numbers = listOf("one", "two", "three", "four")
numbers.filter { it.length > 3 } // `numbers` 没有任何改变,结果丢失
println("numbers are still $numbers")
val longerThan3 = numbers.filter { it.length > 3 } // 结果存储在 `longerThan3` 中
println("numbers longer than 3 chars are $longerThan3")
val filterResults = mutableListOf<String>() // 目标对象
numbers.filterTo(filterResults) { it.length > 3 }
numbers.filterIndexedTo(filterResults) { index, _ -> index == 0 }
println(filterResults) // 包含两个操作的结果
// 将数字直接过滤到新的哈希集中,
// 从而消除结果中的重复项
val result = numbers.mapTo(HashSet()) { it.length }
println("distinct item lengths are $result")
} | bsd-2-clause | 4fbd14a0d58eeb5526a72f906ef1295a | 35.35 | 79 | 0.668044 | 3.408451 | false | false | false | false |
weisterjie/FamilyLedger | app/src/main/java/ycj/com/familyledger/utils/SPUtils.kt | 1 | 1177 | package ycj.com.familyledger.utils
import android.content.Context
import android.content.SharedPreferences
import ycj.com.familyledger.Consts
/**
* @author: ycj
* @date: 2017-06-22 16:54
* @version V1.0 <>
*/
class SPUtils {
companion object {
fun getInstance() = Holder.instance
}
private object Holder {
val instance = SPUtils()
}
private var mContext: Context? = null
private lateinit var sp: SharedPreferences
fun init(context: Context) {
this.mContext = context
sp = mContext?.getSharedPreferences(Consts.SP_APP_NAME, android.content.Context.MODE_PRIVATE)!!
}
fun getString(key: String): String {
return sp.getString(key, "")
}
fun getLong(key: String): Long {
return sp.getLong(key, 0)
}
fun getInt(key: String): Int {
return sp.getInt(key, 0)
}
fun putInt(key: String, value: Int) {
sp.edit().putInt(key, value)?.apply()
}
fun putLong(key: String, value: Long) {
sp.edit().putLong(key, value)?.apply()
}
fun putString(key: String, value: String) {
sp.edit().putString(key, value)?.apply()
}
} | apache-2.0 | 4546294ac3b6ffa252b9cddf87a29a6d | 20.418182 | 103 | 0.617672 | 3.859016 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/metrics/CalendarWeekTest.kt | 1 | 3183 | package de.maibornwolff.codecharta.importer.gitlogparser.input.metrics
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.OffsetDateTime
import java.time.ZoneOffset
class CalendarWeekTest {
private val zoneOffset = ZoneOffset.UTC
@Test
fun canCreateCalendarWeekFromADateTime() {
// given
val commitDateTime = OffsetDateTime.of(2016, 4, 2, 12, 0, 0, 0, zoneOffset)
// when
val kw = CalendarWeek.forDateTime(commitDateTime)
// then
assertThat(kw).isEqualTo(CalendarWeek(13, 2016))
}
@Test
fun calendarWeekProperlyCalculated_when_dayAtStartOfYear_and_weekInLastYear_and_53WeeksInLastYear() {
// given
val commitDateTime = OffsetDateTime.of(2016, 1, 3, 12, 0, 0, 0, zoneOffset)
// when
val kw = CalendarWeek.forDateTime(commitDateTime)
// then
assertThat(kw).isEqualTo(CalendarWeek(53, 2015)) // 2015 has 53 Weeks
}
@Test
fun calendarWeekProperlyCalculated_when_dayAtStartOfYear_and_weekInLastYear_and_52WeeksInLastYear() {
// given
val commitDateTime = OffsetDateTime.of(2017, 1, 3, 12, 0, 0, 0, zoneOffset)
// when
val kw = CalendarWeek.forDateTime(commitDateTime)
// then
assertThat(kw).isEqualTo(CalendarWeek(1, 2017))
}
@Test
fun calendarWeekProperlyCalculated_when_dayAtEndOfYear_and_weekInNextYear() {
// given
val commitDateTime = OffsetDateTime.of(2018, 12, 31, 12, 0, 0, 0, zoneOffset)
// when
val kw = CalendarWeek.forDateTime(commitDateTime)
// then
assertThat(kw).isEqualTo(CalendarWeek(1, 2019))
}
@Test
fun weeksBetweenCommitsProperlyCalculated_when_52WeeksInYears() {
// given
val commitDateTime2 = OffsetDateTime.of(2018, 1, 11, 12, 0, 0, 0, zoneOffset)
val commitDateTime3 = OffsetDateTime.of(2017, 12, 13, 12, 0, 0, 0, zoneOffset)
val kw1 = CalendarWeek.forDateTime(commitDateTime2)
val kw2 = CalendarWeek.forDateTime(commitDateTime3)
// then
assertThat(CalendarWeek.numberOfWeeksBetween(kw2, kw1)).isEqualTo(4)
assertThat(CalendarWeek.numberOfWeeksBetween(kw1, kw2)).isEqualTo(-4)
assertThat(CalendarWeek.numberOfWeeksBetween(kw1, kw1)).isEqualTo(0)
assertThat(CalendarWeek.numberOfWeeksBetween(kw2, kw2)).isEqualTo(0)
}
@Test
fun weeksBetweenCommitsProperlyCalculated_when_firstWeek_and_53WeeksInOldYear() {
// given
val commitDateTime2 = OffsetDateTime.of(2021, 1, 11, 12, 0, 0, 0, zoneOffset)
val commitDateTime3 = OffsetDateTime.of(2020, 12, 13, 12, 0, 0, 0, zoneOffset)
val kw1 = CalendarWeek.forDateTime(commitDateTime2)
val kw2 = CalendarWeek.forDateTime(commitDateTime3)
// then
assertThat(CalendarWeek.numberOfWeeksBetween(kw2, kw1)).isEqualTo(5)
assertThat(CalendarWeek.numberOfWeeksBetween(kw1, kw2)).isEqualTo(-5)
assertThat(CalendarWeek.numberOfWeeksBetween(kw1, kw1)).isEqualTo(0)
assertThat(CalendarWeek.numberOfWeeksBetween(kw2, kw2)).isEqualTo(0)
}
}
| bsd-3-clause | e9ea6ee1e893e14234038ada8805ca72 | 33.978022 | 105 | 0.681433 | 3.891198 | false | true | false | false |
christophpickl/gadsu | src/test/kotlin/at/cpickl/gadsu/testinfra/client.kt | 1 | 1242 | package at.cpickl.gadsu.testinfra
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.client.ClientCategory
import at.cpickl.gadsu.client.ClientDonation
import at.cpickl.gadsu.client.ClientState
import at.cpickl.gadsu.client.Contact
import at.cpickl.gadsu.client.Gender
import at.cpickl.gadsu.client.Relationship
import at.cpickl.gadsu.client.xprops.model.CProps
import at.cpickl.gadsu.image.MyImage
import at.cpickl.gadsu.image.defaultImage
import at.cpickl.gadsu.service.parseDate
import at.cpickl.gadsu.tcm.model.XProps
import org.joda.time.DateTime
@Suppress("UNUSED")
fun Client.Companion.unsavedValidInstance() = Client.INSERT_PROTOTYPE.copy(
created = TEST_DATETIME1,
firstName = "testFirstName",
lastName = "testLastName",
gender = Gender.MALE,
birthday = TEST_DATE_1985,
job = "lazy bastard",
picture = MyImage.DEFAULT_PROFILE_MAN,
countryOfOrigin = "\u00d6sterreich"
)
@Suppress("UNUSED")
fun Client.Companion.savedValidInstance() = unsavedValidInstance().copy(id = TEST_UUID1)
@Suppress("UNUSED")
fun Client.Companion.savedValidInstance2() = unsavedValidInstance().copy(id = TEST_UUID2)
fun Client.copyWithoutCprops() = this.copy(cprops = CProps.empty)
| apache-2.0 | 8d2d90e620a28ea221051bbd99bd348b | 33.5 | 89 | 0.76248 | 3.548571 | false | true | false | false |
AlmasB/GroupNet | src/main/kotlin/icurves/util/DiagramLibrary.kt | 1 | 2439 | package icurves.util
import com.fasterxml.jackson.core.Version
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import icurves.algorithm.DescriptionMatcher
import icurves.diagram.EulerDiagram
import javafx.geometry.Point2D
import javafx.scene.shape.Path
import java.io.File
import java.util.*
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
class DiagramLibrary(val fileName: String) {
companion object {
private val objectMapper = ObjectMapper().registerKotlinModule()
init {
val diagramModule = SimpleModule("PointModule", Version(1, 0, 0, "", "", ""))
diagramModule.addDeserializer(Point2D::class.java, Point2DDeserializer())
diagramModule.addSerializer(Path::class.java, PathSerializer())
diagramModule.addDeserializer(Path::class.java, PathDeserializer())
objectMapper.registerModule(diagramModule)
}
}
// maps normalized informal description -> Euler diagram
private val diagrams: MutableMap<String, EulerDiagram>
init {
val file = File(fileName)
if (file.exists()) {
diagrams = objectMapper.readValue<MutableMap<String, EulerDiagram>>(File(fileName), object : TypeReference<MutableMap<String, EulerDiagram>>() {})
} else {
diagrams = HashMap()
}
}
/**
* @param informalDescription normalized informal description
*/
fun getDiagram(informalDescription: String): EulerDiagram? {
if (diagrams.containsKey(informalDescription))
return diagrams[informalDescription]
diagrams.keys.forEach { pattern ->
val mapping = DescriptionMatcher.match(pattern, informalDescription)
if (mapping.isNotEmpty()) {
println("Pattern match succeeded")
println(mapping)
return diagrams[pattern]!!.copyWithNewLabels(mapping)
}
}
return null
}
/**
* @param informalDescription normalized informal description
*/
fun putDiagram(informalDescription: String, diagram: EulerDiagram) {
diagrams[informalDescription] = diagram
}
fun save() {
objectMapper.writeValue(File(fileName), diagrams)
}
} | apache-2.0 | 849694b0e62c2b67197d483c016f0da2 | 29.886076 | 158 | 0.676097 | 4.735922 | false | false | false | false |
pronghorn-tech/server | src/main/kotlin/tech/pronghorn/util/finder/Equals.kt | 2 | 2445 | /*
* Copyright 2017 Pronghorn Technology LLC
*
* 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 tech.pronghorn.util.finder
import java.nio.ByteBuffer
internal fun isEqual(a1: ByteArray, a2: ByteArray, offset: Int, size: Int): Boolean {
if (a2.size != size) {
return false
}
var x = 0
while (x < size) {
if (a1[offset + x] != a2[x]) {
return false
}
x += 1
}
return true
}
internal fun isEqualStartingAt(a1: ByteArray, a2: ByteArray, startingAt: Int): Boolean {
if (a1.size != a2.size) {
return false
}
var x = 0
while (x < a1.size) {
val index = (startingAt + x) % a1.size
if (a1[index] != a2[index]) {
return false
}
x += 1
}
return true
}
internal fun isEqualStartingAt(arr: ByteArray, buffer: ByteBuffer, offset: Int, size: Int, startingAt: Int): Boolean {
val prePosition = buffer.position()
if (arr.size != size) {
return false
}
buffer.position(offset + startingAt)
var x = startingAt
while (x < size) {
if (buffer.get() != arr[x]) {
buffer.position(prePosition)
return false
}
x += 1
}
x = 0
buffer.position(offset)
while (x < startingAt) {
if (buffer.get() != arr[x]) {
buffer.position(prePosition)
return false
}
x += 1
}
buffer.position(prePosition)
return true
}
internal fun isEqual(arr: ByteArray, buffer: ByteBuffer, offset: Int, size: Int): Boolean {
val prePosition = buffer.position()
if (arr.size != size) {
return false
}
buffer.position(offset)
var x = 0
while (x < size) {
if (buffer.get() != arr[x]) {
buffer.position(prePosition)
return false
}
x += 1
}
buffer.position(prePosition)
return true
}
| apache-2.0 | b975947ecafaf121f4009c9754efd6a9 | 23.45 | 118 | 0.588548 | 3.802488 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/activity/BaseActivity.kt | 1 | 3641 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import fr.cph.chicago.R
import fr.cph.chicago.R.string
import fr.cph.chicago.databinding.LoadingBinding
import fr.cph.chicago.redux.BaseAction
import fr.cph.chicago.redux.DefaultSettingsAction
import fr.cph.chicago.redux.State
import fr.cph.chicago.redux.Status
import fr.cph.chicago.redux.store
import fr.cph.chicago.repository.RealmConfig
import org.rekotlin.StoreSubscriber
import timber.log.Timber
/**
* This class represents the base activity of the application It will load the loading screen and then the main
* activity
*
* @author Carl-Philipp Harmant
* @version 1
*/
class BaseActivity : AppCompatActivity(), StoreSubscriber<State> {
private val realmConfig = RealmConfig
private lateinit var binding: LoadingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!this.isFinishing) {
binding = LoadingBinding.inflate(layoutInflater)
setContentView(R.layout.loading)
store.subscribe(this)
setUpRealm()
binding.included.retryButton.setOnClickListener {
if (binding.included.failureLayout.visibility != View.GONE) binding.included.failureLayout.visibility = View.GONE
if (binding.loadingLayout.visibility != View.VISIBLE) binding.loadingLayout.visibility = View.VISIBLE
store.dispatch(BaseAction())
}
}
}
override fun onResume() {
super.onResume()
val defaultSettingsAction = DefaultSettingsAction(
ctaTrainKey = applicationContext.getString(string.cta_train_key),
ctaBusKey = applicationContext.getString(string.cta_bus_key),
googleStreetKey = applicationContext.getString(string.google_maps_api_key)
)
store.dispatch(defaultSettingsAction)
store.dispatch(BaseAction())
}
private fun setUpRealm() {
realmConfig.setUpRealm()
}
override fun newState(state: State) {
when (state.status) {
Status.SUCCESS -> {
store.unsubscribe(this)
startMainActivity()
}
Status.FAILURE -> {
store.unsubscribe(this)
startMainActivity()
}
Status.FULL_FAILURE -> {
if (binding.included.failureLayout.visibility != View.VISIBLE) binding.included.failureLayout.visibility = View.VISIBLE
if (binding.loadingLayout.visibility != View.GONE) binding.loadingLayout.visibility = View.GONE
}
else -> Timber.d("Unknown status on new state")
}
}
private fun startMainActivity() {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
finish()
}
}
| apache-2.0 | 283a5a36fddab44c7142ace78b3c52bd | 34.009615 | 135 | 0.680308 | 4.528607 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/location/LocationReportingService.kt | 1 | 5591 | package mil.nga.giat.mage.location
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.location.Location
import android.location.LocationManager
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import mil.nga.giat.mage.MageApplication
import mil.nga.giat.mage.R
import mil.nga.giat.mage.data.location.LocationRepository
import mil.nga.giat.mage.login.LoginActivity
import javax.inject.Inject
@AndroidEntryPoint
open class LocationReportingService : LifecycleService(), Observer<Location>, SharedPreferences.OnSharedPreferenceChangeListener {
@Inject lateinit var locationProvider: LocationProvider
@Inject lateinit var locationRepository: LocationRepository
@Inject lateinit var locationAccess: LocationAccess
@Inject lateinit var preferences: SharedPreferences
private var shouldReportLocation: Boolean = false
private var locationPushFrequency: Long = 0
private var oldestLocationTime: Long = 0
companion object {
private val LOG_NAME = LocationReportingService::class.java.name
const val NOTIFICATION_ID = 500
const val NOTIFICATION_CHANNEL_ID = "mil.nga.mage.LOCATION_NOTIFICATION_CHANNEL"
}
override fun onCreate() {
super.onCreate()
// If the user disables the location permission from settings, MAGE will be restarted, including this service (Service.START_STICKY)
// Check for location permission here as it may have been disabled, if so stop the service.
if (locationAccess.isLocationDenied()) {
stopForeground(true)
return
}
preferences.registerOnSharedPreferenceChangeListener(this)
locationPushFrequency = getLocationPushFrequency()
shouldReportLocation = getShouldReportLocation()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "MAGE", NotificationManager.IMPORTANCE_MIN)
channel.setShowBadge(true)
notificationManager.createNotificationChannel(channel)
}
val intent = Intent(applicationContext, LoginActivity::class.java)
intent.putExtra("LOGOUT", true)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val pendingIntent = PendingIntent.getActivity(applicationContext, 1, intent, PendingIntent.FLAG_IMMUTABLE)
val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle("MAGE Location Service")
.setContentText("MAGE is currently reporting your location.")
.setSmallIcon(R.drawable.ic_place_white_24dp)
.setGroup(MageApplication.MAGE_NOTIFICATION_GROUP)
.addAction(R.drawable.ic_power_settings_new_white_24dp, "Logout", pendingIntent)
.build()
startForeground(NOTIFICATION_ID, notification)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
locationProvider.observe(this, this)
return Service.START_STICKY
}
override fun onDestroy() {
super.onDestroy()
locationProvider.removeObserver(this)
preferences.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onChanged(location: Location?) {
if (shouldReportLocation && location?.provider == LocationManager.GPS_PROVIDER) {
Log.v(LOG_NAME, "GPS location changed")
lifecycleScope.launch {
locationRepository.saveLocation(location)
if (oldestLocationTime == 0L) {
oldestLocationTime = location.time
}
if (!locationAccess.isPreciseLocationGranted() || (location.time - oldestLocationTime > locationPushFrequency)) {
val success = locationRepository.pushLocations()
if (success) {
oldestLocationTime = 0
}
}
}
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key.equals(getString(R.string.reportLocationKey), ignoreCase = true)) {
shouldReportLocation = getShouldReportLocation()
Log.d(LOG_NAME, "Report location changed $shouldReportLocation")
} else if (key.equals(getString(R.string.locationPushFrequencyKey), ignoreCase = true)) {
locationPushFrequency = getLocationPushFrequency()
Log.d(LOG_NAME, "Location push frequency changed $locationPushFrequency")
}
}
private fun getLocationPushFrequency(): Long {
return preferences.getInt(getString(R.string.locationPushFrequencyKey), resources.getInteger(R.integer.locationPushFrequencyDefaultValue)).toLong()
}
private fun getShouldReportLocation(): Boolean {
return preferences.getBoolean(getString(R.string.reportLocationKey), resources.getBoolean(R.bool.reportLocationDefaultValue))
}
}
| apache-2.0 | 88cae366ef12896593d303cc751e49c7 | 39.810219 | 155 | 0.712931 | 5.101277 | false | false | false | false |
world-federation-of-advertisers/common-jvm | src/main/kotlin/org/wfanet/measurement/common/ProtoUtils.kt | 1 | 4679 | // Copyright 2020 The Cross-Media Measurement Authors
//
// 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.wfanet.measurement.common
import com.google.protobuf.ByteString
import com.google.protobuf.Descriptors.FieldDescriptor
import com.google.protobuf.Duration as ProtoDuration
import com.google.protobuf.Message
import com.google.protobuf.MessageOrBuilder
import com.google.protobuf.ProtocolMessageEnum
import com.google.protobuf.TextFormat
import com.google.protobuf.Timestamp
import com.google.protobuf.TypeRegistry
import com.google.protobuf.duration
import com.google.protobuf.timestamp
import com.google.protobuf.util.JsonFormat
import java.io.File
import java.time.Clock
import java.time.Duration
import java.time.Instant
/** Converts a protobuf [MessageOrBuilder] into its canonical JSON representation. */
fun MessageOrBuilder.toJson(): String {
return JsonFormat.printer().omittingInsignificantWhitespace().print(this)
}
/**
* Truncates all of the [bytes][FieldDescriptor.Type.BYTES] fields in this [Message.Builder]
* in-place, returning itself for chaining.
*
* @param truncatedSize the size in bytes to truncate to
*/
fun <T : Message.Builder> T.truncateByteFields(truncatedSize: Int): T {
descriptors@ for (descriptor in descriptorForType.fields) {
when (descriptor.type) {
FieldDescriptor.Type.BYTES -> {
if (descriptor.isRepeated) {
val fields = getField(descriptor) as List<*>
fields.forEachIndexed { index, value ->
val bytes = value as ByteString
if (bytes.size() > truncatedSize) {
setRepeatedField(descriptor, index, bytes.substring(0, truncatedSize))
}
}
} else {
val bytes = getField(descriptor) as ByteString
if (bytes.size() > truncatedSize) {
setField(descriptor, bytes.substring(0, truncatedSize))
}
}
}
FieldDescriptor.Type.MESSAGE -> {
if (descriptor.isRepeated) {
val fields = getField(descriptor) as List<*>
fields.forEachIndexed { index, field ->
val message = field as Message
setRepeatedField(descriptor, index, message.truncateByteFields(truncatedSize))
}
} else {
if (!hasField(descriptor)) {
// Skip unset fields. This also avoids clobbering oneofs.
continue@descriptors
}
val message = getField(descriptor) as Message
setField(descriptor, message.truncateByteFields(truncatedSize))
}
}
else -> {} // No-op.
}
}
return this
}
/** Truncate all byte fields inside a protobuf [Message]. */
fun <T : Message> T.truncateByteFields(truncatedSize: Int): T {
@Suppress("UNCHECKED_CAST") // Safe due to Message contract.
return toBuilder().truncateByteFields(truncatedSize).build() as T
}
fun Instant.toProtoTime(): Timestamp = timestamp {
seconds = epochSecond
nanos = nano
}
fun Timestamp.toInstant(): Instant = Instant.ofEpochSecond(seconds, nanos.toLong())
fun Duration.toProtoDuration(): ProtoDuration = duration {
seconds = seconds
nanos = nanos
}
fun ProtoDuration.toDuration(): Duration = Duration.ofSeconds(seconds, nanos.toLong())
fun Clock.protoTimestamp(): Timestamp = instant().toProtoTime()
val ProtocolMessageEnum.numberAsLong: Long
get() = number.toLong()
fun Message.Builder.mergeFromTextProto(textProto: Readable, typeRegistry: TypeRegistry) {
TextFormat.Parser.newBuilder().setTypeRegistry(typeRegistry).build().merge(textProto, this)
}
@Suppress("UNCHECKED_CAST") // Safe per Message contract.
fun <T : Message> parseTextProto(
textProto: Readable,
messageInstance: T,
typeRegistry: TypeRegistry = TypeRegistry.getEmptyTypeRegistry()
): T {
return messageInstance
.newBuilderForType()
.apply { mergeFromTextProto(textProto, typeRegistry) }
.build() as T
}
fun <T : Message> parseTextProto(
textProto: File,
messageInstance: T,
typeRegistry: TypeRegistry = TypeRegistry.getEmptyTypeRegistry()
): T {
return textProto.bufferedReader().use { reader ->
parseTextProto(reader, messageInstance, typeRegistry)
}
}
| apache-2.0 | 98204f83a5e817bc14d65c67a2198afb | 33.153285 | 93 | 0.712118 | 4.292661 | false | false | false | false |
lttng/lttng-scope | jabberwocky-core/src/main/kotlin/com/efficios/jabberwocky/trace/event/BaseTraceEvent.kt | 2 | 2016 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.trace.event
import com.efficios.jabberwocky.trace.Trace
import com.google.common.base.MoreObjects
import com.google.common.collect.ImmutableMap
import java.text.NumberFormat
import java.util.*
open class BaseTraceEvent(@Transient override val trace: Trace<TraceEvent>,
final override val timestamp: Long,
final override val cpu: Int,
final override val eventName: String,
final override val fields: Map<String, FieldValue>,
attributes: Map<String, String>? = null) : TraceEvent {
final override val attributes: Map<String, String> = attributes ?: Collections.emptyMap()
override fun hashCode() = Objects.hash(timestamp, cpu, eventName, fields, attributes)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as BaseTraceEvent
if (timestamp != other.timestamp) return false
if (cpu != other.cpu) return false
if (eventName != other.eventName) return false
if (fields != other.fields) return false
if (attributes != other.attributes) return false
return true
}
override fun toString(): String {
return MoreObjects.toStringHelper(this)
.add("timestamp", NumberFormat.getInstance().format(timestamp)) //$NON-NLS-1$
.add("event name", eventName) //$NON-NLS-1$
.add("cpu", cpu) //$NON-NLS-1$
.add("fields", fields) //$NON-NLS-1$
.toString()
}
}
| epl-1.0 | 1e01e04afa75684196c306f9890b1b30 | 37.037736 | 93 | 0.638889 | 4.634483 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-material/src/main/java/reactivecircus/flowbinding/material/NavigationViewItemSelectedFlow.kt | 1 | 1762 | package reactivecircus.flowbinding.material
import android.view.MenuItem
import androidx.annotation.CheckResult
import com.google.android.material.navigation.NavigationView
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.onStart
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [Flow] of item selected events on the [NavigationView] instance
* where the value emitted is the currently selected menu item.
*
* Note: if a [MenuItem] is already selected, it will be emitted immediately upon collection.
*
* Note: Created flow keeps a strong reference to the [NavigationView] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* navigationView.itemSelections()
* .onEach { menuItem ->
* // handle menuItem
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun NavigationView.itemSelections(): Flow<MenuItem> = callbackFlow {
checkMainThread()
val listener = NavigationView.OnNavigationItemSelectedListener { item ->
trySend(item)
true
}
setNavigationItemSelectedListener(listener)
awaitClose { setNavigationItemSelectedListener(null) }
}
.onStart {
var selectedItem: MenuItem? = null
for (index in 0 until menu.size()) {
val item = menu.getItem(index)
if (item.isChecked) {
selectedItem = item
break
}
}
selectedItem?.run { emit(this) }
}
.conflate()
| apache-2.0 | be80a8e8a9119c9dc25f5fd7dcc8f125 | 31.036364 | 93 | 0.710556 | 4.80109 | false | false | false | false |
spark/photon-tinker-android | app/src/main/java/io/particle/android/sdk/tinker/TinkerApplication.kt | 1 | 2726 | package io.particle.android.sdk.tinker
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.android.sdk.devicesetup.BuildConfig
import io.particle.android.sdk.devicesetup.ParticleDeviceSetupLibrary
import io.particle.android.sdk.onApplicationCreated
import io.particle.android.sdk.ui.devicelist.DeviceListActivity
import io.particle.android.sdk.utils.logging.FileLogging
import io.particle.mesh.common.QATool
import io.particle.mesh.setup.flow.Scopes
import mu.KotlinLogging
class TinkerApplication : Application() {
val fileLogging = FileLogging(this)
private val log = KotlinLogging.logger {}
override fun onCreate() {
super.onCreate()
QATool.isDebugBuild = BuildConfig.DEBUG
// HI THERE: doing a release build? Read the rest of this comment. (Otherwise, carry on.)
//
// ReleaseBuildAppInitializer is a per-build type file, intended to avoid initializing
// things like analytics when doing debug builds (i.e.: what most people will be doing when
// they download the app via GitHub.)
//
// If you do a release build of an app based on this code, you'll need to manually comment
// out this line by hand or otherwise prevent calling the code
// inside ReleaseBuildAppInitializer
onApplicationCreated(this)
fileLogging.initLogging(Scopes())
ParticleDeviceSetupLibrary.init(this, DeviceListActivity::class.java)
log.info { "Device make and model=${getDeviceNameAndMfg()},\n" +
"OS version=${Build.VERSION.RELEASE},\n" +
"App version=$appVersionName,"
}
// Use `Log` class to only log this to the system log, and not the separate logs we store
// on disk for export on user request
val last4 = ParticleCloudSDK.getCloud().accessToken?.takeLast(4) ?: "No token stored yet!"
Log.i("ParticleAuth", "Last 4 digits of auth token: $last4")
}
}
private fun getDeviceNameAndMfg(): String {
val manufacturer = Build.MANUFACTURER
val model = Build.MODEL
return if (model.toLowerCase().startsWith(manufacturer.toLowerCase())) {
model.capitalize()
} else manufacturer.capitalize() + " " + model
}
private val Context.appVersionName: String
get() {
return try {
val pInfo = packageManager.getPackageInfo(packageName, 0)
pInfo.versionName
} catch (e: PackageManager.NameNotFoundException) {
QATool.report(e)
"(Error getting version)"
}
} | apache-2.0 | cfcdc61053b5fa5a373c82e4492cc9d0 | 33.961538 | 99 | 0.694424 | 4.446982 | false | false | false | false |
7hens/KDroid | sample/src/main/java/cn/thens/kdroid/sample/common/util/Dates.kt | 1 | 3417 | package cn.thens.kdroid.sample.common.util
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
object Dates {
private val PATTERN_DEFAULT = "yyyy-MM-dd HH:mm:ss"
val dayOfWeekInChinese: String get() = getDayOfWeekInChinese(System.currentTimeMillis())
val dayOfWeek: Int get() = getDayOfWeek(System.currentTimeMillis())
@JvmOverloads fun from(text: String, pattern: String = PATTERN_DEFAULT): Date? {
val format = SimpleDateFormat(pattern, Locale.CHINA)
var date: Date? = null
try {
date = format.parse(text)
} catch (e: ParseException) {
e.printStackTrace()
}
return date
}
fun from(): Date {
return Date()
}
@JvmOverloads fun format(pattern: String, date: Date = Date()): String {
val formatter = SimpleDateFormat(pattern, Locale.CHINA)
return formatter.format(date)
}
fun format(pattern: String, time: Long): String {
return format(pattern, Date(time))
}
@JvmOverloads fun format(date: Date = Date()): String {
return format(PATTERN_DEFAULT, date)
}
fun format(time: Long): String {
return format(PATTERN_DEFAULT, time)
}
fun calendar(): Calendar {
return Calendar.getInstance()
}
fun calendar(date: Date): Calendar {
val calendar = calendar()
calendar.time = date
return calendar
}
fun calendar(time: Long): Calendar {
val calendar = calendar()
calendar.timeInMillis = time
return calendar
}
fun smartTimer(calendar: Calendar): String {
calendar.timeZone = TimeZone.getTimeZone("Etc/Greenwich")
val day = TimeUnit.MILLISECONDS.toDays(calendar.timeInMillis)
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val second = calendar.get(Calendar.SECOND)
val buffer = StringBuilder()
if (day > 0) buffer.append(day).append("天")
if (hour > 0) buffer.append(hour).append("时")
if (minute > 0) buffer.append(minute).append("分")
if (second > 0) buffer.append(second).append("秒")
return buffer.toString()
}
fun smartTimer(date: Date): String {
return smartTimer(calendar(date))
}
fun smartTimer(time: Long): String {
return smartTimer(calendar(time))
}
fun convertDayOfWeekToChinese(dayOfWeek: Int): String {
when (dayOfWeek) {
Calendar.SUNDAY -> return "周日"
Calendar.MONDAY -> return "周一"
Calendar.TUESDAY -> return "周二"
Calendar.WEDNESDAY -> return "周三"
Calendar.THURSDAY -> return "周四"
Calendar.FRIDAY -> return "周五"
Calendar.SATURDAY -> return "周六"
}
return ""
}
fun getDayOfWeekInChinese(timeMillis: Long): String {
return convertDayOfWeekToChinese(getDayOfWeek(timeMillis))
}
fun getDayOfWeek(timeMills: Long): Int {
val calendar = Calendar.getInstance()
calendar.timeInMillis = timeMills
return calendar.get(Calendar.DAY_OF_WEEK)
}
fun isToday(timeMillis: Long): Boolean {
return TimeUnit.MILLISECONDS.toDays(timeMillis) == TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis())
}
}
| apache-2.0 | dae127e6ded547b9c9d95a0702cd63bb | 29.459459 | 115 | 0.627033 | 4.351351 | false | false | false | false |
facebook/litho | litho-core-kotlin/src/test/kotlin/com/facebook/litho/KStateSkipSameValueTest.kt | 1 | 16653 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.testing.LithoViewRule
import com.facebook.litho.testing.assertj.LithoViewAssert
import com.facebook.litho.testing.testrunner.LithoTestRunner
import com.facebook.litho.view.onClick
import com.facebook.litho.view.viewTag
import java.util.concurrent.atomic.AtomicInteger
import org.assertj.core.api.Assertions
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowLooper
/** Unit tests for skipping state updates if value won't change. */
@LooperMode(LooperMode.Mode.LEGACY)
@RunWith(LithoTestRunner::class)
class KStateSkipSameValueTest {
@Rule @JvmField val lithoViewRule = LithoViewRule()
@Test
fun `skip state update if new value is the same as old value during layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
// unconditional state update
state.updateSync(true)
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip state update if nullable new value is the same as old value during layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
val stateSampleString: String? = "sample string"
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { stateSampleString }
// unconditional state update
state.updateSync(null)
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip state update if new value object is the same as old value during layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { Person("Joe") }
// unconditional state update
state.updateSync(Person("Joe"))
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip async state update if new value is the same as old value`() {
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
// unconditional state update
state.update(true)
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
lithoViewRule.idle()
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip async state update if nullable new value is the same as old value`() {
val renderCount = AtomicInteger()
val stateSampleString: String? = "sample string"
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { stateSampleString }
// unconditional state update
state.update(null)
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
lithoViewRule.idle()
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip async state update if new value object reference is the same as old value`() {
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { Person("Joe") }
// unconditional state update
state.update(Person("Joe"))
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
lithoViewRule.idle()
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip sync state update triggered from outside layout if value is same`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
val listeners = mutableListOf<Listener>()
class RootComponent : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
val listener1 =
useCached(state) {
object : Listener {
override fun onTriggerListener() {
state.updateSync(true)
}
}
}
useEffect(listener1) {
listeners.add(listener1)
onCleanup { listeners.remove(listener1) }
}
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent() }
for (i in 0..10) {
for (listener in listeners) {
listener.onTriggerListener()
}
}
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `do not skip state update if new updates were enqueued during layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
// unconditional state update
if (renderCount.get() == 1) {
state.updateSync(true)
state.updateSync(false)
}
return Row { child(Text(text = "State is ${state.value}")) }
}
}
val lithoView = lithoViewRule.render { RootComponent(renderCount = renderCount) }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
LithoViewAssert.assertThat(lithoView.lithoView).hasVisibleText("State is false")
}
@Test
fun `do not skip state update if new updates were enqueued outside layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
return Row(
style =
Style.viewTag("clickTag").onClick {
state.updateSync(true)
state.updateSync(false)
}) {
child(Text(text = "State is ${state.value}"))
}
}
}
val lithoView = lithoViewRule.render { RootComponent(renderCount = renderCount) }
lithoViewRule.act(lithoView) { clickOnTag("clickTag") }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
LithoViewAssert.assertThat(lithoView.lithoView).hasVisibleText("State is false")
}
// Same tests as above but with lambda state updates.
@Test
fun `skip lambda state update if new value is the same as old value during layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
// unconditional state update
state.updateSync { true }
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip lambda state update if new nullable value is the same as old value during layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
val stateSampleString: String? = "sample string"
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { stateSampleString }
// unconditional state update
state.updateSync { null }
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip lambda state update if new object is the same as old value during layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { Person("Joe") }
// unconditional state update
state.updateSync { Person("Joe") }
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip lambda async state update if new value is the same as old value`() {
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
// unconditional state update
state.update { true }
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
lithoViewRule.idle()
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip lambda async state update if new nullable value is the same as old value`() {
val renderCount = AtomicInteger()
val stateSampleString: String? = "sample string"
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { stateSampleString }
// unconditional state update
state.update { null }
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
lithoViewRule.idle()
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip lambda async state update if new object value is the same as old value`() {
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { Person("Joe") }
// unconditional state update
state.update { Person("Joe") }
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent(renderCount = renderCount) }
lithoViewRule.idle()
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `skip lambda sync state update triggered from outside layout if value is same`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
val listeners = mutableListOf<Listener>()
class RootComponent : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
val listener1 =
useCached(state) {
object : Listener {
override fun onTriggerListener() {
state.updateSync { true }
}
}
}
useEffect(listener1) {
listeners.add(listener1)
onCleanup { listeners.remove(listener1) }
}
return Row { child(Text(text = "hello world")) }
}
}
lithoViewRule.render { RootComponent() }
for (i in 0..10) {
for (listener in listeners) {
listener.onTriggerListener()
}
}
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
Assertions.assertThat(renderCount.get()).isEqualTo(2)
}
@Test
fun `do not skip lambda state update if new updates were enqueued during layout`() {
ShadowLooper.pauseMainLooper()
val renderCount = AtomicInteger()
class RootComponent(private val renderCount: AtomicInteger) : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val state = useState { false }
// unconditional state update
if (renderCount.get() == 1) {
state.updateSync { currentVal -> !currentVal }
state.updateSync { currentVal -> !currentVal }
}
return Row { child(Text(text = "State is ${state.value}")) }
}
}
val lithoView = lithoViewRule.render { RootComponent(renderCount = renderCount) }
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
LithoViewAssert.assertThat(lithoView.lithoView).hasVisibleText("State is false")
}
@Test
fun `do not skip lambda state update if new updates were enqueued outside layout`() {
ShadowLooper.pauseMainLooper()
class RootComponent : KComponent() {
override fun ComponentScope.render(): Component {
val state = useState { false }
return Row(
style =
Style.viewTag("clickTag").onClick {
state.updateSync { currentState -> !currentState }
state.updateSync { currentState -> !currentState }
}) {
child(Text(text = "State is ${state.value}"))
}
}
}
val lithoView = lithoViewRule.render { RootComponent() }
lithoViewRule.act(lithoView) {
clickOnTag("clickTag")
/**
* We need to perform this assertion here because as soon as we exit this lambda, all pending
* runnables enqueued on the UI or BG thread will be executed.
*/
Assertions.assertThat(
lithoView.componentTree.treeState?.getRenderStateHandler()?.pendingHookUpdatesCount)
.isEqualTo(2)
}
for (i in 0..10) {
ShadowLooper.runMainLooperOneTask()
}
LithoViewAssert.assertThat(lithoView.lithoView).hasVisibleText("State is false")
}
private interface Listener {
fun onTriggerListener()
}
class Person(var name: String) {
override fun equals(that: Any?): Boolean {
if (that == null) return false
if (that !is Person) return false
return this.name == that.name
}
override fun hashCode(): Int {
return name.hashCode()
}
}
}
| apache-2.0 | f4f53a62e7d4aba8dd21df9b95e9f45e | 28.684492 | 99 | 0.652795 | 4.613019 | false | false | false | false |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/browser/history/Adapter.kt | 1 | 4263 | package jp.toastkid.yobidashi.browser.history
import android.content.Context
import android.net.Uri
import android.text.format.DateFormat
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.yobidashi.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* View history activity's adapter.
*
* @param context
* @param viewHistoryRepository
* @param onClick
* @param onDelete
*
* @author toastkidjp
*/
internal class Adapter(
private val context: Context,
private val viewHistoryRepository: ViewHistoryRepository,
private val onClick: (ViewHistory) -> Unit,
private val onDelete: (ViewHistory) -> Unit
) : RecyclerView.Adapter<ViewHolder>() {
/**
* Layout inflater.
*/
private val inflater: LayoutInflater = LayoutInflater.from(context)
private val items = mutableListOf<ViewHistory>()
private val parent = Job()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(DataBindingUtil.inflate(inflater, ITEM_LAYOUT_ID, parent, false))
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val viewHistory: ViewHistory = items[position]
holder.setText(
viewHistory.title,
viewHistory.url,
DateFormat.format(context.getString(R.string.date_format), viewHistory.lastViewed).toString()
)
holder.itemView.setOnClickListener { onClick(viewHistory) }
holder.setOnClickAdd(viewHistory) { history ->
remove(viewHistory)
onDelete.invoke(history)
}
holder.setOnClickBookmark(viewHistory)
holder.setImage(viewHistory.favicon)
val browserViewModel = (holder.itemView.context as? FragmentActivity)?.let {
ViewModelProvider(it).get(BrowserViewModel::class.java)
}
holder.itemView.setOnLongClickListener {
browserViewModel?.openBackground(viewHistory.title, Uri.parse(viewHistory.url))
true
}
holder.hideButton()
}
override fun getItemCount(): Int = items.size
fun filter(query: String?) {
if (query.isNullOrBlank()) {
refresh()
return
}
items.clear()
CoroutineScope(Dispatchers.Main).launch(parent) {
withContext(Dispatchers.IO) {
items.addAll(viewHistoryRepository.search("%$query%"))
}
notifyDataSetChanged()
}
}
fun refresh(onComplete: () -> Unit = {}) {
items.clear()
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) { items.addAll(viewHistoryRepository.reversed()) }
notifyDataSetChanged()
onComplete()
}
}
/**
* Remove item with position.
*
* @param position
*/
fun removeAt(position: Int) {
remove(items[position], position)
}
private fun remove(item: ViewHistory, position: Int = -1) {
CoroutineScope(Dispatchers.Main).launch {
val index = if (position == -1) items.indexOf(item) else position
withContext(Dispatchers.IO) {
viewHistoryRepository.delete(item)
items.remove(item)
}
notifyItemRemoved(index)
}
}
/**
* Clear all item.
*
* @param onComplete
*/
fun clearAll(onComplete: () -> Unit) {
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) {
viewHistoryRepository.deleteAll()
}
onComplete()
notifyDataSetChanged()
}
}
fun dispose() {
parent.cancel()
}
companion object {
@LayoutRes
private val ITEM_LAYOUT_ID = R.layout.item_view_history
}
}
| epl-1.0 | d0a8bb543ebc01ba90ab5895a38131fa | 26.326923 | 105 | 0.641802 | 5.009401 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2020/Day12.kt | 1 | 1503 | package com.s13g.aoc.aoc2020
import com.s13g.aoc.*
/**
* --- Day 12: Rain Risk ---
* https://adventofcode.com/2020/day/12
*/
class Day12 : Solver {
private val dirVec = hashMapOf('N' to XY(0, 1), 'S' to XY(0, -1), 'W' to XY(-1, 0), 'E' to XY(1, 0))
private var dirs = listOf('N', 'E', 'S', 'W')
override fun solve(lines: List<String>): Result {
val input = lines.map { Pair(it[0], it.substring(1).toInt()) }
return Result("${partA(input).manhattan()}", "${partB(input).manhattan()}")
}
private fun partA(input: List<Pair<Char, Int>>): XY {
val pos = XY(0, 0)
var facing = 'E'
for (foo in input) {
when (foo.first) {
in dirVec -> for (n in 0 until foo.second) pos.addTo(dirVec[foo.first]!!)
'F' -> for (n in 0 until foo.second) pos.addTo(dirVec[facing]!!)
'L' -> facing = dirs[(dirs.indexOf(facing) - (foo.second / 90) + 360) % dirs.size]
'R' -> facing = dirs[(dirs.indexOf(facing) + (foo.second / 90)) % dirs.size]
}
}
return pos
}
private fun partB(input: List<Pair<Char, Int>>): XY {
val pos = XY(0, 0)
var waypoint = XY(10, 1)
for (foo in input) {
when (foo.first) {
in dirVec -> for (n in 0 until foo.second) waypoint.addTo(dirVec[foo.first]!!)
'F' -> for (n in 0 until foo.second) pos.addTo(waypoint)
'L' -> waypoint = waypoint.rotate90(foo.second / 90, true)
'R' -> waypoint = waypoint.rotate90(foo.second / 90, false)
}
}
return pos
}
}
| apache-2.0 | 6eb93433695b8e6d5f90398cb464ead2 | 33.159091 | 102 | 0.568862 | 2.994024 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBackupController.kt | 1 | 12659 | package eu.kanade.tachiyomi.ui.setting
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.app.Activity
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.core.os.bundleOf
import androidx.preference.PreferenceScreen
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.hippo.unifile.UniFile
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.backup.BackupConst
import eu.kanade.tachiyomi.data.backup.BackupCreateService
import eu.kanade.tachiyomi.data.backup.BackupCreatorJob
import eu.kanade.tachiyomi.data.backup.BackupRestoreService
import eu.kanade.tachiyomi.data.backup.full.FullBackupRestoreValidator
import eu.kanade.tachiyomi.data.backup.full.models.BackupFull
import eu.kanade.tachiyomi.data.backup.legacy.LegacyBackupRestoreValidator
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.ui.base.controller.requestPermissionsSafe
import eu.kanade.tachiyomi.util.preference.bindTo
import eu.kanade.tachiyomi.util.preference.entriesRes
import eu.kanade.tachiyomi.util.preference.infoPreference
import eu.kanade.tachiyomi.util.preference.intListPreference
import eu.kanade.tachiyomi.util.preference.onChange
import eu.kanade.tachiyomi.util.preference.onClick
import eu.kanade.tachiyomi.util.preference.preference
import eu.kanade.tachiyomi.util.preference.preferenceCategory
import eu.kanade.tachiyomi.util.preference.summaryRes
import eu.kanade.tachiyomi.util.preference.titleRes
import eu.kanade.tachiyomi.util.system.DeviceUtil
import eu.kanade.tachiyomi.util.system.toast
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class SettingsBackupController : SettingsController() {
/**
* Flags containing information of what to backup.
*/
private var backupFlags = 0
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
requestPermissionsSafe(arrayOf(WRITE_EXTERNAL_STORAGE), 500)
}
override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply {
titleRes = R.string.label_backup
preference {
key = "pref_create_backup"
titleRes = R.string.pref_create_backup
summaryRes = R.string.pref_create_backup_summ
onClick {
if (DeviceUtil.isMiui && DeviceUtil.isMiuiOptimizationDisabled()) {
context.toast(R.string.restore_miui_warning, Toast.LENGTH_LONG)
}
if (!BackupCreateService.isRunning(context)) {
val ctrl = CreateBackupDialog()
ctrl.targetController = this@SettingsBackupController
ctrl.showDialog(router)
} else {
context.toast(R.string.backup_in_progress)
}
}
}
preference {
key = "pref_restore_backup"
titleRes = R.string.pref_restore_backup
summaryRes = R.string.pref_restore_backup_summ
onClick {
if (DeviceUtil.isMiui && DeviceUtil.isMiuiOptimizationDisabled()) {
context.toast(R.string.restore_miui_warning, Toast.LENGTH_LONG)
}
if (!BackupRestoreService.isRunning(context)) {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
}
val title = resources?.getString(R.string.file_select_backup)
val chooser = Intent.createChooser(intent, title)
startActivityForResult(chooser, CODE_BACKUP_RESTORE)
} else {
context.toast(R.string.restore_in_progress)
}
}
}
preferenceCategory {
titleRes = R.string.pref_backup_service_category
intListPreference {
bindTo(preferences.backupInterval())
titleRes = R.string.pref_backup_interval
entriesRes = arrayOf(
R.string.update_never,
R.string.update_6hour,
R.string.update_12hour,
R.string.update_24hour,
R.string.update_48hour,
R.string.update_weekly
)
entryValues = arrayOf("0", "6", "12", "24", "48", "168")
summary = "%s"
onChange { newValue ->
val interval = (newValue as String).toInt()
BackupCreatorJob.setupTask(context, interval)
true
}
}
preference {
bindTo(preferences.backupsDirectory())
titleRes = R.string.pref_backup_directory
onClick {
try {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
startActivityForResult(intent, CODE_BACKUP_DIR)
} catch (e: ActivityNotFoundException) {
activity?.toast(R.string.file_picker_error)
}
}
visibleIf(preferences.backupInterval()) { it > 0 }
preferences.backupsDirectory().asFlow()
.onEach { path ->
val dir = UniFile.fromUri(context, path.toUri())
summary = dir.filePath + "/automatic"
}
.launchIn(viewScope)
}
intListPreference {
bindTo(preferences.numberOfBackups())
titleRes = R.string.pref_backup_slots
entries = arrayOf("1", "2", "3", "4", "5")
entryValues = entries
summary = "%s"
visibleIf(preferences.backupInterval()) { it > 0 }
}
}
infoPreference(R.string.backup_info)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (data != null && resultCode == Activity.RESULT_OK) {
val activity = activity ?: return
val uri = data.data
when (requestCode) {
CODE_BACKUP_DIR -> {
// Get UriPermission so it's possible to write files
val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
if (uri != null) {
activity.contentResolver.takePersistableUriPermission(uri, flags)
}
// Set backup Uri
preferences.backupsDirectory().set(uri.toString())
}
CODE_BACKUP_CREATE -> {
val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
if (uri != null) {
activity.contentResolver.takePersistableUriPermission(uri, flags)
}
val file = UniFile.fromUri(activity, uri)
activity.toast(R.string.creating_backup)
BackupCreateService.start(
activity,
file.uri,
backupFlags,
)
}
CODE_BACKUP_RESTORE -> {
uri?.let { RestoreBackupDialog(it).showDialog(router) }
}
}
}
}
fun createBackup(flags: Int) {
backupFlags = flags
try {
// Use Android's built-in file creator
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE)
.setType("application/*")
.putExtra(Intent.EXTRA_TITLE, BackupFull.getDefaultFilename())
startActivityForResult(intent, CODE_BACKUP_CREATE)
} catch (e: ActivityNotFoundException) {
activity?.toast(R.string.file_picker_error)
}
}
class CreateBackupDialog(bundle: Bundle? = null) : DialogController(bundle) {
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
val activity = activity!!
val options = arrayOf(
R.string.manga,
R.string.categories,
R.string.chapters,
R.string.track,
R.string.history
)
.map { activity.getString(it) }
val selected = options.map { true }.toBooleanArray()
return MaterialAlertDialogBuilder(activity)
.setTitle(R.string.backup_choice)
.setMultiChoiceItems(options.toTypedArray(), selected) { dialog, which, checked ->
if (which == 0) {
(dialog as AlertDialog).listView.setItemChecked(which, true)
} else {
selected[which] = checked
}
}
.setPositiveButton(R.string.action_create) { _, _ ->
var flags = 0
selected.forEachIndexed { i, checked ->
if (checked) {
when (i) {
1 -> flags = flags or BackupCreateService.BACKUP_CATEGORY
2 -> flags = flags or BackupCreateService.BACKUP_CHAPTER
3 -> flags = flags or BackupCreateService.BACKUP_TRACK
4 -> flags = flags or BackupCreateService.BACKUP_HISTORY
}
}
}
(targetController as? SettingsBackupController)?.createBackup(flags)
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
}
class RestoreBackupDialog(bundle: Bundle? = null) : DialogController(bundle) {
constructor(uri: Uri) : this(
bundleOf(KEY_URI to uri)
)
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
val activity = activity!!
val uri: Uri = args.getParcelable(KEY_URI)!!
return try {
var type = BackupConst.BACKUP_TYPE_FULL
val results = runCatching {
FullBackupRestoreValidator().validate(activity, uri)
}.recoverCatching {
type = BackupConst.BACKUP_TYPE_LEGACY
LegacyBackupRestoreValidator().validate(activity, uri)
}.getOrThrow()
var message = if (type == BackupConst.BACKUP_TYPE_FULL) {
activity.getString(R.string.backup_restore_content_full)
} else {
activity.getString(R.string.backup_restore_content)
}
if (results.missingSources.isNotEmpty()) {
message += "\n\n${activity.getString(R.string.backup_restore_missing_sources)}\n${results.missingSources.joinToString("\n") { "- $it" }}"
}
if (results.missingTrackers.isNotEmpty()) {
message += "\n\n${activity.getString(R.string.backup_restore_missing_trackers)}\n${results.missingTrackers.joinToString("\n") { "- $it" }}"
}
MaterialAlertDialogBuilder(activity)
.setTitle(R.string.pref_restore_backup)
.setMessage(message)
.setPositiveButton(R.string.action_restore) { _, _ ->
BackupRestoreService.start(activity, uri, type)
}
.create()
} catch (e: Exception) {
MaterialAlertDialogBuilder(activity)
.setTitle(R.string.invalid_backup_file)
.setMessage(e.message)
.setPositiveButton(android.R.string.cancel, null)
.create()
}
}
}
}
private const val KEY_URI = "RestoreBackupDialog.uri"
private const val CODE_BACKUP_DIR = 503
private const val CODE_BACKUP_CREATE = 504
private const val CODE_BACKUP_RESTORE = 505
| apache-2.0 | 9384c09447261073bfb7681245169322 | 39.573718 | 159 | 0.558654 | 5.17116 | false | false | false | false |
zensum/franz | src/main/kotlin/producer/Producer.kt | 1 | 1422 | package franz.producer
import org.apache.kafka.clients.producer.ProducerRecord
import java.util.concurrent.CompletableFuture
import kotlinx.coroutines.future.await
typealias ProduceResultF = CompletableFuture<ProduceResult>
interface Producer<K, V> {
@Deprecated("This API relies on directly on Kafka and will be removed")
fun sendRaw(rec: ProducerRecord<K, V>): ProduceResultF
fun sendAsync(topic: String, key: K?, value: V): ProduceResultF
fun sendAsync(topic: String, key: K?, value: V, headers: Iterable<Pair<String, ByteArray>>) : ProduceResultF
fun sendAsync(topic: String, key: K?, value: V, headers: Map<String, ByteArray>) =
sendAsync(topic, key, value, headers.toList())
fun close(): Unit
fun sendAsync(topic: String, value: V): ProduceResultF =
sendAsync(topic, null, value)
fun forTopic(topic: String) = TopicProducer(this, topic)
suspend fun send(topic: String, key: K?, value: V): ProduceResult =
sendAsync(topic, key, value).await()
suspend fun send(topic: String, value: V): ProduceResult =
sendAsync(topic, value).await()
suspend fun send(topic: String, key: K?, value: V, headers: Iterable<Pair<String, ByteArray>>) =
sendAsync(topic, key, value, headers).await()
suspend fun send(topic: String, key: K?, value: V, headers: Map<String, ByteArray>) =
sendAsync(topic, key, value, headers).await()
} | mit | 3382c92629baef059cd38bd1bd69ad09 | 38.527778 | 112 | 0.701828 | 3.802139 | false | false | false | false |
rpradal/OCTOMeuh | app/src/main/kotlin/com/octo/mob/octomeuh/settings/screen/SettingsActivity.kt | 1 | 2963 | package com.octo.mob.octomeuh.settings.screen
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import com.octo.mob.octomeuh.R
import com.octo.mob.octomeuh.settings.injection.SettingsComponent
import com.octo.mob.octomeuh.settings.model.RepetitionModeDescription
import com.octo.mob.octomeuh.settings.presenter.SettingsPresenter
import com.octo.mob.octomeuh.settings.utils.RepetitionModeDialogCreator
import kotlinx.android.synthetic.main.activity_settings.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
class SettingsActivity : AppCompatActivity(), SettingsScreen {
@Inject
lateinit var repetitionModeDialogCreator : RepetitionModeDialogCreator
@Inject
lateinit var presenter: SettingsPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
initToolbar()
SettingsComponent.init().inject(this)
durationCellLayout.setOnClickListener { presenter.onDurationChangeRequest() }
repetitionModeCellLayout.setOnClickListener { presenter.onRepetitionModeChangeRequest() }
}
private fun initToolbar() {
setSupportActionBar(toolbar)
supportActionBar?.title = getString(R.string.settings)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onResume() {
super.onResume()
presenter.attach(this)
}
override fun onPause() {
super.onPause()
presenter.detach()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item?.itemId) {
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun showVersionNumber(appVersionLabel: String) {
versionNumberTextView.text = appVersionLabel
}
override fun showRepetitionModeSelection(values: Array<RepetitionModeDescription>, selectionIndex: Int) {
val repetitionModeDialog = repetitionModeDialogCreator.getRepetitionModeDialog(values, selectionIndex, this)
repetitionModeDialog.show()
}
override fun showDurationSelection() {
val fragment = DurationPickerDialogFragment()
fragment.onDismissListener = object : DurationPickerDialogFragment.OnDismissListener {
override fun onDismiss() {
presenter.onDurationChanged()
}
}
fragment.show(supportFragmentManager, DurationPickerDialogFragment::class.java.simpleName)
}
override fun showCurrentRepetitionMode(repetitionModeDescription: RepetitionModeDescription) {
repetitionModeLabelTextView.setText(repetitionModeDescription.titleRes)
}
override fun showCurrentDuration(initialDuration: String) {
durationTextView.text = initialDuration
}
} | mit | 11832f88e624066e8ee6c3d00e88209c | 33.068966 | 116 | 0.725278 | 5.198246 | false | false | false | false |
williamfiset/Algorithms | slides/other/recursion/SumList.kt | 1 | 601 |
fun sum(ar: IntArray): Int {
return sum(0, ar)
}
fun sum(i: Int, ar: IntArray): Int {
if (i >= ar.size) {
return 0;
}
return ar[i] + sum(i+1, ar)
}
fun divideAndConquer(ar: List<Int>): Int {
if (ar.size == 0) {
return 0
}
return divideAndConquer(0, ar.size - 1, ar)
}
fun divideAndConquer(i:Int, j:Int, ar: List<Int>): Int {
if (i == j) {
return ar[i]
}
val mid = (i+j) / 2
return divideAndConquer(i, mid, ar) + divideAndConquer(mid+1, j, ar)
}
fun main() {
for (n in 0..20) {
val ar = List(n, {1})
println(ar)
println(divideAndConquer(ar))
}
}
| mit | 4ffc8128fcdeaaf8d344dc8504b86ed2 | 16.171429 | 70 | 0.562396 | 2.443089 | false | false | false | false |
Shynixn/BlockBall | blockball-bukkit-plugin/src/main/java/com/github/shynixn/blockball/bukkit/logic/business/service/DependencyPlaceholderApiServiceImpl.kt | 1 | 3631 | package com.github.shynixn.blockball.bukkit.logic.business.service
import com.github.shynixn.blockball.api.business.enumeration.PlaceHolder
import com.github.shynixn.blockball.api.business.service.*
import com.google.inject.Inject
import kotlinx.coroutines.Dispatchers
import me.clip.placeholderapi.expansion.PlaceholderExpansion
import org.bukkit.entity.Player
import org.bukkit.plugin.Plugin
/**
* Handles the connection to the placeholder API plugin.
*/
class DependencyPlaceholderApiServiceImpl @Inject constructor(
private val plugin: Plugin,
private val gameService: GameService,
private val placeHolderService: PlaceholderService,
private val persistenceStatsService: PersistenceStatsService,
private val coroutineSessionService: CoroutineSessionService
) : PlaceholderExpansion(),
DependencyPlaceholderApiService {
private var registerd: Boolean = false
/**
* Registers the placeholder hook if it is not already registered.
*/
override fun registerListener() {
if (!registerd) {
this.register()
registerd = true
}
}
/**
* Gets the expansion version which is the same of the plugin version.
*/
override fun getVersion(): String {
return plugin.description.version
}
/**
* Gets the expansion author for placeholderapi.
*/
override fun getAuthor(): String {
return plugin.description.authors[0]
}
/**
* Gets the identifier which is required by placeholderapi to match the placeholder against this plugin.
*/
override fun getIdentifier(): String {
return "blockball"
}
/**
* OnPlaceHolder Request
*
* @param player player
* @param s customText
* @return result
*/
override fun onPlaceholderRequest(player: Player?, s: String?): String? {
var result: String? = null
coroutineSessionService.launch(Dispatchers.Unconfined) {
try {
val stats = persistenceStatsService.getStatsFromPlayerAsync(player!!).await()
PlaceHolder.values().asSequence().filter { p -> s != null && s.startsWith(p.placeHolder) }
.forEach { p ->
if (p == PlaceHolder.STATS_WINRATE) {
result = String.format(
"%.2f",
stats.winRate
)
} else if (p == PlaceHolder.STATS_PLAYEDGAMES) {
result = stats.amountOfPlayedGames.toString()
} else if (p == PlaceHolder.STATS_GOALS_PER_GAME) {
result = String.format(
"%.2f",
stats.goalsPerGame
)
} else if (p == PlaceHolder.STATS_GOALS_AMOUNT) {
result = stats.amountOfGoals.toString()
} else if (p == PlaceHolder.STATS_WINS_AMOUNT) {
result = stats.amountOfWins.toString()
} else {
val data = s!!.split("_")
val game = gameService.getGameFromName(data[1])
if (game.isPresent) {
result = placeHolderService.replacePlaceHolders(data[0], game.get())
}
}
}
} catch (ignored: Exception) {
}
}
return result
}
}
| apache-2.0 | 974030495a2dc9389af75db463b532dc | 34.252427 | 108 | 0.553567 | 5.293003 | false | false | false | false |
adelnizamutdinov/headphone-reminder | app/src/main/kotlin/common/recycler/recycler.kt | 1 | 1034 | package common.recycler
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
fun <VH : RecyclerView.ViewHolder, LM : RecyclerView.LayoutManager, A : RecyclerView.Adapter<VH>>
mkRecycler(recyclerView: RecyclerView, layoutManager: LM, adapter: A): Pair<LM, A> =
recyclerView.let {
it.setHasFixedSize(true)
it.itemAnimator = DefaultItemAnimator()
it.layoutManager = layoutManager
it.adapter = adapter
return Pair(layoutManager, adapter)
}
fun <VH : RecyclerView.ViewHolder, A : RecyclerView.Adapter<VH>> A.stableIds(): A =
apply { setHasStableIds(true) }
inline fun from(crossinline f: (Int) -> Int): GridLayoutManager.SpanSizeLookup =
object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int = f(position)
}
inline fun GridLayoutManager.spanSizeLookup(crossinline f: (Int) -> Int): GridLayoutManager =
apply { spanSizeLookup = from(f) } | mit | 7427c178af846ebe4314c1a97fb5b6d3 | 38.807692 | 97 | 0.737911 | 4.362869 | false | false | false | false |
reime005/splintersweets | core/src/de/reimerm/splintersweets/actors/scene2d/Score.kt | 1 | 1366 | /*
* Copyright (c) 2017. Marius Reimer
*
* 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 de.reimerm.splintersweets.actors.scene2d
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.scenes.scene2d.ui.Label
import de.reimerm.splintersweets.enums.GameState
import de.reimerm.splintersweets.utils.GameManager
/**
* Created by Marius Reimer on 05-Oct-16.
*/
class Score(text: CharSequence? = "", style: LabelStyle?) : Label(text, style) {
private var score: Long = 0
override fun draw(batch: Batch?, parentAlpha: Float) {
super.draw(batch, parentAlpha)
if (GameManager.gameState != GameState.PAUSED) {
score = GameManager.score
}
if (GameManager.gameState == GameState.MENU) {
score = GameManager.onlineScore
}
setText(score.toString())
}
} | apache-2.0 | e71abc689001533fcf75b3efa245c2f6 | 30.068182 | 80 | 0.702782 | 3.815642 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/dao/LabelDao.kt | 1 | 387 | package com.booboot.vndbandroid.dao
import com.booboot.vndbandroid.model.vndb.Label
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
@Entity
class LabelDao() {
@Id(assignable = true) var id: Long = 0
var label: String = ""
constructor(item: Label) : this() {
id = item.id
label = item.label
}
fun toBo() = Label(id, label)
} | gpl-3.0 | 24944d7fed5c39c3a54336dc4f696f8d | 20.555556 | 47 | 0.666667 | 3.518182 | false | false | false | false |
jtransc/jtransc | benchmark_kotlin_mpp/src/commonMain/kotlin/simd/Float32x4.kt | 1 | 2395 | package simd
/**
* IMMUTABLE FLOAT32 x 4
*/
class Float32x4 private constructor(
private val x: Float,
private val y: Float,
private val z: Float,
private val w: Float
) {
companion object {
fun create(): Float32x4 {
return Float32x4(0f, 0f, 0f, 0f)
}
fun create(x: Float, y: Float, z: Float, w: Float): Float32x4 {
return Float32x4(x, y, z, w)
}
fun add(l: Float32x4, r: Float32x4): Float32x4 {
return Float32x4(l.x + r.x, l.y + r.y, l.z + r.z, l.w + r.w)
}
//@JTranscCallSiteBody(target = "dart", value = "((#0) + (#1) + (#2) + (#3))")
fun add(a: Float32x4, b: Float32x4, c: Float32x4, d: Float32x4): Float32x4 {
return add(add(a, b), add(c, d))
}
fun mul(l: Float32x4, r: Float32x4): Float32x4 {
return Float32x4(l.x * r.x, l.y * r.y, l.z * r.z, l.w * r.w)
}
fun mul(l: Float32x4, r: Float): Float32x4 {
return Float32x4(l.x * r, l.y * r, l.z * r, l.w * r)
}
fun getX(l: Float32x4): Float {
return l.x
}
fun getY(l: Float32x4): Float {
return l.y
}
fun getZ(l: Float32x4): Float {
return l.z
}
fun getW(l: Float32x4): Float {
return l.w
}
fun getLane(l: Float32x4, index: Int): Float {
return when (index) {
0 -> getX(l)
1 -> getY(l)
2 -> getZ(l)
3 -> getW(l)
else -> getX(l)
}
}
fun xxxx(l: Float32x4): Float32x4 {
return create(getX(l), getX(l), getX(l), getX(l))
}
fun yyyy(l: Float32x4): Float32x4 {
return create(getY(l), getY(l), getY(l), getY(l))
}
fun zzzz(l: Float32x4): Float32x4 {
return create(getZ(l), getZ(l), getZ(l), getZ(l))
}
fun wwww(l: Float32x4): Float32x4 {
return create(getW(l), getW(l), getW(l), getW(l))
}
fun mul44(R: Array<Float32x4?>, A: Array<Float32x4>, B: Array<Float32x4>) {
val a0 = A[0]
val a1 = A[1]
val a2 = A[2]
val a3 = A[3]
val b0 = B[0]
val b1 = B[1]
val b2 = B[2]
val b3 = B[3]
R[0] = add(mul(xxxx(b0), a0), mul(yyyy(b0), a1), mul(zzzz(b0), a2), mul(wwww(b0), a3))
R[1] = add(mul(xxxx(b1), a0), mul(yyyy(b1), a1), mul(zzzz(b1), a2), mul(wwww(b1), a3))
R[2] = add(mul(xxxx(b2), a0), mul(yyyy(b2), a1), mul(zzzz(b2), a2), mul(wwww(b2), a3))
R[3] = add(mul(xxxx(b3), a0), mul(yyyy(b3), a1), mul(zzzz(b3), a2), mul(wwww(b3), a3))
}
fun toString(v: Float32x4?): String {
return Float32x4Utils.toStringInternal(v)
}
init {
Simd.ref()
}
}
} | apache-2.0 | c22ea368abe6e509328ae341534cf3bb | 20.981651 | 89 | 0.566597 | 2.134581 | false | false | false | false |
rei-m/android_hyakuninisshu | infrastructure/src/main/java/me/rei_m/hyakuninisshu/infrastructure/database/KarutaRepositoryImpl.kt | 1 | 6739 | /*
* 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.infrastructure.database
import android.content.Context
import android.content.SharedPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import me.rei_m.hyakuninisshu.domain.karuta.model.KamiNoKu
import me.rei_m.hyakuninisshu.domain.karuta.model.Karuta
import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaColor
import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaId
import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaImageNo
import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaNo
import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaRepository
import me.rei_m.hyakuninisshu.domain.karuta.model.Kimariji
import me.rei_m.hyakuninisshu.domain.karuta.model.ShimoNoKu
import me.rei_m.hyakuninisshu.domain.karuta.model.Verse
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.coroutines.CoroutineContext
class KarutaRepositoryImpl(
private val context: Context,
private val preferences: SharedPreferences,
private val orma: OrmaDatabase,
private val ioContext: CoroutineContext = Dispatchers.IO
) : KarutaRepository {
@Suppress("BlockingMethodInNonBlockingContext")
override suspend fun initialize() {
withContext(ioContext) {
val karutaJsonVersion = preferences.getInt(
KarutaJsonConstant.KEY_KARUTA_JSON_VERSION,
0
)
if (karutaJsonVersion < KarutaJsonConstant.KARUTA_VERSION) {
val inputStream = context.assets.open("karuta_list_v_2.json")
val reader = BufferedReader(InputStreamReader(inputStream))
val stringBuilder = StringBuilder()
var line: String?
while (true) {
line = reader.readLine()
if (line == null) {
break
}
stringBuilder.append(line)
}
reader.close()
val karutaSchemaList = KarutaJsonAdaptor.convert(stringBuilder.toString())
orma.transactionSync {
karutaSchemaList.forEach {
val count = KarutaSchema.relation(orma).selector().idEq(it.id)
.and()
.where("isEdited = ?", true).count()
if (count == 0) {
KarutaSchema.relation(orma).upsert(it)
}
}
preferences.edit()
.putInt(
KarutaJsonConstant.KEY_KARUTA_JSON_VERSION,
KarutaJsonConstant.KARUTA_VERSION
)
.apply()
}
}
}
}
override suspend fun findByNo(karutaNo: KarutaNo): Karuta = withContext(ioContext) {
KarutaSchema.relation(orma).selector()
.idEq(karutaNo.value.toLong())
.first().toModel()
}
override suspend fun findAll(): List<Karuta> {
return withContext(ioContext) {
val relation = KarutaSchema.relation(orma)
relation.selector()
.orderBy(relation.schema.id.orderInAscending())
.toList()
.map { it.toModel() }
}
}
override suspend fun findAllWithCondition(
fromNo: KarutaNo,
toNo: KarutaNo,
kimarijis: List<Kimariji>,
colors: List<KarutaColor>
): List<Karuta> {
return withContext(ioContext) {
val relation = KarutaSchema.relation(orma)
var selector = relation.selector()
.idBetween(fromNo.value.toLong(), toNo.value.toLong())
selector = selector.and().kimarijiIn(kimarijis.map { it.value })
selector = selector.and().colorIn(colors.map { it.value })
selector
.orderBy(relation.schema.id.orderInAscending())
.toList()
.map { it.toModel() }
}
}
override suspend fun findAllWithNo(karutaNoList: List<KarutaNo>): List<Karuta> {
return withContext(ioContext) {
val relation = KarutaSchema.relation(orma)
val selector = relation.selector()
.idIn(karutaNoList.map { it.value.toLong() })
selector
.orderBy(relation.schema.id.orderInAscending())
.toList()
.map { it.toModel() }
}
}
override suspend fun save(karuta: Karuta) = withContext(ioContext) {
val kamiNoKu = karuta.kamiNoKu
val shimoNoKu = karuta.shimoNoKu
KarutaSchema.relation(orma).updater()
.idEq(karuta.identifier.value.toLong())
.firstKana(kamiNoKu.shoku.kana)
.firstKanji(kamiNoKu.shoku.kanji)
.secondKana(kamiNoKu.niku.kana)
.secondKanji(kamiNoKu.niku.kanji)
.thirdKana(kamiNoKu.sanku.kana)
.thirdKanji(kamiNoKu.sanku.kanji)
.fourthKana(shimoNoKu.shiku.kana)
.fourthKanji(shimoNoKu.shiku.kanji)
.fifthKana(shimoNoKu.goku.kana)
.fifthKanji(shimoNoKu.goku.kanji)
.isEdited(true)
.execute()
return@withContext
}
}
private fun KarutaSchema.toModel(): Karuta {
val identifier = KarutaId(id.toInt())
val karutaNo = KarutaNo(id.toInt())
val firstPart = Verse(firstKana, firstKanji)
val secondPart = Verse(secondKana, secondKanji)
val thirdPart = Verse(thirdKana, thirdKanji)
val fourthPart = Verse(fourthKana, fourthKanji)
val fifthPart = Verse(fifthKana, fifthKanji)
val kamiNoKu = KamiNoKu(karutaNo, firstPart, secondPart, thirdPart)
val shimoNoKu = ShimoNoKu(karutaNo, fourthPart, fifthPart)
val kimariji = Kimariji.forValue(kimariji)
val color = KarutaColor.forValue(color)
return Karuta(
identifier,
karutaNo,
creator,
kamiNoKu,
shimoNoKu,
kimariji,
KarutaImageNo(imageNo),
translation,
color
)
}
| apache-2.0 | 3dfc81b59ac9a8aec3d36931a4082f09 | 35.825137 | 112 | 0.612257 | 4.273304 | false | false | false | false |
square/moshi | moshi/src/main/java/com/squareup/moshi/JsonScope.kt | 1 | 2849 | /*
* Copyright (C) 2010 Google 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.squareup.moshi
/** Lexical scoping elements within a JSON reader or writer. */
internal object JsonScope {
/** An array with no elements requires no separators or newlines before it is closed. */
const val EMPTY_ARRAY = 1
/** An array with at least one value requires a comma and newline before the next element. */
const val NONEMPTY_ARRAY = 2
/** An object with no name/value pairs requires no separators or newlines before it is closed. */
const val EMPTY_OBJECT = 3
/** An object whose most recent element is a key. The next element must be a value. */
const val DANGLING_NAME = 4
/** An object with at least one name/value pair requires a separator before the next element. */
const val NONEMPTY_OBJECT = 5
/** No object or array has been started. */
const val EMPTY_DOCUMENT = 6
/** A document with at an array or object. */
const val NONEMPTY_DOCUMENT = 7
/** A document that's been closed and cannot be accessed. */
const val CLOSED = 8
/** Sits above the actual state to indicate that a value is currently being streamed in. */
const val STREAMING_VALUE = 9
/**
* Renders the path in a JSON document to a string. The `pathNames` and `pathIndices`
* parameters corresponds directly to stack: At indices where the stack contains an object
* (EMPTY_OBJECT, DANGLING_NAME or NONEMPTY_OBJECT), pathNames contains the name at this scope.
* Where it contains an array (EMPTY_ARRAY, NONEMPTY_ARRAY) pathIndices contains the current index
* in that array. Otherwise the value is undefined, and we take advantage of that by incrementing
* pathIndices when doing so isn't useful.
*/
@JvmStatic
fun getPath(stackSize: Int, stack: IntArray, pathNames: Array<String?>, pathIndices: IntArray): String {
return buildString {
append('$')
for (i in 0 until stackSize) {
when (stack[i]) {
EMPTY_ARRAY, NONEMPTY_ARRAY -> append('[').append(pathIndices[i]).append(']')
EMPTY_OBJECT, DANGLING_NAME, NONEMPTY_OBJECT -> {
append('.')
if (pathNames[i] != null) {
append(pathNames[i])
}
}
NONEMPTY_DOCUMENT, EMPTY_DOCUMENT, CLOSED -> {}
}
}
}
}
}
| apache-2.0 | 221ca4780c05339805678e0ac4e9955c | 38.027397 | 106 | 0.682696 | 4.245902 | false | false | false | false |
pdvrieze/ProcessManager | PMEditor/src/main/java/nl/adaptivity/diagram/android/AndroidCanvas.kt | 1 | 17383 | /*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.diagram.android
import android.graphics.*
import android.graphics.Paint.Style
import nl.adaptivity.diagram.Canvas
import nl.adaptivity.diagram.Pen
import nl.adaptivity.diagram.Rectangle
import nl.adaptivity.diagram.Theme
import org.jetbrains.annotations.Contract
class AndroidCanvas(private var canvas: android.graphics.Canvas,
private var _theme: Theme<AndroidStrategy, AndroidPen, AndroidPath>?)
: IAndroidCanvas {
override val strategy: AndroidStrategy
get() = AndroidStrategy.INSTANCE
override val theme: Theme<AndroidStrategy, AndroidPen, AndroidPath>
get() {
return _theme ?: AndroidTheme(strategy).also { _theme = it }
}
fun setCanvas(canvas: android.graphics.Canvas) {
this.canvas = canvas
}
override fun childCanvas(offsetX: Double, offsetY: Double, scale: Double): IAndroidCanvas {
return OffsetCanvas(offsetX, offsetY, scale)
}
override fun drawFilledCircle(x: Double, y: Double, radius: Double, fill: AndroidPen) {
val paint = fill.paint
val oldStyle = paint.style
paint.style = Paint.Style.FILL
canvas.drawCircle(x.toFloat(), y.toFloat(), radius.toFloat(), paint)
paint.style = oldStyle
}
override fun drawCircle(x: Double, y: Double, radius: Double, stroke: AndroidPen) {
canvas.drawCircle(x.toFloat(), y.toFloat(), radius.toFloat(), stroke.paint)
}
override fun drawCircle(x: Double,
y: Double,
radius: Double,
stroke: AndroidPen?,
fill: AndroidPen?) {
if (fill != null) {
drawFilledCircle(x, y, radius, fill)
}
if (stroke != null) {
drawCircle(x, y, radius, stroke)
}
}
override fun drawFilledRoundRect(rect: Rectangle,
rx: Double,
ry: Double,
fill: AndroidPen) {
val paint = fill.paint
val oldStyle = paint.style
paint.style = Paint.Style.FILL
canvas.drawRoundRect(toRectF(rect), rx.toFloat(), ry.toFloat(), fill.paint)
paint.style = oldStyle
}
override fun drawRoundRect(rect: Rectangle,
rx: Double,
ry: Double,
stroke: AndroidPen) {
canvas.drawRoundRect(toRectF(rect), rx.toFloat(), ry.toFloat(), stroke.paint)
}
override fun drawRoundRect(rect: Rectangle,
rx: Double,
ry: Double,
stroke: AndroidPen?,
fill: AndroidPen?) {
if (fill != null) {
drawFilledRoundRect(rect, rx, ry, fill)
}
if (stroke != null) {
drawRoundRect(rect, rx, ry, stroke)
}
}
override fun drawFilledRect(rect: Rectangle, fill: AndroidPen) {
val paint = fill.paint
val oldStyle = paint.style
paint.style = Paint.Style.FILL
canvas.drawRect(toRectF(rect), fill.paint)
paint.style = oldStyle
}
override fun drawRect(rect: Rectangle, stroke: AndroidPen) {
canvas.drawRect(toRectF(rect), stroke.paint)
}
override fun drawRect(rect: Rectangle,
stroke: AndroidPen?,
fill: AndroidPen?) {
if (fill != null) {
drawFilledRect(rect, fill)
}
if (stroke != null) {
drawRect(rect, stroke)
}
}
override fun drawPoly(points: DoubleArray,
stroke: AndroidPen?,
fill: AndroidPen?) {
val androidPath = toPath(points)
if (fill != null) {
val fillPaint = fill.paint
val oldStyle = fillPaint.style
fillPaint.style = Paint.Style.FILL
canvas.drawPath(androidPath, fill.paint)
fillPaint.style = oldStyle
}
if (stroke != null) {
canvas.drawPath(androidPath, stroke.paint)
}
}
override fun drawPath(path: AndroidPath,
stroke: AndroidPen?,
fill: AndroidPen?) {
if (fill != null) drawFilledPath(path.path, fill.paint)
if (stroke != null) drawPath(path.path, stroke.paint)
}
internal fun drawPath(path: Path, paint: Paint) {
canvas.drawPath(path, paint)
}
private fun drawFilledPath(path: Path, paint: Paint) {
val oldStyle = paint.style
paint.style = Paint.Style.FILL
canvas.drawPath(path, paint)
paint.style = oldStyle
}
private fun toPath(points: DoubleArray): Path {
val result = Path()
val len = points.size - 1
if (len > 0) {
result.moveTo(points[0].toFloat(), points[1].toFloat())
var i = 2
while (i < len) {
result.lineTo(points[i].toFloat(), points[++i].toFloat())
++i
}
result.close()
}
return result
}
private fun toRectF(rect: Rectangle): RectF {
return RectF(rect.leftf, rect.topf, rect.rightf, rect.bottomf)
}
override fun scale(scale: Double): IAndroidCanvas {
return OffsetCanvas(scale)
}
override fun translate(dx: Double, dy: Double): IAndroidCanvas {
return if (dx == 0.0 && dy == 0.0) {
this
} else OffsetCanvas(dx, dy, 1.0)
}
override fun drawBitmap(left: Double, top: Double, bitmap: Bitmap, pen: AndroidPen) {
canvas.drawBitmap(bitmap, left.toFloat(), top.toFloat(), pen.paint)
}
override fun drawText(textPos: Canvas.TextPos,
left: Double,
baselineY: Double,
text: String,
foldWidth: Double,
pen: AndroidPen) {
drawText(textPos, left, baselineY, text, foldWidth, pen, 1.0)
}
private fun drawText(textPos: Canvas.TextPos,
x: Double,
y: Double,
text: String,
foldWidth: Double,
pen: AndroidPen,
scale: Double) {
val paint = pen.paint
paint.style = Style.FILL
val left = getLeft(textPos, x, text, foldWidth, pen, scale)
val baseline = getBaseLine(textPos, y, pen, scale)
canvas.drawText(text, left, baseline, paint)
//Only for debug purposes
// mCanvas.drawCircle(left, baseline, 3f, mRedPaint);
// mCanvas.drawCircle((float)pX, (float)pY, 3f, mGreenPaint);
}
private fun getBaseLine(textPos: Canvas.TextPos,
y: Double,
pen: Pen<*>,
scale: Double): Float {
when (textPos) {
Canvas.TextPos.MAXTOPLEFT,
Canvas.TextPos.MAXTOP,
Canvas.TextPos.MAXTOPRIGHT -> return (y + pen.textMaxAscent * scale).toFloat()
Canvas.TextPos.ASCENTLEFT,
Canvas.TextPos.ASCENT,
Canvas.TextPos.ASCENTRIGHT -> return (y + pen.textAscent * scale).toFloat()
Canvas.TextPos.LEFT,
Canvas.TextPos.MIDDLE,
Canvas.TextPos.RIGHT -> return (y + (0.5 * pen.textAscent - 0.5 * pen.textDescent) * scale).toFloat()
Canvas.TextPos.BASELINEMIDDLE,
Canvas.TextPos.BASELINERIGHT,
Canvas.TextPos.BASELINELEFT -> return y.toFloat()
Canvas.TextPos.BOTTOMLEFT,
Canvas.TextPos.BOTTOMRIGHT,
Canvas.TextPos.BOTTOM -> return (y - pen.textMaxDescent * scale).toFloat()
Canvas.TextPos.DESCENTLEFT,
Canvas.TextPos.DESCENTRIGHT,
Canvas.TextPos.DESCENT -> return (y - pen.textDescent * scale).toFloat()
}
}
private fun getLeft(textPos: Canvas.TextPos,
x: Double,
text: String,
foldWidth: Double,
pen: AndroidPen,
scale: Double): Float {
when (textPos) {
Canvas.TextPos.BASELINELEFT,
Canvas.TextPos.BOTTOMLEFT,
Canvas.TextPos.LEFT,
Canvas.TextPos.MAXTOPLEFT,
Canvas.TextPos.ASCENTLEFT -> return x.toFloat()
Canvas.TextPos.ASCENT,
Canvas.TextPos.DESCENT,
Canvas.TextPos.BASELINEMIDDLE,
Canvas.TextPos.MAXTOP,
Canvas.TextPos.MIDDLE,
Canvas.TextPos.BOTTOM -> return (x - pen.measureTextWidth(text, foldWidth) * scale / 2).toFloat()
Canvas.TextPos.MAXTOPRIGHT,
Canvas.TextPos.ASCENTRIGHT,
Canvas.TextPos.DESCENTLEFT,
Canvas.TextPos.DESCENTRIGHT,
Canvas.TextPos.RIGHT,
Canvas.TextPos.BASELINERIGHT,
Canvas.TextPos.BOTTOMRIGHT -> return (x - pen.measureTextWidth(text, foldWidth) * scale).toFloat()
}
}
private inner class OffsetCanvas(xOffset: Double, yOffset: Double, private val scale: Double) : IAndroidCanvas {
/** The offset of the canvas. This is in scaled coordinates. */
private val xOffset: Double = -xOffset
private val yOffset: Double = -yOffset
override val strategy: AndroidStrategy
get() = AndroidStrategy.INSTANCE
override val theme: Theme<AndroidStrategy, AndroidPen, AndroidPath>
get() = [email protected]
constructor(base: OffsetCanvas, offsetX: Double, offsetY: Double, scale: Double) :
this((base.xOffset - offsetX) * scale,
(base.yOffset - offsetY) * scale,
base.scale * scale)
constructor(base: OffsetCanvas, scale: Double) :
this(base.xOffset * scale, base.yOffset * scale, base.scale * scale)
constructor(scale: Double) : this(0.0, 0.0, scale)
override fun scale(scale: Double): IAndroidCanvas {
return OffsetCanvas(this, scale)
}
override fun childCanvas(offsetX: Double, offsetY: Double, scale: Double): IAndroidCanvas {
return OffsetCanvas(this, offsetX, offsetY, scale)
}
override fun translate(dx: Double, dy: Double): IAndroidCanvas {
return OffsetCanvas(xOffset - dx, yOffset - dy, scale)
}
@Contract("null -> null; !null -> !null")
private fun scalePen(pen: AndroidPen?): AndroidPen? {
return pen?.scale(scale)
}
override fun drawCircle(x: Double, y: Double, radius: Double, stroke: AndroidPen) {
[email protected](transformX(x), transformY(y), radius * scale, scalePen(stroke)!!)
}
override fun drawFilledCircle(x: Double,
y: Double,
radius: Double,
fill: AndroidPen) {
[email protected](transformX(x), transformY(y), radius * scale, fill)
}
override fun drawCircle(x: Double, y: Double, radius: Double, stroke: AndroidPen?,
fill: AndroidPen?) {
if (fill != null) {
[email protected](transformX(x), transformY(y), radius * scale, fill)
}
if (stroke != null) {
[email protected](transformX(x), transformY(y), radius * scale, scalePen(stroke)!!)
}
}
override fun drawBitmap(left: Double,
top: Double,
bitmap: Bitmap,
pen: AndroidPen) {
[email protected](transformX(left), transformY(top), bitmap, scalePen(pen)!!)
}
override fun drawRect(rect: Rectangle, stroke: AndroidPen) {
[email protected](rect.offsetScaled(-xOffset, -yOffset, scale), scalePen(stroke)!!)
}
override fun drawFilledRect(rect: Rectangle, fill: AndroidPen) {
[email protected](rect.offsetScaled(-xOffset, -yOffset, scale), scalePen(fill)!!)
}
override fun drawRect(rect: Rectangle,
stroke: AndroidPen?,
fill: AndroidPen?) {
if (fill != null) {
[email protected](rect.offsetScaled(-xOffset, -yOffset, scale), fill)
}
if (stroke != null) {
[email protected](rect.offsetScaled(-xOffset, -yOffset, scale), scalePen(stroke)!!)
}
}
override fun drawPoly(points: DoubleArray,
stroke: AndroidPen?,
fill: AndroidPen?) {
[email protected](transform(points), scalePen(stroke), fill)
}
private fun transform(points: DoubleArray): DoubleArray {
val result = DoubleArray(points.size)
val len = points.size - 1
var i = 0
while (i < len) {
result[i] = transformX(points[i])
++i
result[i] = transformY(points[i])
++i
}
return result
}
fun transformX(x: Double): Double {
return (x - xOffset) * scale
}
fun transformY(y: Double): Double {
return (y - yOffset) * scale
}
override fun drawPath(path: AndroidPath, stroke: AndroidPen?, fill: AndroidPen?) {
val transformedPath = transformPath(path)
if (fill != null) {
[email protected](transformedPath, fill.paint)
}
if (stroke != null) {
[email protected](transformedPath, scalePen(stroke)!!.paint)
}
}
private fun transformPath(path: AndroidPath): Path {
val transformedPath = Path(path.path)
val matrix = Matrix()
matrix.setScale(scale.toFloat(), scale.toFloat())
matrix.preTranslate((-xOffset).toFloat(), (-yOffset).toFloat())
transformedPath.transform(matrix)
return transformedPath
}
override fun drawRoundRect(rect: Rectangle,
rx: Double,
ry: Double,
stroke: AndroidPen) {
[email protected](rect.offsetScaled(-xOffset, -yOffset, scale), rx * scale, ry * scale,
scalePen(
stroke)!!)
}
override fun drawFilledRoundRect(rect: Rectangle,
rx: Double,
ry: Double,
fill: AndroidPen) {
[email protected](rect.offsetScaled(-xOffset, -yOffset, scale), rx * scale,
ry * scale, scalePen(
fill)!!)
}
override fun drawRoundRect(rect: Rectangle,
rx: Double,
ry: Double,
stroke: AndroidPen?,
fill: AndroidPen?) {
if (fill != null) {
[email protected](rect.offsetScaled(-xOffset, -yOffset, scale), rx * scale,
ry * scale, scalePen(fill)!!)
}
if (stroke != null) {
[email protected](rect.offsetScaled(-xOffset, -yOffset, scale), rx * scale,
ry * scale, scalePen(stroke)!!)
}
}
override fun drawText(textPos: Canvas.TextPos,
left: Double,
baselineY: Double,
text: String,
foldWidth: Double,
pen: AndroidPen) {
[email protected](textPos, transformX(left), transformY(baselineY), text, foldWidth * scale,
scalePen(pen)!!, scale)
}
}
}
| lgpl-3.0 | dec0b259bea40c8ab16e9d36de4b2925 | 36.382796 | 120 | 0.53305 | 4.728781 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/ktx/Double.kt | 1 | 302 | package de.westnordost.streetcomplete.ktx
import java.util.*
fun Double.toShortString() = if (this % 1 == 0.0) toInt().toString() else toString()
fun Double.format(digits: Int) = "%.${digits}f".format(null, this)
fun Double.format(locale: Locale, digits: Int) = "%.${digits}f".format(locale, this)
| gpl-3.0 | f6d6b43853b899cb969140933b20f373 | 32.555556 | 84 | 0.698675 | 3.247312 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/SplitWayFragment.kt | 1 | 11396 | package de.westnordost.streetcomplete.quests
import android.animation.AnimatorInflater
import android.annotation.SuppressLint
import android.content.res.Configuration
import android.graphics.PointF
import android.graphics.drawable.Animatable
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.RelativeLayout
import androidx.annotation.UiThread
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.core.view.isInvisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.split_way.SplitAtLinePosition
import de.westnordost.streetcomplete.data.osm.edits.split_way.SplitAtPoint
import de.westnordost.streetcomplete.data.osm.edits.split_way.SplitPolylineAtPosition
import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.data.osm.mapdata.LatLon
import de.westnordost.streetcomplete.data.osm.mapdata.Way
import de.westnordost.streetcomplete.data.quest.OsmQuestKey
import de.westnordost.streetcomplete.data.quest.QuestKey
import de.westnordost.streetcomplete.databinding.FragmentSplitWayBinding
import de.westnordost.streetcomplete.ktx.*
import de.westnordost.streetcomplete.util.SoundFx
import de.westnordost.streetcomplete.util.alongTrackDistanceTo
import de.westnordost.streetcomplete.util.crossTrackDistanceTo
import de.westnordost.streetcomplete.util.distanceTo
import de.westnordost.streetcomplete.view.RoundRectOutlineProvider
import de.westnordost.streetcomplete.view.insets_animation.respectSystemInsets
import kotlinx.coroutines.launch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import javax.inject.Inject
import kotlin.math.abs
/** Fragment that lets the user split an OSM way */
class SplitWayFragment : Fragment(R.layout.fragment_split_way),
IsCloseableBottomSheet, IsShowingQuestDetails {
private val splits: MutableList<Pair<SplitPolylineAtPosition, LatLon>> = mutableListOf()
private val binding by viewBinding(FragmentSplitWayBinding::bind)
@Inject internal lateinit var soundFx: SoundFx
override val questKey: QuestKey get() = osmQuestKey
private lateinit var osmQuestKey: OsmQuestKey
private lateinit var way: Way
private lateinit var positions: List<LatLon>
private var clickPos: PointF? = null
private val hasChanges get() = splits.isNotEmpty()
private val isFormComplete get() = splits.size >= if (way.isClosed) 2 else 1
interface Listener {
fun onAddSplit(point: LatLon)
fun onRemoveSplit(point: LatLon)
fun onSplittedWay(osmQuestKey: OsmQuestKey, splits: List<SplitPolylineAtPosition>)
}
private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener
init {
Injector.applicationComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args = requireArguments()
osmQuestKey = Json.decodeFromString(args.getString(ARG_OSM_QUEST_KEY)!!)
way = Json.decodeFromString(args.getString(ARG_WAY)!!)
val elementGeometry: ElementPolylinesGeometry = Json.decodeFromString(args.getString(ARG_ELEMENT_GEOMETRY)!!)
positions = elementGeometry.polylines.single()
}
@SuppressLint("ClickableViewAccessibility")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.bottomSheetContainer.respectSystemInsets(View::setMargins)
binding.splitWayRoot.setOnTouchListener { _, event ->
clickPos = PointF(event.x, event.y)
false
}
binding.okButton.setOnClickListener { onClickOk() }
binding.cancelButton.setOnClickListener { activity?.onBackPressed() }
binding.undoButton.setOnClickListener { onClickUndo() }
binding.undoButton.isInvisible = !hasChanges
binding.okButton.isInvisible = !isFormComplete
val cornerRadius = resources.getDimension(R.dimen.speech_bubble_rounded_corner_radius)
val margin = resources.getDimensionPixelSize(R.dimen.horizontal_speech_bubble_margin)
binding.speechbubbleContentContainer.outlineProvider = RoundRectOutlineProvider(
cornerRadius, margin, margin, margin, margin
)
if (savedInstanceState == null) {
binding.speechbubbleContentContainer.startAnimation(
AnimationUtils.loadAnimation(context, R.anim.inflate_answer_bubble)
)
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// see rant comment in AbstractBottomSheetFragment
resources.updateConfiguration(newConfig, resources.displayMetrics)
binding.bottomSheetContainer.updateLayoutParams { width = resources.getDimensionPixelSize(R.dimen.quest_form_width) }
}
private fun onClickOk() {
if (splits.size > 2) {
confirmManySplits { onSplittedWayConfirmed() }
} else {
onSplittedWayConfirmed()
}
}
private fun onSplittedWayConfirmed() {
listener?.onSplittedWay(osmQuestKey, splits.map { it.first })
}
private fun confirmManySplits(callback: () -> (Unit)) {
context?.let {
AlertDialog.Builder(it)
.setTitle(R.string.quest_generic_confirmation_title)
.setMessage(R.string.quest_split_way_many_splits_confirmation_description)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> callback() }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
}
private fun onClickUndo() {
if (splits.isNotEmpty()) {
val item = splits.removeAt(splits.lastIndex)
animateButtonVisibilities()
viewLifecycleScope.launch { soundFx.play(R.raw.plop2) }
listener?.onRemoveSplit(item.second)
}
}
@UiThread
override fun onClickMapAt(position: LatLon, clickAreaSizeInMeters: Double): Boolean {
val splitWayCandidates = createSplits(position, clickAreaSizeInMeters)
if (splitWayCandidates.isEmpty()) return true
// show toast only if it is possible to zoom in further
if (splitWayCandidates.size > 1 && clickAreaSizeInMeters > CLICK_AREA_SIZE_AT_MAX_ZOOM) {
context?.toast(R.string.quest_split_way_too_imprecise)
return true
}
val splitWay = splitWayCandidates.minByOrNull { it.pos.distanceTo(position) }!!
val splitPosition = splitWay.pos
// new split point is too close to existing split points
if (splits.any { it.second.distanceTo(splitPosition) < clickAreaSizeInMeters } ) {
context?.toast(R.string.quest_split_way_too_imprecise)
} else {
splits.add(Pair(splitWay, splitPosition))
animateButtonVisibilities()
animateScissors()
listener?.onAddSplit(splitPosition)
}
// always consume event. User should press the cancel button to exit
return true
}
private fun animateScissors() {
val scissorsPos = clickPos ?: return
(binding.scissors.drawable as? Animatable)?.start()
binding.scissors.updateLayoutParams<RelativeLayout.LayoutParams> {
leftMargin = (scissorsPos.x - binding.scissors.width/2).toInt()
topMargin = (scissorsPos.y - binding.scissors.height/2).toInt()
}
binding.scissors.alpha = 1f
val animator = AnimatorInflater.loadAnimator(context, R.animator.scissors_snip)
animator.setTarget(binding.scissors)
animator.start()
viewLifecycleScope.launch { soundFx.play(R.raw.snip) }
}
private fun createSplits(clickPosition: LatLon, clickAreaSizeInMeters: Double): Set<SplitPolylineAtPosition> {
val splitWaysAtNodes = createSplitsAtNodes(clickPosition, clickAreaSizeInMeters)
// if a split on a node is possible, do that and don't even check if a split on a way is also possible
if (splitWaysAtNodes.isNotEmpty()) return splitWaysAtNodes
return createSplitsForLines(clickPosition, clickAreaSizeInMeters)
}
private fun createSplitsAtNodes(clickPosition: LatLon, clickAreaSizeInMeters: Double): Set<SplitAtPoint> {
// ignore first and last node (cannot be split at the very start or end)
val result = mutableSetOf<SplitAtPoint>()
for (pos in positions.subList(1, positions.size - 1)) {
val nodeDistance = clickPosition.distanceTo(pos)
if (clickAreaSizeInMeters > nodeDistance) {
result.add(SplitAtPoint(pos))
}
}
return result
}
private fun createSplitsForLines(clickPosition: LatLon, clickAreaSizeInMeters: Double): Set<SplitAtLinePosition> {
val result = mutableSetOf<SplitAtLinePosition>()
positions.forEachLine { first, second ->
val crossTrackDistance = abs(clickPosition.crossTrackDistanceTo(first, second))
if (clickAreaSizeInMeters > crossTrackDistance) {
val alongTrackDistance = clickPosition.alongTrackDistanceTo(first, second)
val distance = first.distanceTo(second)
if (distance > alongTrackDistance && alongTrackDistance > 0) {
val delta = alongTrackDistance / distance
result.add(SplitAtLinePosition(first, second, delta))
}
}
}
return result
}
@UiThread override fun onClickClose(onConfirmed: () -> Unit) {
if (!hasChanges) {
onConfirmed()
} else {
activity?.let {
AlertDialog.Builder(it)
.setMessage(R.string.confirmation_discard_title)
.setPositiveButton(R.string.confirmation_discard_positive) { _, _ ->
onConfirmed()
}
.setNegativeButton(R.string.confirmation_discard_negative, null)
.show()
}
}
}
private fun animateButtonVisibilities() {
if (isFormComplete) binding.okButton.popIn() else binding.okButton.popOut()
if (hasChanges) binding.undoButton.popIn() else binding.undoButton.popOut()
}
companion object {
private const val CLICK_AREA_SIZE_AT_MAX_ZOOM = 2.6
private const val ARG_OSM_QUEST_KEY = "osmQuestKey"
private const val ARG_WAY = "way"
private const val ARG_ELEMENT_GEOMETRY = "elementGeometry"
fun create(osmQuestKey: OsmQuestKey, way: Way, elementGeometry: ElementPolylinesGeometry): SplitWayFragment {
val f = SplitWayFragment()
f.arguments = bundleOf(
ARG_OSM_QUEST_KEY to Json.encodeToString(osmQuestKey),
ARG_WAY to Json.encodeToString(way),
ARG_ELEMENT_GEOMETRY to Json.encodeToString(elementGeometry)
)
return f
}
}
}
| gpl-3.0 | a53926dd87e9f84c051b8ad8e197b570 | 40.74359 | 125 | 0.694454 | 4.70326 | false | false | false | false |
jinping125/ukulele-kotlin-blog | src/main/kotlin/com/after10years/blog/model/ModuleModel.kt | 1 | 517 | package com.after10years.blog.model
import java.sql.Timestamp
class ModuleModel {
var moduleId : Int? = null
var uriRoute : String? = null
var moduleName : String? = null
var img : String? = null
var pid : Int? = null
var addTime : Timestamp? = null
var commentCount : Int? = null
override fun toString(): String {
return "ModuleModel(moduleId=$moduleId, uriRoute=$uriRoute, moduleName=$moduleName, img=$img, pid=$pid, addTime=$addTime, commentCount=$commentCount)"
}
} | apache-2.0 | af43ebcc48915bfd585e1b5fa35d0311 | 27.777778 | 158 | 0.675048 | 3.887218 | false | false | false | false |
gotev/android-upload-service | uploadservice/src/main/java/net/gotev/uploadservice/observer/request/RequestObserver.kt | 2 | 1751 | package net.gotev.uploadservice.observer.request
import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import net.gotev.uploadservice.UploadRequest
import net.gotev.uploadservice.UploadService
import net.gotev.uploadservice.data.UploadInfo
class RequestObserver @JvmOverloads constructor(
context: Context,
lifecycleOwner: LifecycleOwner,
delegate: RequestObserverDelegate,
shouldAcceptEventsFrom: (uploadInfo: UploadInfo) -> Boolean = { true }
) : BaseRequestObserver(context, delegate, shouldAcceptEventsFrom), LifecycleObserver {
private var subscribedUploadID: String? = null
init {
lifecycleOwner.lifecycle.addObserver(this)
}
/**
* Register this upload receiver to listen for events.
*/
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
override fun register() {
super.register()
subscribedUploadID?.let {
if (!UploadService.taskList.contains(it)) {
delegate.onCompletedWhileNotObserving()
}
}
}
/**
* Unregister this upload receiver from listening events.
*/
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
override fun unregister() {
super.unregister()
}
/**
* Subscribe to get only the events from the given upload request. Otherwise, it will listen to
* all the upload requests.
*/
fun subscribe(request: UploadRequest<*>) {
subscribedUploadID = request.startUpload()
shouldAcceptEventsFrom = { uploadInfo ->
subscribedUploadID?.let { it == uploadInfo.uploadId } ?: false
}
}
}
| apache-2.0 | 248b0c6677486ac16582582fcc0a0ed0 | 29.719298 | 99 | 0.6996 | 4.918539 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashTask.kt | 1 | 4324 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.asynchronous.asynctasks.hashcalculator
import android.content.Context
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.amaze.filemanager.R
import com.amaze.filemanager.asynchronous.asynctasks.Task
import com.amaze.filemanager.filesystem.HybridFileParcelable
import com.amaze.filemanager.filesystem.files.FileUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.Callable
data class Hash(val md5: String, val sha: String)
class CalculateHashTask(
private val file: HybridFileParcelable,
context: Context,
view: View
) : Task<Hash, Callable<Hash>> {
private val log: Logger = LoggerFactory.getLogger(CalculateHashTask::class.java)
private val task: Callable<Hash> = if (file.isSftp) {
CalculateHashSftpCallback(file)
} else if (file.isFtp) {
// Don't do this. Especially when FTPClient requires thread safety.
DoNothingCalculateHashCallback()
} else {
CalculateHashCallback(file, context)
}
private val context = WeakReference(context)
private val view = WeakReference(view)
override fun getTask(): Callable<Hash> = task
override fun onError(error: Throwable) {
log.error("Error on calculate hash", error)
updateView(null)
}
override fun onFinish(value: Hash) {
updateView(value)
}
private fun updateView(hashes: Hash?) {
val context = context.get()
context ?: return
val view = view.get()
view ?: return
val md5Text = hashes?.md5 ?: context.getString(R.string.unavailable)
val shaText = hashes?.sha ?: context.getString(R.string.unavailable)
val md5HashText = view.findViewById<TextView>(R.id.t9)
val sha256Text = view.findViewById<TextView>(R.id.t10)
val mMD5LinearLayout = view.findViewById<LinearLayout>(R.id.properties_dialog_md5)
val mSHA256LinearLayout = view.findViewById<LinearLayout>(R.id.properties_dialog_sha256)
if (!file.isDirectory(context) && file.getSize() != 0L) {
md5HashText.text = md5Text
sha256Text.text = shaText
mMD5LinearLayout.setOnLongClickListener {
FileUtils.copyToClipboard(context, md5Text)
Toast.makeText(
context,
context.resources.getString(R.string.md5).uppercase(Locale.getDefault()) +
" " +
context.resources.getString(R.string.properties_copied_clipboard),
Toast.LENGTH_SHORT
)
.show()
false
}
mSHA256LinearLayout.setOnLongClickListener {
FileUtils.copyToClipboard(context, shaText)
Toast.makeText(
context,
context.resources.getString(R.string.hash_sha256) + " " +
context.resources.getString(R.string.properties_copied_clipboard),
Toast.LENGTH_SHORT
)
.show()
false
}
} else {
mMD5LinearLayout.visibility = View.GONE
mSHA256LinearLayout.visibility = View.GONE
}
}
}
| gpl-3.0 | b7a4245e629fe226e79c7a49bd063a0f | 35.644068 | 107 | 0.659112 | 4.403259 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/local/LocalNovelProvider.kt | 1 | 3266 | package cc.aoeiuv020.panovel.local
import cc.aoeiuv020.exception.interrupt
import cc.aoeiuv020.panovel.api.NovelChapter
import cc.aoeiuv020.panovel.data.NovelProvider
import cc.aoeiuv020.panovel.data.entity.Novel
import java.io.File
import java.net.URL
import java.util.*
/**
* Created by AoEiuV020 on 2018.06.13-15:38:49.
*/
class LocalNovelProvider(
private val novel: Novel
) : NovelProvider {
// detail直接保存文件全路径,/x/y/z
private val file = File(novel.detail)
private val type = LocalNovelType.values()
.firstOrNull { it.suffix == novel.site }
?: interrupt("本地小说类型<${novel.site}>不支持")
private val parser = when (type) {
LocalNovelType.TEXT -> TextParser(file, charset(novel.nChapters))
LocalNovelType.EPUB -> EpubParser(file, charset(novel.nChapters))
}
override fun requestNovelChapters(): List<NovelChapter> {
val info = parser.parse()
update(novel, info)
return info.chapters.map {
NovelChapter(name = it.name, extra = it.extra)
}
}
override fun getNovelContent(chapter: NovelChapter, listener: ((Long, Long) -> Unit)?): List<String> {
// epub章节内容开头可能是章节名,过滤掉不要,
// 按理说是内容比章节名更适合保留着,但是不方便统一处理,
return parser.getNovelContent(LocalNovelChapter(name = chapter.name, extra = chapter.extra)).dropWhile { it == chapter.name }
}
override fun getContentUrl(chapter: NovelChapter): String {
return getDetailUrl()
}
override fun getDetailUrl(): String {
return file.toURI().toString()
}
override fun getImage(extra: String): URL {
return parser.getImage(extra)
}
override fun updateNovelDetail() {
// 不真的刷新什么,但是以防万一,chapters为null会反复调用这个方法,
if (novel.chapters == null) {
// 按理说没用,编码是一开始就决定好了写死的,不会为空,
novel.chapters = "null"
}
}
override fun cleanData() {
file.delete()
}
override fun cleanCache() {
// 没什么缓存文件可以删除的,
// 复制到内部的备份不方便删除,
}
companion object {
// 因为要在导入时和刷新章节列表时调用,所以写在伴生对象里,
fun update(novel: Novel, info: LocalNovelInfo) {
novel.apply {
checkUpdateTime = Date()
if (info.chapters.size > chaptersCount) {
// 本地导入小说按导入时间存一个receiveUpdateTime, 方便排序时算上,
receiveUpdateTime = checkUpdateTime
}
}
val list = info.chapters
novel.apply {
chaptersCount = list.size
if (readAtChapterIndex == 0) {
// 阅读至第一章代表没阅读过,保存第一章的章节名,
readAtChapterName = list.firstOrNull()?.name ?: "(null)"
}
lastChapterName = list.lastOrNull()?.name ?: "(null)"
}
}
}
} | gpl-3.0 | 341c08f4c936b4d7ee619108346272fe | 30.131868 | 133 | 0.597458 | 3.721419 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/report/pom/PomGenerator.kt | 2 | 3411 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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 io.spine.internal.gradle.report.pom
import org.gradle.api.Project
import org.gradle.api.plugins.BasePlugin
import org.gradle.kotlin.dsl.extra
/**
* Generates a `pom.xml` file that contains dependencies of the root project as
* well as the dependencies of its subprojects.
*
* Usage:
* ```
* PomGenerator.applyTo(project)
* ```
*
* The generated `pom.xml` is not usable for Maven build tasks and is merely a
* description of project dependencies.
*
* Configures the `build` task to generate the `pom.xml` file.
*
* Note that the generated `pom.xml` includes the group ID, artifact ID and the version of the
* project this script was applied to. In case you want to override the default values, do so in
* the `ext` block like so:
*
* ```
* ext {
* groupId = 'custom-group-id'
* artifactId = 'custom-artifact-id'
* version = 'custom-version'
* }
* ```
*
* By default, those values are taken from the `project` object, which may or may not include
* them. If the project does not have these values, and they are not specified in the `ext`
* block, the resulting `pom.xml` file is going to contain empty blocks, e.g. `<groupId></groupId>`.
*/
@Suppress("unused")
object PomGenerator {
/**
* Configures the generator for the passed [project].
*/
fun applyTo(project: Project) {
/**
* In some cases, the `base` plugin, which is by default is added by e.g. `java`,
* is not yet added. `base` plugin defines the `build` task. This generator needs it.
*/
project.apply {
plugin(BasePlugin::class.java)
}
val task = project.tasks.create("generatePom")
task.doLast {
val pomFile = project.projectDir.resolve("pom.xml")
project.delete(pomFile)
val projectData = project.metadata()
val writer = PomXmlWriter(projectData)
writer.writeTo(pomFile)
}
val buildTask = project.tasks.findByName("build")!!
buildTask.finalizedBy(task)
val assembleTask = project.tasks.findByName("assemble")!!
task.dependsOn(assembleTask)
}
}
| apache-2.0 | 9575d414a1aaadd8cff6daf054e0bc97 | 34.905263 | 100 | 0.687482 | 4.12954 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/ui/eventlog/EventLogClientFragment.kt | 2 | 5432 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.ui.eventlog
import android.os.Bundle
import android.os.RemoteException
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import edu.berkeley.boinc.adapter.ClientLogRecyclerViewAdapter
import edu.berkeley.boinc.databinding.EventLogClientLayoutBinding
import edu.berkeley.boinc.rpc.Message
import edu.berkeley.boinc.utils.Logging
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class EventLogClientFragment : Fragment() {
private lateinit var activity: EventLogActivity
private var _binding: EventLogClientLayoutBinding? = null
private val binding get() = _binding!!
private var mostRecentSeqNo = 0
private var pastSeqNo = -1 // oldest (lowest) seqNo currently loaded to GUI
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
activity = getActivity() as EventLogActivity
_binding = EventLogClientLayoutBinding.inflate(inflater, container, false)
activity.clientLogList = binding.clientLogList
activity.clientLogRecyclerViewAdapter = ClientLogRecyclerViewAdapter(activity.clientLogData)
activity.clientLogList.layoutManager = LinearLayoutManager(context)
activity.clientLogList.adapter = activity.clientLogRecyclerViewAdapter
binding.root.setOnRefreshListener { update() }
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
fun init() {
lifecycleScope.launch {
retrievePastClientMessages() // read messages
}
}
fun update() {
lifecycleScope.launch {
retrieveRecentClientMessages() // refresh messages
}
}
private suspend fun retrieveRecentClientMessages() {
if (activity.clientLogData.isNotEmpty()) {
mostRecentSeqNo = activity.clientLogData[0].seqno
}
coroutineScope {
val messages = withContext(Dispatchers.Default) {
return@withContext try {
(getActivity() as EventLogActivity).monitorService.getMessages(mostRecentSeqNo)
} catch (e: RemoteException) {
e.printStackTrace()
emptyList<Message>()
}
}
try {
for ((y, x) in messages.indices.reversed().withIndex()) {
activity.clientLogData.add(y, messages[x])
}
} catch (e: Exception) {
Logging.logException(Logging.Category.CLIENT, "EventLogClientFragment.loadRecentMsgs error: ", e)
} //IndexOutOfBoundException
activity.clientLogRecyclerViewAdapter.notifyDataSetChanged()
withContext(Dispatchers.Main) { binding.root.isRefreshing = false }
}
}
private suspend fun retrievePastClientMessages() {
if (activity.clientLogData.isNotEmpty()) {
pastSeqNo = activity.clientLogData.last().seqno
if (pastSeqNo == 0) {
Logging.logDebug(Logging.Category.CLIENT, "cancel, oldest messages already loaded")
return // cancel if all past messages are present
}
}
// message retrieval
// amount messages loaded when end of list is reached
val pastMsgsLoadingRange = 50
Logging.logDebug(Logging.Category.CLIENT, "calling monitor with: " + pastSeqNo + " / " +
pastMsgsLoadingRange)
coroutineScope {
val messages = withContext(Dispatchers.Default) {
return@withContext try {
(getActivity() as EventLogActivity).monitorService.getEventLogMessages(pastSeqNo,
pastMsgsLoadingRange)
} catch (e: RemoteException) {
e.printStackTrace()
emptyList<Message>()
}
}
// back in UI thread
// Append old messages to the event log
try {
activity.clientLogData.addAll(messages.reversed())
} catch (e: Exception) {
Logging.logException(Logging.Category.CLIENT, "EventLogClientFragment.loadPastMsgs error: ", e)
} //IndexOutOfBoundException
activity.clientLogRecyclerViewAdapter.notifyDataSetChanged()
}
}
}
| lgpl-3.0 | 5c9bd0fd4db9c1ccee44df19f8e0322e | 37.8 | 116 | 0.660898 | 5.114878 | false | false | false | false |
langara/MyIntent | myintent/src/main/java/pl/mareklangiewicz/myintent/MIActivityAnimations.kt | 1 | 2915 | package pl.mareklangiewicz.myintent
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.os.Build
import android.view.View
import android.view.animation.LinearInterpolator
import pl.mareklangiewicz.mydrawables.MyMagicLinesDrawable
/**
* Created by Marek Langiewicz on 11.03.16.
* Some animations used in MIActivity
*/
internal class MIActivityAnimations(private val mlogo: MagicLogo, private val mhomepage: MagicHomePage, private val mlines: MagicLines) {
constructor(logo: View, homepage: View, lines: View, lcolor: Int, lwidth: Float)
: this(MagicLogo(logo), MagicHomePage(homepage), MagicLines(lcolor, lwidth)) {
lines.background = mlines
}
fun onGlobalDrawerOpened() { mlines.start() }
fun onGlobalDrawerClosed() { mlines.stop() }
fun onGlobalDrawerSlide(offset: Float) {
mlogo.offset = offset
mhomepage.offset = offset
}
/**
* Some simple logo animation
*/
internal class MagicLogo(logo: View) {
private val animator = ObjectAnimator.ofPropertyValuesHolder(logo,
PropertyValuesHolder.ofFloat(View.ALPHA, 0f, 0.2f, 1f),
PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, -130f, -30f, 0f)
).apply {
interpolator = LinearInterpolator()
}
var offset: Float = 0f
set(value) {
field = value
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
animator.setCurrentFraction(value)
}
}
/**
* Some simple home page presentation/animation
*/
internal class MagicHomePage(homepage: View) {
private val animator = ObjectAnimator.ofPropertyValuesHolder(
homepage,
PropertyValuesHolder.ofFloat(View.ALPHA, 0f, 0f, 0.7f),
PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, -50f, -50f, 0f)
).apply {
interpolator = LinearInterpolator()
}
var offset: Float = 0f
set(value) {
field = value
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
animator.setCurrentFraction(value)
}
}
/**
* Little animated drawable to make header view more interesting
*/
internal class MagicLines(acolor: Int, width: Float, duration: Long = 1000) : MyMagicLinesDrawable() {
private val animator = ObjectAnimator.ofInt(this, "level", 0, 10000).apply {
setDuration(duration)
interpolator = LinearInterpolator()
}
init {
color = acolor
strokeWidth = width
}
fun start() {
if (!animator.isStarted)
animator.start()
}
fun stop() {
animator.cancel()
level = 0
}
}
}
| apache-2.0 | 11c0d10a465b576116da6207d01d2d6d | 29.051546 | 137 | 0.608919 | 4.484615 | false | false | false | false |
bozaro/git-as-svn | src/test/kotlin/svnserver/replay/SVNEditorWrapper.kt | 1 | 3253 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.replay
import org.testng.Assert
import org.tmatesoft.svn.core.SVNCommitInfo
import org.tmatesoft.svn.core.SVNPropertyValue
import org.tmatesoft.svn.core.io.ISVNEditor
import org.tmatesoft.svn.core.io.diff.SVNDiffWindow
import java.io.OutputStream
/**
* Simple transparent wrapper for ISVNEditor.
*
* @author a.navrotskiy
*/
abstract class SVNEditorWrapper(private val editor: ISVNEditor?, private val checkDelete: Boolean) : ISVNEditor {
// Allow removing directory entries only before creation/updating (issue #123).
private var allowDelete = false
override fun targetRevision(revision: Long) {
editor?.targetRevision(revision)
}
override fun openRoot(revision: Long) {
editor?.openRoot(revision)
allowDelete = true
}
override fun deleteEntry(path: String, revision: Long) {
editor?.deleteEntry(path, revision)
if (checkDelete) {
Assert.assertTrue(allowDelete, "Removing from $path#$revision is not allowed")
}
}
override fun absentDir(path: String) {
editor?.absentDir(path)
}
override fun absentFile(path: String) {
editor?.absentFile(path)
}
override fun addDir(path: String, copyFromPath: String?, copyFromRevision: Long) {
editor?.addDir(path, copyFromPath, copyFromRevision)
allowDelete = true
}
override fun openDir(path: String, revision: Long) {
editor?.openDir(path, revision)
allowDelete = true
}
override fun changeDirProperty(name: String, value: SVNPropertyValue) {
editor?.changeDirProperty(name, value)
}
override fun closeDir() {
editor?.closeDir()
allowDelete = false
}
override fun addFile(path: String, copyFromPath: String?, copyFromRevision: Long) {
editor?.addFile(path, copyFromPath, copyFromRevision)
allowDelete = false
}
override fun openFile(path: String, revision: Long) {
editor?.openFile(path, revision)
allowDelete = false
}
override fun changeFileProperty(path: String, propertyName: String, propertyValue: SVNPropertyValue?) {
editor?.changeFileProperty(path, propertyName, propertyValue)
}
override fun closeFile(path: String, textChecksum: String) {
editor?.closeFile(path, textChecksum)
}
override fun closeEdit(): SVNCommitInfo? {
return editor?.closeEdit()
}
override fun abortEdit() {
editor?.abortEdit()
}
override fun applyTextDelta(path: String, baseChecksum: String?) {
editor?.applyTextDelta(path, baseChecksum)
}
override fun textDeltaChunk(path: String, diffWindow: SVNDiffWindow): OutputStream? {
return editor?.textDeltaChunk(path, diffWindow)
}
override fun textDeltaEnd(path: String) {
editor?.textDeltaEnd(path)
}
}
| gpl-2.0 | 7a36aff54aa4083e8643190b1195b92a | 29.688679 | 113 | 0.686443 | 4.186615 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/htl/highlighting/HtlHighlighterColors.kt | 1 | 1226 | package co.nums.intellij.aem.htl.highlighting
import com.intellij.openapi.editor.*
import com.intellij.openapi.editor.colors.*
object HtlHighlighterColors {
val GLOBAL_OBJECT = TextAttributesKey.createTextAttributesKey("GLOBAL_OBJECT", DefaultLanguageHighlighterColors.LOCAL_VARIABLE)
val BLOCK_TYPE = TextAttributesKey.createTextAttributesKey("BLOCK_TYPE", XmlHighlighterColors.HTML_ATTRIBUTE_NAME)
val VARIABLE = TextAttributesKey.createTextAttributesKey("VARIABLE", DefaultLanguageHighlighterColors.LOCAL_VARIABLE)
val UNREFERENCED_IDENTIFIER = TextAttributesKey.createTextAttributesKey("UNREFERENCED_IDENTIFIER", CodeInsightColors.WRONG_REFERENCES_ATTRIBUTES)
val USE_DECLARATION = TextAttributesKey.createTextAttributesKey("USE_DECLARATION", DefaultLanguageHighlighterColors.CLASS_NAME)
val PROPERTY_ACCESS = TextAttributesKey.createTextAttributesKey("PROPERTY_ACCESS", DefaultLanguageHighlighterColors.INSTANCE_FIELD)
val OPTION_NAME = TextAttributesKey.createTextAttributesKey("OPTION_NAME", DefaultLanguageHighlighterColors.LOCAL_VARIABLE)
val TEMPLATE_IDENTIFIER = TextAttributesKey.createTextAttributesKey("TEMPLATE_IDENTIFIER", DefaultLanguageHighlighterColors.LOCAL_VARIABLE)
}
| gpl-3.0 | a6d65444f5d2c3a459fb492b73653a6d | 71.117647 | 149 | 0.843393 | 5.894231 | false | false | false | false |
Egorand/kotlin-playground | src/me/egorand/kotlin/playground/basics/Labels.kt | 1 | 1659 | /*
* Copyright 2016 Egor Andreevici
*
* 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.egorand.kotlin.playground.basics
fun breakOuterLoop() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (i > 1 && j > 1) {
break@outer
}
println("i = $i, j = $j")
}
}
}
fun returnFromLambda() {
val ints = arrayOf(1, 2, 0, 3)
ints.forEach {
if (it == 0) return
println(it)
}
println("Won't be printed!")
}
fun returnFromLambda2() {
val ints = arrayOf(1, 2, 0, 3)
ints.forEach loop@ {
if (it == 0) return@loop
println(it)
}
println("Will be printed!")
}
fun returnFromLambda3() {
val ints = arrayOf(1, 2, 0, 3)
ints.forEach {
if (it == 0) return@forEach
println(it)
}
println("Will be printed!")
}
fun returnFromLambda4() {
val ints = arrayOf(1, 2, 0, 3)
ints.forEach(fun(value: Int) {
if (value == 0) return
println(value)
})
println("Will be printed!")
}
fun main(args: Array<String>) {
breakOuterLoop()
returnFromLambda()
returnFromLambda2()
returnFromLambda3()
returnFromLambda4()
} | apache-2.0 | ac0968e01b7675058cacb93713f8587e | 21.739726 | 80 | 0.624473 | 3.385714 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/auth/legal/LegalAgreementActivity.kt | 1 | 4045 | /*
* Copyright (c) 2019 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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 ffc.app.auth.legal
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.os.Bundle
import ffc.android.observe
import ffc.android.viewModel
import ffc.api.ApiErrorException
import ffc.api.FfcCentral
import ffc.app.FamilyFolderActivity
import ffc.app.MainActivity
import ffc.app.R
import ffc.app.util.alert.handle
import org.jetbrains.anko.startActivity
import retrofit2.dsl.enqueue
class LegalAgreementActivity : FamilyFolderActivity() {
val api = FfcCentral().service<LegalAgreementApi>()
val viewModel by lazy { viewModel<AgreementViewModel>() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.legal_activity)
observe(viewModel.activeType) {
if (it == null) {
startActivity<MainActivity>()
overridePendingTransition(0, R.anim.design_bottom_sheet_slide_out)
finish()
} else {
val fragment = LegalAgreementFragment().apply {
legalDocCall = api.latest(it)
onAccept = { version ->
api.agreeWith(it, version, currentUser!!.id, currentUser!!.orgId!!).enqueue {
onSuccess {
val queue = viewModel.queueType.value
queue?.remove(it)
viewModel.activeType.value = queue?.getOrNull(0)
}
onError { viewModel.exception.value = ApiErrorException(this) }
onFailure { viewModel.exception.value = it }
}
}
}
supportFragmentManager.beginTransaction().replace(R.id.contentContainer, fragment).commit()
}
}
observe(viewModel.exception) {
it?.let { handle(it) }
}
viewModel.queueType.value = mutableListOf()
if (currentUser != null) {
checkAgreement(LegalType.privacy)
checkAgreement(LegalType.terms)
}
}
private val requireDoc = 2
private var responseDoc = 0
set(value) {
if (value == requireDoc) {
viewModel.activeType.value = viewModel.queueType.value?.getOrNull(0)
}
field = value
}
private fun checkAgreement(type: LegalType) {
api.checkAgreement(type, currentUser!!.id, currentUser!!.orgId!!).enqueue {
onSuccess { /* Do nothing */ }
onError {
when (code()) {
404 -> viewModel.queueType.value!!.add(type)
else -> viewModel.exception.value = ApiErrorException(this)
}
}
onFailure { viewModel.exception.value = it }
finally { responseDoc++ }
}
}
override fun onBackPressed() {
super.onBackPressed()
overridePendingTransition(0, R.anim.design_bottom_sheet_slide_out)
}
class AgreementViewModel : ViewModel() {
val queueType: MutableLiveData<MutableList<LegalType>> = MutableLiveData()
val activeType: MutableLiveData<LegalType> = MutableLiveData()
val exception: MutableLiveData<Throwable> = MutableLiveData()
}
}
| apache-2.0 | 5b7606900f9f4a531929cecf9ce3d0bd | 35.772727 | 107 | 0.607169 | 4.957108 | false | false | false | false |
Ribesg/anko | preview/intentions/src/org/jetbrains/anko/idea/intentions/AnkoIntention.kt | 1 | 6008 | package org.jetbrains.anko.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.resolveTopLevelClass
import org.jetbrains.kotlin.types.lowerIfFlexible
abstract class AnkoIntention<TElement : KtElement>(
elementType: Class<TElement>,
text: String,
familyName: String = text
) : SelfTargetingIntention<TElement>(elementType, text, familyName) {
final override fun isApplicableTo(element: TElement, caretOffset: Int): Boolean {
val file = element.containingFile as? KtFile ?: return false
val moduleDescriptor = file.findModuleDescriptor()
moduleDescriptor.resolveTopLevelClass(ANKO_INTERNALS_FQNAME, NoLookupLocation.FROM_IDE) ?: return false
return isApplicable(element, caretOffset)
}
abstract fun isApplicable(element: TElement, caretOffset: Int): Boolean
private fun isTypeOf(descriptor: ClassifierDescriptor, vararg fqName: String): Boolean {
val resolvedName = DescriptorUtils.getFqNameSafe(descriptor).asString()
return fqName.any { it == resolvedName }
}
protected fun KtCallExpression.isValueParameterTypeOf(
parameterIndex: Int,
resolvedCall: ResolvedCall<*>?,
vararg fqName: String
): Boolean {
val ctxArgumentDescriptor = (resolvedCall ?: getResolvedCall(analyze()))?.resultingDescriptor
?.valueParameters?.get(parameterIndex)?.type?.lowerIfFlexible()
?.constructor?.declarationDescriptor ?: return false
return isTypeOf(ctxArgumentDescriptor, *fqName)
}
protected fun KtCallExpression.isReceiverParameterTypeOf(
resolvedCall: ResolvedCall<*>?,
vararg fqName: String
): Boolean {
val receiverDescriptor = (resolvedCall ?: getResolvedCall(analyze()))?.resultingDescriptor
?.dispatchReceiverParameter?.type?.lowerIfFlexible()
?.constructor?.declarationDescriptor ?: return false
return isTypeOf(receiverDescriptor, *fqName)
}
protected val KtDotQualifiedExpression.receiver: KtExpression?
get() = receiverExpression
protected val KtDotQualifiedExpression.selector: KtExpression?
get() = selectorExpression
protected val KtBinaryExpressionWithTypeRHS.operation: KtSimpleNameExpression
get() = operationReference
protected inline fun <reified E : PsiElement> PsiElement?.require(name: String? = null, sub: E.() -> Boolean): Boolean {
return require<E>(name) && (this as E).sub()
}
inline fun require(cond: Boolean, sub: () -> Boolean): Boolean {
if (cond) sub()
return cond
}
protected inline fun <reified E : PsiElement> PsiElement?.require(name: String? = null): Boolean {
if (this !is E) return false
if (name != null && name != this.text) return false
return true
}
protected inline fun PsiElement?.requireCall(
functionName: String? = null,
argCount: Int? = null,
sub: KtCallExpression.() -> Boolean
): Boolean {
return requireCall(functionName, argCount) && (this as KtCallExpression).sub()
}
@Suppress("NOTHING_TO_INLINE")
protected inline fun PsiElement?.requireCall(functionName: String? = null, argCount: Int? = null): Boolean {
if (this !is KtCallExpression) return false
if (functionName != null && functionName != calleeExpression?.text) return false
if (argCount != null && argCount != valueArguments.size) return false
return true
}
abstract fun replaceWith(element: TElement, psiFactory: KtPsiFactory): NewElement?
final override fun applyTo(element: TElement, editor: Editor?) {
val project = editor?.project ?: return
val file = element.containingFile as? KtFile ?: return
val moduleDescriptor = file.findModuleDescriptor()
val resolutionFacade = file.getResolutionFacade()
val psiFactory = KtPsiFactory(project)
val (newElement, fqNamesToImport) = replaceWith(element, psiFactory) ?: return
val newExpression = newElement
ImportInsertHelper.getInstance(project).apply {
fqNamesToImport
.flatMap {
val fqName = FqName(if ('.' in it) it else "$ANKO_PACKAGE$it")
resolutionFacade.resolveImportReference(moduleDescriptor, fqName)
}
.forEach { if (it.importableFqName != null) importDescriptor(file, it) }
}
element.replace(newExpression)
}
private companion object {
private val ANKO_PACKAGE = "org.jetbrains.anko."
private val ANKO_INTERNALS_FQNAME = FqName("org.jetbrains.anko.internals.AnkoInternals")
}
}
object FqNames {
val ACTIVITY_FQNAME = "android.app.Activity"
val CONTEXT_FQNAME = "android.content.Context"
val VIEW_FQNAME = "android.view.View"
}
class NewElement(val element: KtExpression, vararg val newNames: String) {
operator fun component1() = element
operator fun component2() = newNames //fqName or name in anko package
} | apache-2.0 | 9b3ffe9ff24b097a5a2c6d7142cf65a6 | 41.020979 | 124 | 0.700399 | 5.130658 | false | false | false | false |
SirWellington/alchemy-generator | src/test/java/tech/sirwellington/alchemy/generator/ChecksTest.kt | 1 | 3347 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.generator
import org.apache.commons.lang3.RandomStringUtils
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import tech.sirwellington.alchemy.generator.Throwables.assertThrows
/**
* @author SirWellington
*/
@RunWith(MockitoJUnitRunner::class)
class ChecksTest
{
private lateinit var message: String
@Before
fun setUp()
{
message = "some message"
}
@Test
fun testCheckNotNull()
{
println("testCheckNotNull")
val `object` = Any()
checkNotNull(`object`)
checkNotNull(`object`, message)
}
@Test(expected = IllegalArgumentException::class)
fun testCheckNotNullExpecting()
{
println("testCheckNotNullExpecting")
checkNotNull(null)
}
@Test(expected = IllegalArgumentException::class)
fun testCheckNotNullExpectingWithMessage()
{
println("testCheckNotNullExpectingWithMessage")
checkNotNull(null, message)
}
@Test
fun testCheckThat()
{
println("testCheckThat")
checkThat(true)
checkThat(true, message)
}
@Test(expected = IllegalArgumentException::class)
fun testCheckThatExpecting()
{
println("testCheckThatExpecting")
checkThat(false)
}
@Test(expected = IllegalArgumentException::class)
fun testCheckThatExpectingWithMessage()
{
println("testCheckThatExpectingWithMessage")
checkThat(false, message)
}
@Test
fun testCheckNotEmptyString()
{
println("testCheckNotEmptyString")
val string = RandomStringUtils.randomAlphanumeric(10)
checkNotEmpty(string)
val nullString: String? = null
assertThrows { checkNotEmpty(nullString) }
.isInstanceOf(IllegalArgumentException::class.java)
val emptyString = ""
assertThrows { checkNotEmpty(emptyString) }
.isInstanceOf(IllegalArgumentException::class.java)
}
@Test
fun testCheckNotEmptyStringWithMessage()
{
println("testCheckNotEmptyStringWithMessage")
val message = RandomStringUtils.randomAlphabetic(100)
val string = RandomStringUtils.randomAscii(10)
checkNotEmpty(string, message)
checkNotEmpty(string, null)
checkNotEmpty(string, "")
val nullString: String? = null
assertThrows { checkNotEmpty(nullString, message) }
.isInstanceOf(IllegalArgumentException::class.java)
val emptyString = ""
assertThrows { checkNotEmpty(emptyString, message) }
.isInstanceOf(IllegalArgumentException::class.java)
}
}
| apache-2.0 | d7e2175e43ee199bd3a741cb7fff01cd | 25.346457 | 75 | 0.67902 | 4.964392 | false | true | false | false |
pyamsoft/pasterino | app/src/main/java/com/pyamsoft/pasterino/settings/AppSettings.kt | 1 | 5066 | /*
* Copyright 2021 Peter Kenji Yamanaka
*
* 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.pyamsoft.pasterino.settings
import android.os.Bundle
import androidx.annotation.CheckResult
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.pyamsoft.pasterino.PasterinoComponent
import com.pyamsoft.pasterino.PasterinoViewModelFactory
import com.pyamsoft.pasterino.R
import com.pyamsoft.pasterino.main.ToolbarViewModel
import com.pyamsoft.pydroid.core.requireNotNull
import com.pyamsoft.pydroid.inject.Injector
import com.pyamsoft.pydroid.ui.preference.Preferences
import com.pyamsoft.pydroid.ui.preference.checkBoxPreference
import com.pyamsoft.pydroid.ui.preference.listPreference
import com.pyamsoft.pydroid.ui.preference.preferenceGroup
import com.pyamsoft.pydroid.ui.settings.SettingsFragment
import javax.inject.Inject
import com.pyamsoft.pasterino.service.R as R2
class AppSettings : SettingsFragment() {
override val hideClearAll: Boolean = false
override val hideUpgradeInformation: Boolean = false
@JvmField @Inject internal var factory: PasterinoViewModelFactory? = null
private val toolbarViewModel by
activityViewModels<ToolbarViewModel> { factory.requireNotNull().create(this) }
private val viewModel by
activityViewModels<SettingsViewModel> { factory.requireNotNull().create(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Injector.obtainFromApplication<PasterinoComponent>(requireActivity())
.plusAppSettings()
.create()
.inject(this)
}
@Composable
override fun customBottomItemMargin(): Dp {
// Additional bottom padding based on the size of the measured FAB space
val state by toolbarViewModel.compose()
val density = LocalDensity.current
val bottomSpaceHeight = state.bottomSpaceHeight
return remember(bottomSpaceHeight) { density.run { bottomSpaceHeight.toDp() } }
}
@Composable
override fun customPostPreferences(): List<Preferences> {
return emptyList()
}
@Composable
override fun customPrePreferences(): List<Preferences> {
val state by viewModel.compose()
val rawDelayTime = state.delayTime
val delayTime =
if (rawDelayTime == 0L) stringResource(R2.string.delay_time_default_v2)
else rawDelayTime.toString()
val isDeepSearch: Boolean = state.isDeepSearch
val names = stringArrayResource(R.array.delay_time_names_v2)
val values = stringArrayResource(R.array.delay_time_values_v2)
return listOf(
preferenceGroup(
name = "Notification Settings",
preferences =
listOf(
listPreference(
name = stringResource(R.string.delay_time_title),
summary = stringResource(R.string.delay_time_summary),
icon = R.drawable.ic_timer_24dp,
value = delayTime,
entries = names.mapIndexed { index, name -> name to values[index] }.toMap(),
onPreferenceSelected = { _, value ->
viewModel.handleDelayTimeChanged(value.toLong())
},
),
checkBoxPreference(
name = stringResource(R.string.deep_search_title),
summary = stringResource(R.string.deep_search_summary_on),
icon = R.drawable.ic_timer_24dp,
checked = isDeepSearch,
onCheckedChanged = { viewModel.handleDeepSearchChanged(it) }),
),
),
)
}
@Composable
override fun customTopItemMargin(): Dp {
// Additional top padding based on the size of the measured Top App Bar
val state by toolbarViewModel.compose()
val density = LocalDensity.current
val topBarHeight = state.topBarHeight
return remember(topBarHeight) { density.run { topBarHeight.toDp() } }
}
companion object {
const val TAG = "AppSettings"
@JvmStatic
@CheckResult
internal fun newInstance(): Fragment {
return AppSettings().apply { arguments = Bundle().apply {} }
}
}
}
| apache-2.0 | 985957209b03e639aa01b16021814973 | 35.978102 | 100 | 0.698579 | 4.725746 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsImageTagEditActivity.kt | 1 | 4242 | package org.wikipedia.suggestededits
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.fragment.app.Fragment
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.BaseActivity
import org.wikipedia.databinding.ActivitySuggestedEditsFeedCardImageTagsBinding
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.descriptions.DescriptionEditActivity
import org.wikipedia.json.JsonUtil
import org.wikipedia.settings.Prefs
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.ResourceUtil
class SuggestedEditsImageTagEditActivity : BaseActivity(), SuggestedEditsItemFragment.Callback {
private lateinit var binding: ActivitySuggestedEditsFeedCardImageTagsBinding
private var suggestedEditsImageTagsFragment: SuggestedEditsImageTagsFragment? = null
var page: MwQueryPage? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySuggestedEditsFeedCardImageTagsBinding.inflate(layoutInflater)
setContentView(binding.root)
page = JsonUtil.decodeFromString(intent.getStringExtra(ARG_PAGE))
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.title = getString(R.string.suggested_edits_tag_images)
setImageZoomHelper()
suggestedEditsImageTagsFragment = supportFragmentManager.findFragmentById(R.id.imageTagFragment) as SuggestedEditsImageTagsFragment?
suggestedEditsImageTagsFragment?.invokeSource = intent.getSerializableExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE) as Constants.InvokeSource
binding.addContributionButton.setOnClickListener { suggestedEditsImageTagsFragment!!.publish() }
binding.addContributionLandscapeImage.setOnClickListener { suggestedEditsImageTagsFragment!!.publish() }
maybeShowOnboarding()
}
override fun getLangCode(): String {
return WikipediaApp.instance.languageState.appLanguageCode
}
override fun getSinglePage(): MwQueryPage? {
return page
}
override fun updateActionButton() {
if (suggestedEditsImageTagsFragment != null) {
binding.addContributionLandscapeImage.setBackgroundColor(ResourceUtil.getThemedColor(this, R.attr.colorAccent))
binding.addContributionButton.isEnabled = suggestedEditsImageTagsFragment!!.publishEnabled()
binding.addContributionLandscapeImage.isEnabled = suggestedEditsImageTagsFragment!!.publishEnabled()
binding.addContributionButton.alpha = if (suggestedEditsImageTagsFragment!!.publishEnabled()) 1f else 0.5f
binding.addContributionLandscapeImage.alpha = if (suggestedEditsImageTagsFragment!!.publishEnabled()) 1f else 0.5f
}
if (DimenUtil.isLandscape(this)) {
binding.addContributionButton.visibility = GONE
binding.addContributionLandscapeImage.visibility = VISIBLE
} else {
binding.addContributionButton.visibility = VISIBLE
binding.addContributionLandscapeImage.visibility = GONE
binding.addContributionText.text = getString(R.string.description_edit_save)
}
}
override fun nextPage(sourceFragment: Fragment?) {
setResult(RESULT_OK, Intent().putExtra(Constants.INTENT_EXTRA_ACTION, DescriptionEditActivity.Action.ADD_IMAGE_TAGS))
finish()
}
override fun logSuccess() {
}
private fun maybeShowOnboarding() {
if (Prefs.showImageTagsOnboarding) {
Prefs.showImageTagsOnboarding = false
startActivity(SuggestedEditsImageTagsOnboardingActivity.newIntent(this))
}
}
companion object {
private const val ARG_PAGE = "imageTagPage"
fun newIntent(context: Context, page: MwQueryPage, invokeSource: Constants.InvokeSource): Intent {
return Intent(context, SuggestedEditsImageTagEditActivity::class.java)
.putExtra(ARG_PAGE, JsonUtil.encodeToString(page))
.putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, invokeSource)
}
}
}
| apache-2.0 | eefe27e56a535dee34926035ca23aac7 | 43.1875 | 147 | 0.753182 | 5.256506 | false | false | false | false |
joeygibson/raspimorse | src/main/kotlin/com/joeygibson/raspimorse/Main.kt | 1 | 5397 | package com.joeygibson.raspimorse
/*
* MIT License
*
* Copyright (c) 2017 Joey Gibson
*
* 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.
*/
import com.diozero.Button
import com.diozero.LED
import com.diozero.api.GpioPullUpDown
import com.joeygibson.raspimorse.decoder.DefaultMorseCodeDecoder
import com.joeygibson.raspimorse.reader.CalibrationKeyReader
import com.joeygibson.raspimorse.reader.TelegraphKeyWithLEDReader
import com.joeygibson.raspimorse.util.Config
import com.joeygibson.raspimorse.util.from
import com.natpryce.hamkrest.should.describedAs
import joptsimple.OptionParser
import mu.KotlinLogging
import kotlin.system.exitProcess
val logger = KotlinLogging.logger {}
fun main(args: Array<String>) {
val optParser = OptionParser()
val keyOpt = optParser.accepts("key")
.withRequiredArg()
.ofType(Int::class.java)
.describedAs("The pin number the telegraph key connects to")
.defaultsTo(17)
val ledOpt = optParser.accepts("led")
.withRequiredArg()
.ofType(Int::class.java)
.describedAs("The pin number of the LED")
.defaultsTo(22)
val toleranceOpt = optParser.accepts("tolerance")
.withRequiredArg()
.ofType(Int::class.java)
.describedAs("Percent tolerance for durations")
.defaultsTo(10)
optParser.acceptsAll(listOf("properties", "props", "p"))
.withRequiredArg()
.describedAs("properties file with pin assignments")
optParser.acceptsAll(listOf("help", "h", "?")).describedAs("show help screen")
val options = optParser.parse(*args)
if (options.has("help")) {
optParser.printHelpOn(System.out)
exitProcess(1)
}
val config = if (options.has("properties")) {
Config.from(options.valueOf("properties").toString())
} else {
if (!options.has("key") || !options.has("led")) {
System.err.println("You must specify the pins to use")
optParser.printHelpOn(System.out)
exitProcess(2)
}
val keyPin = options.valueOf(keyOpt)
val ledPin = options.valueOf(ledOpt)
val tolerance = options.valueOf(toleranceOpt)
Config(keyPin = keyPin, ledPin = ledPin, tolerance = tolerance)
}
logger.info { "Running with $config" }
val button = Button(config.keyPin, GpioPullUpDown.PULL_UP)
val led = LED(config.ledPin)
val (dotDuration, dashDuration) = calibrate(button)
println("Calibrated at: ($dotDuration, $dashDuration)")
val keyReader = TelegraphKeyWithLEDReader(led = led)
button.whenPressed { keyReader.pressed() }
button.whenReleased { keyReader.released() }
val decoder = DefaultMorseCodeDecoder(keyReader.asSequence(), dotDuration,
dashDuration, config.tolerance)
decoder.go()
while (true) {
while (!decoder.hasDecodedChars()) {
Thread.sleep(10)
}
val chars = decoder.decodedChars()
println(chars)
}
}
fun calibrate(button: Button): Pair<Long, Long> {
println("Calibrating.")
val calibrationLoops = 3
val keyReader = CalibrationKeyReader(calibrationLoops)
button.whenPressed { keyReader.pressed() }
button.whenReleased { keyReader.released() }
val durations = mutableListOf<Long>()
// First, dots
for (x in 1..calibrationLoops) {
println("Please key in the letter 's' [...]")
while (!keyReader.hasDataReady()) {
Thread.sleep(10)
}
val inputs = keyReader.asSequence().toList().map { it.duration }
val avgDuration = inputs.sum() / calibrationLoops
durations.add(avgDuration)
keyReader.reset()
}
val avgDotDuration = durations.average().toLong()
println("DOT: $avgDotDuration")
// Now dashes
durations.clear()
for (x in 1..calibrationLoops) {
println("Please key in the letter 'o' [---]")
while (!keyReader.hasDataReady()) {
Thread.sleep(10)
}
val inputs = keyReader.asSequence().toList().map { it.duration }
val avgDuration = inputs.sum() / calibrationLoops
durations.add(avgDuration)
keyReader.reset()
}
val avgDashDuration = durations.average().toLong()
return Pair(avgDotDuration, avgDashDuration)
}
| mit | f2d180704a73b55dd853e6ca65c01b1b | 30.196532 | 82 | 0.671299 | 4.067069 | false | false | false | false |
0legg/bodylookin | src/main/kotlin/net/olegg/lottie/idea/action/LoadAction.kt | 1 | 2238 | package net.olegg.lottie.idea.action
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.wm.ToolWindowManager
import net.olegg.lottie.idea.Constants
import net.olegg.lottie.idea.isJson
import net.olegg.lottie.idea.toolwindow.LottieIdeaView
/**
* Animation loading logic.
*/
class LoadAction : AnAction() {
override fun actionPerformed(event: AnActionEvent) {
val project = event.project
if (project == null || project.isDefault || project.isDisposed) {
return
}
val doc = event.getData(CommonDataKeys.EDITOR)?.document
val file = event.getData(CommonDataKeys.VIRTUAL_FILE)
val toolWindowManager = ToolWindowManager.getInstance(project)
val toolWindow = toolWindowManager.getToolWindow(Constants.TOOL_WINDOW_ID)
if (toolWindow.isVisible) {
val content = toolWindow.contentManager.getContent(0)?.component as? LottieIdeaView ?: return
if (doc != null) {
content.loadJson(doc.text)
} else if (file != null) {
content.loadFile(file)
}
} else {
toolWindow.show {
val content = toolWindow.contentManager.getContent(0)?.component as? LottieIdeaView ?: return@show
if (doc != null) {
content.loadJson(doc.text)
} else if (file != null) {
content.loadFile(file)
}
}
}
}
override fun update(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT)
if (project == null || project.isDefault || project.isDisposed) {
e.presentation.isEnabledAndVisible = false
return
}
val doc = e.getData(CommonDataKeys.EDITOR)?.document
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
val docJson = doc != null && doc.textLength > 0 && FileDocumentManager.getInstance().getFile(doc).isJson
e.presentation.isEnabledAndVisible = file.isJson || docJson
}
}
| mit | d2511f6fbab316bcbd53969bf2f5f3c5 | 38.263158 | 114 | 0.644325 | 4.691824 | false | false | false | false |
LivotovLabs/AndroidApplicationSkeleton | template-kotlin/mobile/src/main/java/extensions/calendar.kt | 1 | 1041 | import java.util.*
internal val MILLIS_PER_SECOND: Long = 1000
internal val MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND
internal val MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE
internal val MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR
fun Date.isYesterday(): Boolean
{
val cal1 = java.util.Calendar.getInstance()
cal1.add(java.util.Calendar.DAY_OF_YEAR, -1)
val cal2 = java.util.Calendar.getInstance()
cal2.time = this
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)
}
fun Date.isToday(): Boolean
{
val cal1 = java.util.Calendar.getInstance()
val cal2 = java.util.Calendar.getInstance()
cal2.time = this
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)
}
fun Date.sameDayAs(date: Date): Boolean
{
val julianDayNumber1 = this.time / MILLIS_PER_DAY
val julianDayNumber2 = date.time / MILLIS_PER_DAY
return julianDayNumber1 == julianDayNumber2
} | apache-2.0 | 5a4f474afb7a0eab7392538c07d4f1ad | 30.575758 | 129 | 0.710855 | 2.982808 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/io/pixeloutlaw/minecraft/spigot/mythicdrops/NamespacedKeys.kt | 1 | 2249 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2020 Richard Harrah
*
* 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 io.pixeloutlaw.minecraft.spigot.mythicdrops
import com.tealcube.minecraft.bukkit.mythicdrops.MythicDropsPlugin
import org.bukkit.NamespacedKey
/**
* Creates a [NamespacedKey] in the "MythicDrops" namespace in a "Spigot Approved"^TM way.
*
* @param key
*/
internal fun mythicDrops(key: String): NamespacedKey = NamespacedKey(MythicDropsPlugin.getInstance(), key)
/**
* The [NamespacedKey] used for storing which custom item is used.
*/
val mythicDropsCustomItem = mythicDrops("custom-item")
/**
* The [NamespacedKey] used for storing which socket gem is used.
*/
val mythicDropsSocketGem = mythicDrops("socket-gem")
/**
* The [NamespacedKey] used for storing which tier is used.
*/
val mythicDropsTier = mythicDrops("tier")
/**
* The [NamespacedKey] used for storing if the current item is a socket extender.
*/
val mythicDropsSocketExtender = mythicDrops("socket-extender")
/**
* The [NamespacedKey] used for storing if the current item has already been broadcast.
*/
val mythicDropsAlreadyBroadcast = mythicDrops("already-broadcast")
| mit | de9422444b71ea5439d11de8a670011a | 38.45614 | 106 | 0.761672 | 4.325 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve/Processors.kt | 2 | 13091 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.util.SmartList
import org.rust.lang.core.completion.RsCompletionContext
import org.rust.lang.core.completion.collectVariantsForEnumCompletion
import org.rust.lang.core.completion.createLookupElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.ref.MethodResolveVariant
import org.rust.lang.core.resolve2.RsModInfo
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.Substitution
import org.rust.lang.core.types.emptySubstitution
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.hasTyInfer
import org.rust.lang.core.types.ty.*
/**
* ScopeEntry is some PsiElement visible in some code scope.
*
* [ScopeEntry] handles the two case:
* * aliases (that's why we need a [name] property)
* * lazy resolving of actual elements (that's why [element] can return `null`)
*/
interface ScopeEntry {
val name: String
val element: RsElement?
val subst: Substitution get() = emptySubstitution
}
typealias RsProcessor<T> = (T) -> Boolean
interface RsResolveProcessorBase<in T : ScopeEntry> {
/**
* Return `true` to stop further processing,
* return `false` to continue search
*/
operator fun invoke(entry: T): Boolean
/**
* Indicates that processor is interested only in [ScopeEntry]s with specified [names].
* Improves performance for Resolve2.
* `null` in completion
*/
val names: Set<String>?
fun acceptsName(name: String): Boolean {
val names = names
return names == null || name in names
}
}
typealias RsResolveProcessor = RsResolveProcessorBase<ScopeEntry>
fun createProcessor(name: String? = null, processor: (ScopeEntry) -> Boolean): RsResolveProcessor =
createProcessorGeneric(name, processor)
fun createProcessor(names: Set<String>?, processor: (ScopeEntry) -> Boolean): RsResolveProcessor =
createProcessorGeneric(names, processor)
fun <T : ScopeEntry> createProcessorGeneric(
name: String? = null,
processor: (T) -> Boolean
): RsResolveProcessorBase<T> = createProcessorGeneric(name?.let { setOf(it) }, processor)
fun <T : ScopeEntry> createProcessorGeneric(
names: Set<String>? = null,
processor: (T) -> Boolean
): RsResolveProcessorBase<T> {
return object : RsResolveProcessorBase<T> {
override fun invoke(entry: T): Boolean = processor(entry)
override val names: Set<String>? = names
override fun toString(): String = "Processor(name=$names)"
}
}
typealias RsMethodResolveProcessor = RsResolveProcessorBase<MethodResolveVariant>
fun collectPathResolveVariants(
ctx: PathResolutionContext,
path: RsPath,
f: (RsResolveProcessor) -> Unit
): List<RsPathResolveResult<RsElement>> {
val referenceName = path.referenceName ?: return emptyList()
val result = SmartList<RsPathResolveResult<RsElement>>()
val processor = createProcessor(referenceName) { e ->
if (e.name == referenceName) {
collectPathScopeEntry(ctx, result, e)
}
false
}
f(processor)
return result
}
fun collectMultiplePathResolveVariants(
ctx: PathResolutionContext,
paths: List<RsPath>,
f: (RsResolveProcessor) -> Unit
): Map<RsPath, SmartList<RsPathResolveResult<RsElement>>> {
val result: MutableMap<RsPath, SmartList<RsPathResolveResult<RsElement>>> = hashMapOf()
val resultByName: MutableMap<String, SmartList<RsPathResolveResult<RsElement>>> = hashMapOf()
for (path in paths) {
val name = path.referenceName ?: continue
val list = resultByName.getOrPut(name) { SmartList() }
result[path] = list
}
val processor = createProcessor(resultByName.keys) { e ->
val list = resultByName[e.name]
if (list != null) {
collectPathScopeEntry(ctx, list, e)
}
false
}
f(processor)
return result
}
private fun collectPathScopeEntry(
ctx: PathResolutionContext,
result: MutableList<RsPathResolveResult<RsElement>>,
e: ScopeEntry
) {
val element = e.element ?: return
if (element !is RsDocAndAttributeOwner || element.existsAfterExpansionSelf) {
val visibilityStatus = e.getVisibilityStatusFrom(ctx.context, ctx.lazyContainingModInfo)
if (visibilityStatus != VisibilityStatus.CfgDisabled) {
val isVisible = visibilityStatus == VisibilityStatus.Visible
result += RsPathResolveResult(element, e.subst.foldTyInferWithTyPlaceholder(), isVisible)
}
}
}
// This is basically a hack - we replace type variables incorrectly created during name resolution
// TODO don't create `TyInfer.TyVar` during name resolution
private fun Substitution.foldTyInferWithTyPlaceholder(): Substitution =
foldWith(object : TypeFolder {
override fun foldTy(ty: Ty): Ty {
val foldedTy = if (ty is TyInfer.TyVar) {
if (ty.origin is RsInferType) {
TyPlaceholder(ty.origin)
} else {
TyUnknown
}
} else {
ty
}
return if (foldedTy.hasTyInfer) foldedTy.superFoldWith(this) else foldedTy
}
})
fun collectResolveVariants(referenceName: String?, f: (RsResolveProcessor) -> Unit): List<RsElement> {
if (referenceName == null) return emptyList()
val result = SmartList<RsElement>()
val processor = createProcessor(referenceName) { e ->
if (e.name == referenceName) {
val element = e.element ?: return@createProcessor false
if (element !is RsDocAndAttributeOwner || element.existsAfterExpansionSelf) {
result += element
}
}
false
}
f(processor)
return result
}
fun <T : ScopeEntry> collectResolveVariantsAsScopeEntries(
referenceName: String?,
f: (RsResolveProcessorBase<T>) -> Unit
): List<T> {
if (referenceName == null) return emptyList()
val result = mutableListOf<T>()
val processor = createProcessorGeneric<T>(referenceName) { e ->
if (e.name == referenceName) {
// de-lazying. See `RsResolveProcessor.lazy`
val element = e.element ?: return@createProcessorGeneric false
if (element !is RsDocAndAttributeOwner || element.existsAfterExpansionSelf) {
result += e
}
}
false
}
f(processor)
return result
}
fun pickFirstResolveVariant(referenceName: String?, f: (RsResolveProcessor) -> Unit): RsElement? =
pickFirstResolveEntry(referenceName, f)?.element
fun pickFirstResolveEntry(referenceName: String?, f: (RsResolveProcessor) -> Unit): ScopeEntry? {
if (referenceName == null) return null
var result: ScopeEntry? = null
val processor = createProcessor(referenceName) { e ->
if (e.name == referenceName) {
val element = e.element
if (element != null && (element !is RsDocAndAttributeOwner || element.existsAfterExpansionSelf)) {
result = e
return@createProcessor true
}
}
false
}
f(processor)
return result
}
fun collectCompletionVariants(
result: CompletionResultSet,
context: RsCompletionContext,
f: (RsResolveProcessor) -> Unit
) {
val processor = createProcessor { e ->
val element = e.element ?: return@createProcessor false
if (element is RsEnumItem
&& (context.expectedTy?.ty?.stripReferences() as? TyAdt)?.item == (element.declaredType as? TyAdt)?.item) {
val variants = collectVariantsForEnumCompletion(element, context, e.subst)
result.addAllElements(variants)
}
result.addElement(createLookupElement(
scopeEntry = e,
context = context
))
false
}
f(processor)
}
data class SimpleScopeEntry(
override val name: String,
override val element: RsElement,
override val subst: Substitution = emptySubstitution
) : ScopeEntry
data class ScopeEntryWithVisibility(
override val name: String,
override val element: RsElement,
/** Given a [RsElement] (usually [RsPath]) checks if this item is visible in `containingMod` of that element */
val visibilityFilter: VisibilityFilter,
override val subst: Substitution = emptySubstitution,
) : ScopeEntry
typealias VisibilityFilter = (RsElement, Lazy<RsModInfo?>?) -> VisibilityStatus
fun ScopeEntry.getVisibilityStatusFrom(context: RsElement, lazyModInfo: Lazy<RsModInfo?>?): VisibilityStatus =
if (this is ScopeEntryWithVisibility) {
visibilityFilter(context, lazyModInfo)
} else {
VisibilityStatus.Visible
}
fun ScopeEntry.isVisibleFrom(context: RsElement): Boolean =
getVisibilityStatusFrom(context, null) == VisibilityStatus.Visible
enum class VisibilityStatus {
Visible,
Invisible,
CfgDisabled,
}
interface AssocItemScopeEntryBase<out T : RsAbstractable> : ScopeEntry {
override val element: T
val selfTy: Ty
val source: TraitImplSource
}
data class AssocItemScopeEntry(
override val name: String,
override val element: RsAbstractable,
override val subst: Substitution = emptySubstitution,
override val selfTy: Ty,
override val source: TraitImplSource
) : AssocItemScopeEntryBase<RsAbstractable>
operator fun RsResolveProcessor.invoke(name: String, e: RsElement): Boolean =
this(SimpleScopeEntry(name, e))
operator fun RsResolveProcessor.invoke(
name: String,
e: RsElement,
visibilityFilter: VisibilityFilter
): Boolean = this(ScopeEntryWithVisibility(name, e, visibilityFilter))
inline fun RsResolveProcessor.lazy(name: String, e: () -> RsElement?): Boolean {
if (!acceptsName(name)) return false
val element = e() ?: return false
return this(name, element)
}
operator fun RsResolveProcessor.invoke(e: RsNamedElement): Boolean {
val name = e.name ?: return false
return this(name, e)
}
operator fun RsResolveProcessor.invoke(e: BoundElement<RsNamedElement>): Boolean {
val name = e.element.name ?: return false
return this(SimpleScopeEntry(name, e.element, e.subst))
}
fun processAll(elements: List<RsNamedElement>, processor: RsResolveProcessor): Boolean {
return elements.any { processor(it) }
}
fun processAllScopeEntries(elements: List<ScopeEntry>, processor: RsResolveProcessor): Boolean {
return elements.any { processor(it) }
}
fun processAllWithSubst(
elements: Collection<RsNamedElement>,
subst: Substitution,
processor: RsResolveProcessor
): Boolean {
for (e in elements) {
if (processor(BoundElement(e, subst))) return true
}
return false
}
fun filterNotCfgDisabledItemsAndTestFunctions(processor: RsResolveProcessor): RsResolveProcessor {
return createProcessor(processor.names) { e ->
val element = e.element ?: return@createProcessor false
if (element is RsFunction && element.isTest) return@createProcessor false
if (element is RsDocAndAttributeOwner && !element.existsAfterExpansionSelf) return@createProcessor false
processor(e)
}
}
fun filterCompletionVariantsByVisibility(context: RsElement, processor: RsResolveProcessor): RsResolveProcessor {
// Do not filter out private items in debugger
if (context.containingFile is RsDebuggerExpressionCodeFragment) {
return processor
}
val mod = context.containingMod
return createProcessor(processor.names) {
val element = it.element
if (element is RsVisible && !element.isVisibleFrom(mod)) return@createProcessor false
if (!it.isVisibleFrom(context)) return@createProcessor false
val isHidden = element is RsOuterAttributeOwner && element.queryAttributes.isDocHidden &&
element.containingMod != mod
if (isHidden) return@createProcessor false
processor(it)
}
}
fun filterNotAttributeAndDeriveProcMacros(processor: RsResolveProcessor): RsResolveProcessor =
createProcessor(processor.names) { e ->
val element = e.element
if (element is RsFunction && element.isProcMacroDef && !element.isBangProcMacroDef) return@createProcessor false
processor(e)
}
fun filterAttributeProcMacros(processor: RsResolveProcessor): RsResolveProcessor =
createProcessor(processor.names) { e ->
val function = e.element as? RsFunction ?: return@createProcessor false
if (!function.isAttributeProcMacroDef) return@createProcessor false
processor(e)
}
fun filterDeriveProcMacros(processor: RsResolveProcessor): RsResolveProcessor =
createProcessor(processor.names) { e ->
val function = e.element as? RsFunction ?: return@createProcessor false
if (!function.isCustomDeriveProcMacroDef) return@createProcessor false
processor(e)
}
| mit | 4ed6532ba0af387561c2f5f5d1e73aaa | 33.816489 | 120 | 0.694981 | 4.366578 | false | false | false | false |
applivery/applivery-android-sdk | applvsdklib/src/main/java/com/applivery/applvsdklib/domain/login/GetUserProfileInteractor.kt | 1 | 2008 | package com.applivery.applvsdklib.domain.login
import android.util.Log
import com.applivery.applvsdklib.domain.model.ErrorObject
import com.applivery.applvsdklib.tools.executor.InteractorExecutor
import com.applivery.applvsdklib.tools.executor.MainThread
import com.applivery.base.domain.SessionManager
import com.applivery.base.domain.model.UserProfile
import com.applivery.data.AppliveryApiService
import com.applivery.data.response.toDomain
import java.io.IOException
class GetUserProfileInteractor(
private val interactorExecutor: InteractorExecutor,
private val mainThread: MainThread,
private val apiService: AppliveryApiService,
private val sessionManager: SessionManager
) : Runnable {
lateinit var onSuccess: (UserProfile) -> Unit
lateinit var onError: (error: ErrorObject) -> Unit
fun getUser(
onSuccess: (UserProfile) -> Unit = {},
onError: (error: ErrorObject) -> Unit = {}
) {
this.onSuccess = onSuccess
this.onError = onError
interactorExecutor.run(this)
}
override fun run() {
try {
if (!sessionManager.hasSession()) {
notifyError(ErrorObject("Unauthorized"))
return
}
val user = apiService.getUser().execute().body()?.data?.toDomain()
if (user != null) {
notifySuccess(user)
} else {
Log.e(TAG, "Get profile response error")
notifyError(ErrorObject())
}
} catch (exception: IOException) {
Log.e(TAG, "getProfile() -> ${exception.message}")
notifyError(ErrorObject())
}
}
private fun notifySuccess(userProfile: UserProfile) {
mainThread.execute(Runnable { onSuccess(userProfile) })
}
private fun notifyError(error: ErrorObject) {
mainThread.execute(Runnable { onError(error) })
}
companion object {
private const val TAG = "GetProfileInteractor"
}
}
| apache-2.0 | f2c14f1ff9c854ac0025b8e9635ea21e | 29.892308 | 78 | 0.652888 | 4.780952 | false | false | false | false |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacRoundEnv.kt | 3 | 2310 | /*
* Copyright (C) 2020 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.room.compiler.processing.javac
import androidx.room.compiler.processing.XElement
import androidx.room.compiler.processing.XRoundEnv
import com.google.auto.common.MoreElements
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.Element
import kotlin.reflect.KClass
@Suppress("UnstableApiUsage")
internal class JavacRoundEnv(
private val env: JavacProcessingEnv,
val delegate: RoundEnvironment
) : XRoundEnv {
override val rootElements: Set<XElement> by lazy {
delegate.rootElements.map {
check(MoreElements.isType(it))
env.wrapTypeElement(MoreElements.asType(it))
}.toSet()
}
override val isProcessingOver: Boolean
get() = delegate.processingOver()
override fun getElementsAnnotatedWith(klass: KClass<out Annotation>): Set<XElement> {
val elements = delegate.getElementsAnnotatedWith(klass.java)
return wrapAnnotatedElements(elements, klass.java.canonicalName)
}
override fun getElementsAnnotatedWith(annotationQualifiedName: String): Set<XElement> {
if (annotationQualifiedName == "*") {
return emptySet()
}
val annotationTypeElement =
env.elementUtils.getTypeElement(annotationQualifiedName) ?: return emptySet()
val elements = delegate.getElementsAnnotatedWith(annotationTypeElement)
return wrapAnnotatedElements(elements, annotationQualifiedName)
}
private fun wrapAnnotatedElements(
elements: Set<Element>,
annotationName: String
): Set<XElement> {
return elements.map { env.wrapAnnotatedElement(it, annotationName) }.toSet()
}
}
| apache-2.0 | f4ca35622c696f4b148fea0c7b12f071 | 36.258065 | 91 | 0.729004 | 4.772727 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/OES_geometry_shader.kt | 1 | 6228 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
val OES_geometry_shader = "OESGeometryShader".nativeClassGLES("OES_geometry_shader", postfix = OES) {
documentation =
"""
Native bindings to the $registryLink extension.
OES_geometry_shader defines a new shader type available to be run on the GPU, called a geometry shader. Geometry shaders are run after vertices are
transformed, but prior to color clamping, flatshading and clipping.
A geometry shader begins with a single primitive (point, line, triangle). It can read the attributes of any of the vertices in the primitive and use
them to generate new primitives. A geometry shader has a fixed output primitive type (point, line strip, or triangle strip) and emits vertices to
define a new primitive. A geometry shader can emit multiple disconnected primitives. The primitives emitted by the geometry shader are clipped and then
processed like an equivalent primitive specified by the application.
Furthermore, OES_geometry_shader provides four additional primitive types: lines with adjacency, line strips with adjacency, separate triangles with
adjacency, and triangle strips with adjacency. Some of the vertices specified in these new primitive types are not part of the ordinary primitives,
instead they represent neighboring vertices that are adjacent to the two line segment end points (lines/strips) or the three triangle edges
(triangles/tstrips). These vertices can be accessed by geometry shaders and used to match up the vertices emitted by the geometry shader with those of
neighboring primitives.
Since geometry shaders expect a specific input primitive type, an error will occur if the application presents primitives of a different type. For
example, if a geometry shader expects points, an error will occur at drawing time if a primitive mode of TRIANGLES is specified.
This extension also adds the notion of layered framebuffer attachments and framebuffers that can be used in conjunction with geometry shaders to allow
programs to direct primitives to a face of a cube map or layer of a three-dimensional texture or two-dimensional array texture. The layer used for
rendering can be selected by the geometry shader at run time. The framebuffer layer count present in GL 4.x and removed from ES 3.1 is restored.
Not all geometry shader implementations have the ability to write the point size from a geometry shader. Thus a second extension string and shading
language enable are provided for implementations which do support geometry shader point size.
This extension relies on the OES_shader_io_blocks extension to provide the required functionality for declaring input and output blocks and interfacing
between shaders.
Requires ${GLES31.core} and ${OES_shader_io_blocks.capLink} or ${EXT_shader_io_blocks.capLink}.
"""
IntConstant(
"""
Accepted by the {@code type} parameter of CreateShader and CreateShaderProgramv, by the {@code pname} parameter of GetProgramPipelineiv and returned in
the {@code params} parameter of GetShaderiv when {@code pname} is SHADER_TYPE.
""",
"GEOMETRY_SHADER_OES"..0x8DD9
)
IntConstant(
"Accepted by the {@code stages} parameter of UseProgramStages.",
"GEOMETRY_SHADER_BIT_OES"..0x00000004
)
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"GEOMETRY_LINKED_VERTICES_OUT_OES"..0x8916,
"GEOMETRY_LINKED_INPUT_TYPE_OES"..0x8917,
"GEOMETRY_LINKED_OUTPUT_TYPE_OES"..0x8918,
"GEOMETRY_SHADER_INVOCATIONS_OES"..0x887F
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetInteger64v.",
"LAYER_PROVOKING_VERTEX_OES"..0x825E,
"MAX_GEOMETRY_UNIFORM_COMPONENTS_OES"..0x8DDF,
"MAX_GEOMETRY_UNIFORM_BLOCKS_OES"..0x8A2C,
"MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS_OES"..0x8A32,
"MAX_GEOMETRY_INPUT_COMPONENTS_OES"..0x9123,
"MAX_GEOMETRY_OUTPUT_COMPONENTS_OES"..0x9124,
"MAX_GEOMETRY_OUTPUT_VERTICES_OES"..0x8DE0,
"MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_OES"..0x8DE1,
"MAX_GEOMETRY_SHADER_INVOCATIONS_OES"..0x8E5A,
"MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_OES"..0x8C29,
"MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS_OES"..0x92CF,
"MAX_GEOMETRY_ATOMIC_COUNTERS_OES"..0x92D5,
"MAX_GEOMETRY_IMAGE_UNIFORMS_OES"..0x90CD,
"MAX_GEOMETRY_SHADER_STORAGE_BLOCKS_OES"..0x90D7
)
IntConstant(
"Returned in the {@code data} parameter from a Get query with a {@code pname} of LAYER_PROVOKING_VERTEX_OES.",
"FIRST_VERTEX_CONVENTION_OES"..0x8E4D,
"LAST_VERTEX_CONVENTION_OES"..0x8E4E,
"UNDEFINED_VERTEX_OES"..0x8260
)
IntConstant(
"Accepted by the {@code target} parameter of BeginQuery, EndQuery, GetQueryiv, and GetQueryObjectuiv.",
"PRIMITIVES_GENERATED_OES"..0x8C87
)
IntConstant(
"Accepted by the {@code mode} parameter of DrawArrays, DrawElements, and other commands which draw primitives.",
"LINES_ADJACENCY_OES"..0xA,
"LINE_STRIP_ADJACENCY_OES"..0xB,
"TRIANGLES_ADJACENCY_OES"..0xC,
"TRIANGLE_STRIP_ADJACENCY_OES"..0xD
)
IntConstant(
"Accepted by the {@code pname} parameter of FramebufferParameteri, and GetFramebufferParameteriv.",
"FRAMEBUFFER_DEFAULT_LAYERS_OES"..0x9312
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetInteger64v, and GetFloatv.",
"MAX_FRAMEBUFFER_LAYERS_OES"..0x9317
)
IntConstant(
"Returned by CheckFramebufferStatus.",
"FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_OES"..0x8DA8
)
IntConstant(
"Accepted by the {@code pname} parameter of GetFramebufferAttachmentParameteriv.",
"FRAMEBUFFER_ATTACHMENT_LAYERED_OES"..0x8DA7
)
IntConstant(
"Accepted by the {@code props} parameter of GetProgramResourceiv.",
"REFERENCED_BY_GEOMETRY_SHADER_OES"..0x9309
)
void(
"FramebufferTextureOES",
"",
GLenum.IN("target", ""),
GLenum.IN("attachment", ""),
GLuint.IN("texture", ""),
GLint.IN("level", "")
)
}
val OES_geometry_point_size = EXT_FLAG.nativeClassGLES("OES_geometry_point_size", postfix = OES) {
documentation =
"""
When true, the $registryLink extension is supported.
"""
} | bsd-3-clause | 6e192a35f6463d4c7a1c508d72a96e7d | 38.675159 | 153 | 0.760918 | 3.696142 | false | false | false | false |
codehz/container | app/src/main/java/one/codehz/container/provider/MainProvider.kt | 1 | 4161 | package one.codehz.container.provider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import one.codehz.container.db.MainDb
class MainProvider : ContentProvider() {
companion object {
val TYPE_LIST = 0
val TYPE_ITEM = 1
val AUTHORITY = "one.codehz.container.provider.main"
val LOG_URI = Uri.Builder().scheme("content").authority(AUTHORITY).appendPath("log").build()!!
val COMPONENT_URI = Uri.Builder().scheme("content").authority(AUTHORITY).appendPath("component").build()!!
val COMPONENT_LOG_URI = Uri.Builder().scheme("content").authority(AUTHORITY).appendPath("clog").build()!!
val COMPONENT_LOG_VIEW_URI = Uri.Builder().scheme("content").authority(AUTHORITY).appendPath("clog_view").build()!!
val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI(AUTHORITY, "*", TYPE_LIST)
addURI(AUTHORITY, "*/#", TYPE_ITEM)
}
}
private lateinit var dbHelper: MainDb
override fun onCreate(): Boolean {
dbHelper = MainDb(this.context)
return true
}
private fun getMime(isDir: Boolean, name: String) = "vnd.android.cursor.${if (isDir) "dir" else "item"}/vnd.one.codehz.container.$name"
override fun getType(uri: Uri) = when (uriMatcher.match(uri)) {
TYPE_LIST -> getMime(true, uri.pathSegments.first())
TYPE_ITEM -> getMime(false, uri.pathSegments.first())
else -> throw IllegalArgumentException("Unsupported URI: $uri")
}
override fun insert(uri: Uri, values: ContentValues?): Uri {
val name = when (uriMatcher.match(uri)) {
TYPE_LIST -> uri.pathSegments.first()
else -> throw IllegalArgumentException("Unsupported URI: $uri")
}
val id = dbHelper.writableDatabase.insert(name, null, values)
context.contentResolver.notifyChange(uri, null)
return uri.buildUpon().appendPath(id.toString()).build()
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
val (name, newSelection) = when (uriMatcher.match(uri)) {
TYPE_LIST -> uri.pathSegments.first() to selection
TYPE_ITEM -> uri.pathSegments.first() to "_id=${uri.pathSegments.last()}" + if (selection.isNullOrEmpty()) "" else " AND ($selection)"
else -> throw IllegalArgumentException("Unsupported URI: $uri")
}
val res = dbHelper.writableDatabase.delete(name, newSelection, selectionArgs)
context.contentResolver.notifyChange(uri, null)
return res
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
val (name, newSelection) = when (uriMatcher.match(uri)) {
TYPE_LIST -> uri.pathSegments.first() to selection
TYPE_ITEM -> uri.pathSegments.first() to "_id=${uri.pathSegments.last()}" + if (selection.isNullOrEmpty()) "" else " AND ($selection)"
else -> throw IllegalArgumentException("Unsupported URI: $uri")
}
val res = dbHelper.writableDatabase.update(name, values, newSelection, selectionArgs)
context.contentResolver.notifyChange(uri, null)
return res
}
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor {
val (name, targetId) = when (uriMatcher.match(uri)) {
TYPE_LIST -> uri.pathSegments.first() to null
TYPE_ITEM -> uri.pathSegments.first() to uri.lastPathSegment
else -> throw IllegalArgumentException("Unsupported URI: $uri")
}
return dbHelper.readableDatabase.let {
SQLiteQueryBuilder().apply {
tables = name
targetId?.apply { appendWhere("_id=$this") }
}.query(it, projection, selection, selectionArgs, uri.getQueryParameter("groupBy"), uri.getQueryParameter("having"), sortOrder)
}
}
} | gpl-3.0 | b788c6cbe6d1cefcd6d8fef3ada147f5 | 46.295455 | 149 | 0.655852 | 4.5625 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/data/dao/response/BookcaseFilmsResponse.kt | 2 | 1128 | package ru.fantlab.android.data.dao.response
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.JsonParser
import ru.fantlab.android.data.dao.Pageable
import ru.fantlab.android.data.dao.model.BookcaseFilm
import ru.fantlab.android.provider.rest.DataManager
data class BookcaseFilmsResponse(
val films: Pageable<BookcaseFilm>
) {
class Deserializer(private val perPage: Int) : ResponseDeserializable<BookcaseFilmsResponse> {
override fun deserialize(content: String): BookcaseFilmsResponse {
val jsonObject = JsonParser().parse(content).asJsonObject
val items: ArrayList<BookcaseFilm> = arrayListOf()
val array = jsonObject.getAsJsonArray("bookcase_items")
array.map {
items.add(DataManager.gson.fromJson(it, BookcaseFilm::class.java))
}
val totalCount = jsonObject.getAsJsonPrimitive("count").asInt
val lastPage = (totalCount - 1) / perPage + 1
val films = Pageable(lastPage, totalCount, items)
return BookcaseFilmsResponse(films)
}
}
} | gpl-3.0 | f97afe03f5a631be777860554c36337a | 40.814815 | 98 | 0.699468 | 4.641975 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-db-coroutines/src/main/kotlin/org/ccci/gto/android/common/db/CoroutinesAsyncDao.kt | 2 | 1424 | package org.ccci.gto.android.common.db
import android.database.sqlite.SQLiteDatabase
import kotlinx.coroutines.async
interface CoroutinesAsyncDao : CoroutinesDao {
fun <T : Any> findAsync(clazz: Class<T>, vararg key: Any) = coroutineScope.async { find(clazz, *key) }
fun <T : Any> getAsync(query: Query<T>) = coroutineScope.async { get(query) }
fun getCursorAsync(query: Query<*>) = coroutineScope.async { getCursor(query) }
fun insertAsync(obj: Any, conflictAlgorithm: Int = SQLiteDatabase.CONFLICT_NONE) =
coroutineScope.async { insert(obj, conflictAlgorithm) }
fun updateAsync(obj: Any) = updateAsync(obj, *getFullProjection(obj.javaClass))
fun updateAsync(obj: Any, vararg projection: String) = coroutineScope.async { update(obj, *projection) }
fun <T : Any> updateAsync(sample: T, where: Expression?, vararg projection: String) =
coroutineScope.async { update(sample, where, *projection) }
fun updateOrInsertAsync(obj: Any) = updateOrInsertAsync(obj, *getFullProjection(obj.javaClass))
fun updateOrInsertAsync(obj: Any, vararg projection: String) =
coroutineScope.async { updateOrInsert(obj, *projection) }
fun <T> transactionAsync(exclusive: Boolean = true, body: () -> T) =
coroutineScope.async { transaction(exclusive, body) }
}
inline fun <reified T : Any> CoroutinesAsyncDao.findAsync(vararg key: Any) = findAsync(T::class.java, *key)
| mit | f3a749b3ea9914a607334f844ac9e593 | 51.740741 | 108 | 0.723315 | 3.880109 | false | false | false | false |
tasomaniac/OpenLinkWith | app/src/main/java/com/tasomaniac/openwith/resolver/BrowserHandler.kt | 1 | 2770 | package com.tasomaniac.openwith.resolver
import android.content.pm.ResolveInfo
import android.os.Build
import com.tasomaniac.openwith.browser.BrowserPreferences
import com.tasomaniac.openwith.browser.BrowserPreferences.Mode
import com.tasomaniac.openwith.browser.resolver.BrowserResolver
import com.tasomaniac.openwith.extensions.componentName
import com.tasomaniac.openwith.extensions.isEqualTo
import java.util.ArrayList
import javax.inject.Inject
class BrowserHandler(
private val browserResolver: BrowserResolver,
private val browserPreferences: BrowserPreferences,
private val currentResolveList: MutableList<ResolveInfo>
) {
/**
* First add all browsers into the list if the device is > [Build.VERSION_CODES.M]
*
* Then depending on the browser preference,
*
* - Remove all browsers
* - Only put the selected browser
*
* If the selected browser is not found, fallback to [Mode.AlwaysAsk]
*
*/
fun handleBrowsers() {
val browsers = browserResolver.queryBrowsers()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
addAllBrowsers(browsers)
}
val mode = browserPreferences.mode
when (mode) {
is Mode.None -> removeBrowsers(browsers)
is Mode.Browser -> {
removeBrowsers(browsers)
val found = browsers.find { it.activityInfo.componentName() == mode.componentName }
if (found != null) {
currentResolveList.add(found)
} else {
browserPreferences.mode = Mode.AlwaysAsk
}
}
}
}
private fun removeBrowsers(browsers: List<ResolveInfo>) {
val toRemove = currentResolveList.filter { resolve ->
browsers.find { browser ->
resolve.activityInfo.isEqualTo(browser.activityInfo)
} != null
}
currentResolveList.removeAll(toRemove)
}
private fun addAllBrowsers(browsers: List<ResolveInfo>) {
val initialList = ArrayList(currentResolveList)
browsers.forEach { browser ->
val notFound = initialList.find {
it.activityInfo.isEqualTo(browser.activityInfo)
} == null
if (notFound) {
currentResolveList.add(browser)
}
}
}
class Factory @Inject constructor(
private val browserResolver: BrowserResolver,
private val browserPreferences: BrowserPreferences
) {
fun create(currentResolveList: MutableList<ResolveInfo>) =
BrowserHandler(
browserResolver,
browserPreferences,
currentResolveList
)
}
}
| apache-2.0 | 8b07d52096d49aee61a01dd0d4a2586e | 31.588235 | 99 | 0.629964 | 5 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/gigaviewer/GigaViewerGenerator.kt | 1 | 1065 | package eu.kanade.tachiyomi.multisrc.gigaviewer
import generator.ThemeSourceData.SingleLang
import generator.ThemeSourceGenerator
class GigaViewerGenerator : ThemeSourceGenerator {
override val themePkg = "gigaviewer"
override val themeClass = "GigaViewer"
override val baseVersionCode: Int = 2
override val sources = listOf(
SingleLang("Comic Gardo", "https://comic-gardo.com", "ja"),
SingleLang("Kurage Bunch", "https://kuragebunch.com", "ja"),
SingleLang("MAGCOMI", "https://magcomi.com", "ja", className = "MagComi"),
SingleLang("Magazine Pocket", "https://pocket.shonenmagazine.com", "ja"),
SingleLang("Shonen Jump+", "https://shonenjumpplus.com", "ja", pkgName = "shonenjumpplus", className = "ShonenJumpPlus", overrideVersionCode = 2),
SingleLang("Tonari no Young Jump", "https://tonarinoyj.jp", "ja", className = "TonariNoYoungJump")
)
companion object {
@JvmStatic
fun main(args: Array<String>) {
GigaViewerGenerator().createAll()
}
}
}
| apache-2.0 | 5cb09c37476acf109f541259a495fd6a | 35.724138 | 154 | 0.671362 | 3.736842 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/mine/model/IssueMode.kt | 1 | 6196 | package com.intfocus.template.dashboard.mine.model
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.os.Environment
import com.google.gson.Gson
import com.intfocus.template.dashboard.mine.bean.IssueCommitInfo
import com.intfocus.template.dashboard.mine.bean.IssueCommitRequest
import com.intfocus.template.dashboard.mine.bean.IssueListBean
import com.intfocus.template.dashboard.mine.bean.IssueListRequest
import com.intfocus.template.util.*
import com.zbl.lib.baseframe.core.AbstractMode
import com.zbl.lib.baseframe.utils.StringUtil
import okhttp3.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.util.*
/**
* @author liuruilin on 2017/6/11.
*/
class IssueMode(var ctx: Context) : AbstractMode() {
lateinit var urlString: String
var result: String? = null
val mIssueSP: SharedPreferences = ctx.getSharedPreferences("IssueList", Context.MODE_PRIVATE)
var gson = Gson()
var fileList: MutableList<File> = mutableListOf()
fun getUrl(): String {
val url = "http://development.shengyiplus.com/api/v1/user/123456/page/1/limit/10/problems"
return url
}
override fun requestData() {
Thread(Runnable {
urlString = getUrl()
if (!urlString.isEmpty()) {
val response = HttpUtil.httpGet(ctx, urlString, HashMap<String, String>())
result = response["body"]
if (StringUtil.isEmpty(result)) {
val result1 = IssueListRequest(false, 400)
EventBus.getDefault().post(result1)
return@Runnable
}
analysisData(result)
} else {
val result1 = IssueListRequest(false, 400)
EventBus.getDefault().post(result1)
return@Runnable
}
}).start()
}
/**
* 解析数据
* @param result
*/
private fun analysisData(result: String?): IssueListRequest {
try {
val jsonObject = JSONObject(result)
if (jsonObject.has("code")) {
val code = jsonObject.getInt("code")
if (code != 200) {
val result1 = IssueListRequest(false, code)
EventBus.getDefault().post(result1)
return result1
}
}
val resultStr = jsonObject.toString()
mIssueSP.edit().putString("IssueList", resultStr).apply()
val issueListBean = gson.fromJson(resultStr, IssueListBean::class.java)
val result1 = IssueListRequest(true, 200)
result1.issueList = issueListBean
EventBus.getDefault().post(result1)
return result1
} catch (e: JSONException) {
e.printStackTrace()
val result1 = IssueListRequest(false, -1)
EventBus.getDefault().post(result1)
}
val result1 = IssueListRequest(false, 0)
EventBus.getDefault().post(result1)
return result1
}
fun addUploadImg(bmp: Bitmap) {
if (fileList.size <= 3) {
val str = Environment.getExternalStorageDirectory().toString() + "/" + "image1.png"
if (File(str).exists()) {
File(str).delete()
}
fileList.add(FileUtil.saveImage(str, bmp))
} else {
ToastUtils.show(ctx, "仅可上传3张图片")
}
}
fun setUploadImg(imgFile: File) {
fileList.add(imgFile)
}
/**
params:
{
title: 标题-可选,
content: 反馈内容-必填,
user_num: 用户编号-可选,
app_version: 应用版本-可选,
platform: 系统名称-可选,
platform_version: 系统版本-可选,
images: [
multipart/form-data
]
}
*/
fun commitIssue2(issueInfo: IssueCommitInfo) {
val mOkHttpClient = OkHttpClient()
val requestBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("api_token", URLs.MD5(K.ANDROID_API_KEY + K.K_FEED_BACK + K.ANDROID_API_KEY))
.addFormDataPart("content", issueInfo.issue_content)
.addFormDataPart("title", "生意人问题反馈")
.addFormDataPart("user_num", issueInfo.user_num)
.addFormDataPart("app_version", issueInfo.app_version)
.addFormDataPart("platform", issueInfo.platform)
.addFormDataPart("platform_version", issueInfo.platform_version)
if (!fileList.isEmpty()) {
for ((i, file) in fileList.withIndex()) {
requestBody.addFormDataPart("image" + i, file.name, RequestBody.create(MediaType.parse("image/*"), file))
}
}
val request = Request.Builder()
.url(TempHost.getHost() + K.K_FEED_BACK)
.post(requestBody.build())
.build()
mOkHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
val issueCommitRequest = IssueCommitRequest(false, "提交失败")
EventBus.getDefault().post(issueCommitRequest)
ActionLogUtil.actionLog("点击/问题反馈/失败")
}
override fun onResponse(call: Call?, response: Response?) {
val issueCommitRequest: IssueCommitRequest
val logParams: JSONObject
if (response!!.isSuccessful) {
issueCommitRequest = IssueCommitRequest(true, "提交成功")
EventBus.getDefault().post(issueCommitRequest)
ActionLogUtil.actionLog("点击/问题反馈/成功")
} else {
issueCommitRequest = IssueCommitRequest(false, "提交失败")
EventBus.getDefault().post(issueCommitRequest)
ActionLogUtil.actionLog("点击/问题反馈/失败")
}
}
})
}
}
| gpl-3.0 | c678d002cda8006c73128265ce35e549 | 33.797688 | 121 | 0.58887 | 4.419971 | false | false | false | false |
elect86/jAssimp | src/test/kotlin/assimp/blender/testCubeRotateScaleTranslate.kt | 2 | 3218 | package assimp.blender
import assimp.*
import glm_.func.rad
import glm_.mat4x4.*
import glm_.vec3.*
import io.kotest.assertions.assertSoftly
import io.kotest.matchers.shouldBe
// TODO also test linked meshes
private data class TransformDescription(val x: Float = 0f, val y: Float = 0f, val z: Float = 0f,
val rotation: Float = 0f, val rX: Float = 0f, val rY: Float = 0f, val rZ: Float = 0f,
val sX: Float = 1f, val sY: Float = 1f, val sZ: Float = 1f)
private val cubeDescriptions = mapOf(
"CubeX1" to TransformDescription(x = 1f),
"CubeY1" to TransformDescription(y = 1f),
"CubeZ1" to TransformDescription(z = 1f),
"CubeXN1" to TransformDescription(x = -1f),
"CubeYN1" to TransformDescription(y = -1f),
"CubeZN1" to TransformDescription(z = -1f),
"CubeRX45" to TransformDescription(rotation = 45f.rad, rX = 1f),
"CubeRY45" to TransformDescription(rotation = 45f.rad, rY = 1f),
"CubeRZ45" to TransformDescription(rotation = 45f.rad, rZ = 1f),
"CubeSX2" to TransformDescription(sX = 2f),
"CubeSY2" to TransformDescription(sY = 2f),
"CubeSZ2" to TransformDescription(sZ = 2f)
)
object testCubeRotateScaleTranslate {
private fun generateTrans(des: TransformDescription): Mat4 {
return generateTrans(des.x, des.y, des.z,
des.rotation, des.rX, des.rY, des.rZ,
des.sX, des.sY, des.sZ)
}
private fun AiNode.check(des: TransformDescription) {
transformation.shouldEqual(generateTrans(des), epsilon)
numChildren shouldBe 0
numMeshes shouldBe 1
}
operator fun invoke(fileName: String) {
Importer().testFile(getResource(fileName)) {
flags shouldBe 0
with(rootNode) {
name shouldBe "<BlenderRoot>" // TODO should this be the filename instead??
transformation shouldBe Mat4()
numChildren shouldBe 12
assertSoftly {
cubeDescriptions.forEach { (name, description) ->
children.first { it.name == name }.check(description)
}
}
numMeshes shouldBe 0
numLights shouldBe 0
numCameras shouldBe 0
numTextures shouldBe 0
numAnimations shouldBe 0
}
numMeshes shouldBe 12
repeat(12) { meshInd ->
with(meshes[meshInd]) {
primitiveTypes shouldBe AiPrimitiveType.POLYGON.i
numVertices shouldBe 24
numFaces shouldBe 6
vertices[0] shouldBe Vec3(-0.5, -0.5, +0.5)
vertices[5] shouldBe Vec3(+0.5, +0.5, +0.5)
vertices[10] shouldBe Vec3(+0.5, -0.5, -0.5)
vertices[15] shouldBe Vec3(+0.5, -0.5, -0.5)
vertices[20] shouldBe Vec3(+0.5, -0.5, +0.5)
vertices[23] shouldBe Vec3(-0.5, -0.5, +0.5)
var i = 0
faces.forEach {
it.size shouldBe 4
it shouldBe mutableListOf(i++, i++, i++, i++)
}
}
}
numMaterials shouldBe 1
with(materials[0]) {
name shouldBe AI_DEFAULT_MATERIAL_NAME
// shadingModel shouldBe AiShadingMode.gouraud TODO ???
with(color!!) {
ambient shouldBe Vec3()
diffuse shouldBe Vec3(0.6)
specular shouldBe Vec3(0.6)
emissive shouldBe null
shininess shouldBe null
opacity shouldBe null
refracti shouldBe null
}
}
}
}
} | mit | 1f771ea8bc63b7a90060cbdbe8224004 | 27.741071 | 125 | 0.645743 | 3.260385 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/course_complete/analytic/FinishedStepsBackToAssignmentsPressedAnalyticEvent.kt | 2 | 757 | package org.stepik.android.domain.course_complete.analytic
import org.stepik.android.domain.base.analytic.AnalyticEvent
import org.stepik.android.model.Course
class FinishedStepsBackToAssignmentsPressedAnalyticEvent(
course: Course,
completeRate: Float
) : AnalyticEvent {
companion object {
private const val PARAM_COURSE = "course"
private const val PARAM_TITLE = "title"
private const val COMPLETE_RATE = "complete_rate"
}
override val name: String =
"Finished steps back to assignments pressed"
override val params: Map<String, Any> =
mapOf(
PARAM_COURSE to course.id,
PARAM_TITLE to course.title.toString(),
COMPLETE_RATE to completeRate
)
} | apache-2.0 | 5753e614884776c4b5450e53e47d92f6 | 30.583333 | 60 | 0.686922 | 4.47929 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/ranges/literal/maxValueToMinValue.kt | 2 | 1877 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
// TODO: muted automatically, investigate should it be ran for NATIVE or not
// IGNORE_BACKEND: NATIVE
// Auto-generated by org.jetbrains.kotlin.generators.tests.GenerateRangesCodegenTestData. DO NOT EDIT!
// WITH_RUNTIME
import java.lang.Integer.MAX_VALUE as MaxI
import java.lang.Integer.MIN_VALUE as MinI
import java.lang.Byte.MAX_VALUE as MaxB
import java.lang.Byte.MIN_VALUE as MinB
import java.lang.Short.MAX_VALUE as MaxS
import java.lang.Short.MIN_VALUE as MinS
import java.lang.Long.MAX_VALUE as MaxL
import java.lang.Long.MIN_VALUE as MinL
import java.lang.Character.MAX_VALUE as MaxC
import java.lang.Character.MIN_VALUE as MinC
fun box(): String {
val list1 = ArrayList<Int>()
for (i in MaxI..MinI) {
list1.add(i)
if (list1.size > 23) break
}
if (list1 != listOf<Int>()) {
return "Wrong elements for MaxI..MinI: $list1"
}
val list2 = ArrayList<Int>()
for (i in MaxB..MinB) {
list2.add(i)
if (list2.size > 23) break
}
if (list2 != listOf<Int>()) {
return "Wrong elements for MaxB..MinB: $list2"
}
val list3 = ArrayList<Int>()
for (i in MaxS..MinS) {
list3.add(i)
if (list3.size > 23) break
}
if (list3 != listOf<Int>()) {
return "Wrong elements for MaxS..MinS: $list3"
}
val list4 = ArrayList<Long>()
for (i in MaxL..MinL) {
list4.add(i)
if (list4.size > 23) break
}
if (list4 != listOf<Long>()) {
return "Wrong elements for MaxL..MinL: $list4"
}
val list5 = ArrayList<Char>()
for (i in MaxC..MinC) {
list5.add(i)
if (list5.size > 23) break
}
if (list5 != listOf<Char>()) {
return "Wrong elements for MaxC..MinC: $list5"
}
return "OK"
}
| apache-2.0 | 2b5bde5b5ae56f518ae7a3bea7cb2638 | 26.202899 | 102 | 0.622802 | 3.192177 | false | false | false | false |
jiaminglu/kotlin-native | Interop/Runtime/src/native/kotlin/kotlinx/cinterop/ObjectiveCImpl.kt | 1 | 6437 | /*
* Copyright 2010-2017 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.
*/
@file:Suppress("NOTHING_TO_INLINE")
package kotlinx.cinterop
interface ObjCObject
interface ObjCClass : ObjCObject
typealias ObjCObjectMeta = ObjCClass
abstract class ObjCObjectBase protected constructor() : ObjCObject {
final override fun equals(other: Any?): Boolean = this.uncheckedCast<ObjCPointerHolder>().equals(other)
final override fun hashCode(): Int = ObjCHashCode(this.rawPtr)
final override fun toString(): String = ObjCToString(this.rawPtr)
}
abstract class ObjCObjectBaseMeta protected constructor() : ObjCObjectBase(), ObjCObjectMeta {}
fun optional(): Nothing = throw RuntimeException("Do not call me!!!")
/**
* The runtime representation of any [ObjCObject].
*/
@ExportTypeInfo("theObjCPointerHolderTypeInfo")
class ObjCPointerHolder(inline val rawPtr: NativePtr) {
init {
assert(rawPtr != nativeNullPtr)
objc_retain(rawPtr)
}
final override fun equals(other: Any?): Boolean =
(other is ObjCPointerHolder) && ObjCEquals(this.rawPtr, other.rawPtr)
final override fun hashCode(): Int = ObjCHashCode(this.rawPtr)
final override fun toString(): String = ObjCToString(this.rawPtr)
}
@konan.internal.Intrinsic
@konan.internal.ExportForCompiler
private external fun ObjCObject.initFromPtr(ptr: NativePtr)
@konan.internal.Intrinsic
external fun <T : ObjCObjectBase> T.initBy(constructorCall: T): T
@konan.internal.ExportForCompiler
private fun ObjCObjectBase.superInitCheck(superInitCallResult: ObjCObject?) {
if (superInitCallResult == null)
throw RuntimeException("Super initialization failed")
if (superInitCallResult.rawPtr != this.rawPtr)
throw UnsupportedOperationException("Super initializer has replaced object")
}
fun <T : Any?> Any?.uncheckedCast(): T = @Suppress("UNCHECKED_CAST") (this as T) // TODO: make private
inline fun <T : ObjCObject?> interpretObjCPointerOrNull(rawPtr: NativePtr): T? = if (rawPtr != nativeNullPtr) {
ObjCPointerHolder(rawPtr).uncheckedCast<T>()
} else {
null
}
inline fun <T : ObjCObject> interpretObjCPointer(rawPtr: NativePtr): T = if (rawPtr != nativeNullPtr) {
ObjCPointerHolder(rawPtr).uncheckedCast<T>()
} else {
throw NullPointerException()
}
inline val ObjCObject.rawPtr: NativePtr get() = (this.uncheckedCast<ObjCPointerHolder>()).rawPtr
inline val ObjCObject?.rawPtr: NativePtr get() = if (this != null) {
(this.uncheckedCast<ObjCPointerHolder>()).rawPtr
} else {
nativeNullPtr
}
class ObjCObjectVar<T : ObjCObject?>(rawPtr: NativePtr) : CVariable(rawPtr) {
companion object : CVariable.Type(pointerSize.toLong(), pointerSize)
}
class ObjCStringVarOf<T : String?>(rawPtr: NativePtr) : CVariable(rawPtr) {
companion object : CVariable.Type(pointerSize.toLong(), pointerSize)
}
var <T : String?> ObjCStringVarOf<T>.value: T
get() = TODO()
set(value) = TODO()
@konan.internal.Intrinsic external fun getReceiverOrSuper(receiver: NativePtr, superClass: NativePtr): COpaquePointer?
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
annotation class ExternalObjCClass()
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.BINARY)
annotation class ObjCMethod(val selector: String, val bridge: String)
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.BINARY)
annotation class ObjCBridge(val selector: String, val encoding: String, val imp: String)
@Target(AnnotationTarget.CONSTRUCTOR)
@Retention(AnnotationRetention.BINARY)
annotation class ObjCConstructor(val initSelector: String)
@Target(AnnotationTarget.FILE)
@Retention(AnnotationRetention.BINARY)
annotation class InteropStubs()
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
private annotation class ObjCMethodImp(val selector: String, val encoding: String)
@konan.internal.ExportForCompiler
private fun <T : ObjCObject> allocObjCObject(clazz: NativePtr): T {
val rawResult = objc_allocWithZone(clazz)
if (rawResult == nativeNullPtr) {
throw OutOfMemoryError("Unable to allocate Objective-C object")
}
val result = interpretObjCPointerOrNull<T>(rawResult)!!
// `objc_allocWithZone` returns retained pointer. Balance it:
objc_release(rawResult)
// TODO: do not retain this pointer in `interpretObjCPointerOrNull` instead.
return result
}
@konan.internal.Intrinsic
@konan.internal.ExportForCompiler
private external fun <T : ObjCObject> getObjCClass(): NativePtr
@konan.internal.Intrinsic external fun getMessenger(superClass: NativePtr): COpaquePointer?
@konan.internal.Intrinsic external fun getMessengerLU(superClass: NativePtr): COpaquePointer?
// Konan runtme:
@SymbolName("Kotlin_Interop_CreateNSStringFromKString")
external fun CreateNSStringFromKString(str: String?): NativePtr
@SymbolName("Kotlin_Interop_CreateKStringFromNSString")
external fun CreateKStringFromNSString(ptr: NativePtr): String?
@SymbolName("Kotlin_Interop_ObjCToString")
private external fun ObjCToString(ptr: NativePtr): String
@SymbolName("Kotlin_Interop_ObjCHashCode")
private external fun ObjCHashCode(ptr: NativePtr): Int
@SymbolName("Kotlin_Interop_ObjCEquals")
private external fun ObjCEquals(ptr: NativePtr, otherPtr: NativePtr): Boolean
// Objective-C runtime:
@SymbolName("objc_retainAutoreleaseReturnValue")
external fun objc_retainAutoreleaseReturnValue(ptr: NativePtr): NativePtr
@SymbolName("Kotlin_objc_autoreleasePoolPush")
external fun objc_autoreleasePoolPush(): NativePtr
@SymbolName("Kotlin_objc_autoreleasePoolPop")
external fun objc_autoreleasePoolPop(ptr: NativePtr)
@SymbolName("Kotlin_objc_allocWithZone")
private external fun objc_allocWithZone(clazz: NativePtr): NativePtr
@SymbolName("Kotlin_objc_retain")
external fun objc_retain(ptr: NativePtr): NativePtr
@SymbolName("Kotlin_objc_release")
external fun objc_release(ptr: NativePtr)
| apache-2.0 | 5fa30c6652217ada57f64f49cbe5c7fb | 33.794595 | 118 | 0.770701 | 4.155584 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryItem.kt | 1 | 2785 | package eu.kanade.tachiyomi.ui.library
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import com.f2prateek.rx.preferences.Preference
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
import eu.davidea.flexibleadapter.items.IFilterable
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.LibraryManga
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.widget.AutofitRecyclerView
import kotlinx.android.synthetic.main.catalogue_grid_item.view.*
class LibraryItem(val manga: LibraryManga, private val libraryAsList: Preference<Boolean>) :
AbstractFlexibleItem<LibraryHolder>(), IFilterable<String> {
var downloadCount = -1
override fun getLayoutRes(): Int {
return if (libraryAsList.getOrDefault())
R.layout.catalogue_list_item
else
R.layout.catalogue_grid_item
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): LibraryHolder {
val parent = adapter.recyclerView
return if (parent is AutofitRecyclerView) {
view.apply {
val coverHeight = parent.itemWidth / 3 * 4
card.layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, coverHeight)
gradient.layoutParams = FrameLayout.LayoutParams(
MATCH_PARENT, coverHeight / 2, Gravity.BOTTOM)
}
LibraryGridHolder(view, adapter)
} else {
LibraryListHolder(view, adapter)
}
}
override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>,
holder: LibraryHolder,
position: Int,
payloads: List<Any?>?) {
holder.onSetValues(this)
}
/**
* Filters a manga depending on a query.
*
* @param constraint the query to apply.
* @return true if the manga should be included, false otherwise.
*/
override fun filter(constraint: String): Boolean {
return manga.title.contains(constraint, true) ||
(manga.author?.contains(constraint, true) ?: false)
}
override fun equals(other: Any?): Boolean {
if (other is LibraryItem) {
return manga.id == other.manga.id
}
return false
}
override fun hashCode(): Int {
return manga.id!!.hashCode()
}
} | apache-2.0 | ca40fe481dc36fafda47fd6f315fe266 | 35.662162 | 124 | 0.651706 | 4.79346 | false | false | false | false |
v-grishechko/kmockserver | src/main/kotlin/by/galt/kmockserver/netty/NettyServer.kt | 1 | 1259 | package by.galt.kmockserver.netty
import by.galt.kmockserver.rule.ResponseRule
import io.netty.buffer.ByteBuf
import io.netty.handler.codec.http.HttpResponseStatus
import io.reactivex.netty.RxNetty
import io.reactivex.netty.protocol.http.server.HttpServer
class NettyServer {
var server: HttpServer<ByteBuf, ByteBuf>? = null
fun start(responseRules: MutableList<ResponseRule>) {
stop()
server = RxNetty.createHttpServer(8080, { request, response ->
val rule = responseRules.firstOrNull {
request?.path.equals(it.request.path, true) &&
request.httpMethod.name().equals(it.request.type.name, true)
}
if (rule != null) {
rule.response.headers.forEach { response.headers.addHeader(it.name, it.value) }
response.status = HttpResponseStatus(rule.response.code, "")
response.writeString(rule.response.body)
responseRules.remove(rule)
response.close()
} else {
response.status = HttpResponseStatus.NOT_FOUND
response.close()
}
})
server?.start()
}
fun stop() {
server?.shutdown()
}
}
| mit | 5a5a0052077258d13c41f8be14a3b761 | 28.27907 | 95 | 0.606037 | 4.464539 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt | 1 | 3107 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.TempBasalInsulinProgramElement
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil
import java.nio.ByteBuffer
import kotlin.math.roundToInt
object ProgramTempBasalUtil {
fun mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot: ShortArray): List<BasalInsulinProgramElement> {
return ProgramBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot) { startSlotIndex: Byte, numberOfSlots: Byte, totalTenthPulses: Short ->
TempBasalInsulinProgramElement(
startSlotIndex,
numberOfSlots,
totalTenthPulses
)
}
}
fun mapTempBasalToTenthPulsesPerSlot(durationInSlots: Int, rateInUnitsPerHour: Double): ShortArray {
val pulsesPerHour = (rateInUnitsPerHour * 20).roundToInt().toShort()
val tenthPulsesPerSlot = ShortArray(durationInSlots)
var i = 0
while (durationInSlots > i) {
tenthPulsesPerSlot[i] = (roundToHalf(pulsesPerHour / 2.0) * 10).toInt().toShort()
i++
}
return tenthPulsesPerSlot
}
private fun roundToHalf(d: Double): Double {
return ((d * 10.0).toInt().toShort() / 5 * 5).toShort().toDouble() / 10.0
}
fun mapTempBasalToPulsesPerSlot(durationInSlots: Byte, rateInUnitsPerHour: Double): ShortArray {
val pulsesPerHour = (rateInUnitsPerHour * 20).roundToInt().toShort()
val pulsesPerSlot = ShortArray(durationInSlots.toInt())
var remainingPulse = false
var i = 0
while (durationInSlots > i) {
pulsesPerSlot[i] = (pulsesPerHour / 2).toShort()
if (pulsesPerHour % 2 == 1) { // Do extra alternate pulse
if (remainingPulse) {
pulsesPerSlot[i] = (pulsesPerSlot[i] + 1).toShort()
}
remainingPulse = !remainingPulse
}
i++
}
return pulsesPerSlot
}
fun calculateChecksum(totalNumberOfSlots: Byte, pulsesInFirstSlot: Short, pulsesPerSlot: ShortArray?): Short {
val buffer = ByteBuffer.allocate(1 + 2 + 2 + 2 * pulsesPerSlot!!.size)
.put(totalNumberOfSlots)
.putShort(0x3840.toShort())
.putShort(pulsesInFirstSlot)
for (pulses in pulsesPerSlot) {
buffer.putShort(pulses)
}
return MessageUtil.calculateChecksum(buffer.array())
}
fun mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot: ShortArray?): List<ShortInsulinProgramElement> =
ProgramBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot)
}
| agpl-3.0 | b32c6f349650e88190d535658b3e9238 | 44.691176 | 173 | 0.688767 | 4.285517 | false | false | false | false |
bluelinelabs/Conductor | demo/src/main/java/com/bluelinelabs/conductor/demo/controllers/base/BaseController.kt | 1 | 2198 | package com.bluelinelabs.conductor.demo.controllers.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.appcompat.widget.Toolbar
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.ControllerChangeType
import com.bluelinelabs.conductor.demo.ToolbarProvider
abstract class BaseController(
@LayoutRes private val layoutRes: Int,
args: Bundle? = null
) : Controller(args) {
init {
watchForLeaks()
}
// Note: This is just a quick demo of how an ActionBar *can* be accessed, not necessarily how it *should*
// be accessed. In a production app, this would use Dagger instead.
protected val toolbar: Toolbar?
get() = (activity as? ToolbarProvider)?.toolbar
protected open val title: String? = null
init {
addLifecycleListener(object : LifecycleListener() {
override fun postCreateView(controller: Controller, view: View) {
onViewCreated(view)
toolbar?.let { configureToolbar(it) }
}
})
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
return inflater.inflate(layoutRes, container, false)
}
open fun onViewCreated(view: View) = Unit
override fun onAttach(view: View) {
toolbar?.let { configureToolbar(it) }
super.onAttach(view)
}
override fun onChangeStarted(
changeHandler: ControllerChangeHandler,
changeType: ControllerChangeType
) {
super.onChangeStarted(changeHandler, changeType)
if (changeType.isEnter) {
toolbar?.let { configureMenu(it) }
}
}
open fun configureToolbar(toolbar: Toolbar) {
val title = title ?: return
var parentController = parentController
while (parentController != null) {
if (parentController is BaseController && parentController.title != null) {
return
}
parentController = parentController.parentController
}
toolbar.title = title
}
open fun configureMenu(toolbar: Toolbar) {
toolbar.menu.clear()
}
} | apache-2.0 | fad03f0ac632e7b929050e5b0eeb9654 | 25.178571 | 107 | 0.72293 | 4.607966 | false | true | false | false |
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/power/AndroidPowerManager.kt | 2 | 2763 | package com.fsck.k9.power
import android.annotation.SuppressLint
import android.os.SystemClock
import com.fsck.k9.mail.power.PowerManager
import com.fsck.k9.mail.power.WakeLock
import java.util.concurrent.atomic.AtomicInteger
import timber.log.Timber
import android.os.PowerManager as SystemPowerManager
import android.os.PowerManager.WakeLock as SystemWakeLock
internal class AndroidPowerManager(private val systemPowerManager: SystemPowerManager) : PowerManager {
override fun newWakeLock(tag: String): WakeLock {
return AndroidWakeLock(SystemPowerManager.PARTIAL_WAKE_LOCK, tag)
}
inner class AndroidWakeLock(flags: Int, val tag: String?) : WakeLock {
private val wakeLock: SystemWakeLock = systemPowerManager.newWakeLock(flags, tag)
private val id = wakeLockId.getAndIncrement()
@Volatile
private var startTime: Long? = null
@Volatile
private var timeout: Long? = null
init {
Timber.v("AndroidWakeLock for tag %s / id %d: Create", tag, id)
}
override fun acquire(timeout: Long) {
synchronized(wakeLock) {
wakeLock.acquire(timeout)
}
Timber.v("AndroidWakeLock for tag %s / id %d for %d ms: acquired", tag, id, timeout)
if (startTime == null) {
startTime = SystemClock.elapsedRealtime()
}
this.timeout = timeout
}
@SuppressLint("WakelockTimeout")
override fun acquire() {
synchronized(wakeLock) {
wakeLock.acquire()
}
Timber.v("AndroidWakeLock for tag %s / id %d: acquired with no timeout.", tag, id)
if (startTime == null) {
startTime = SystemClock.elapsedRealtime()
}
timeout = null
}
override fun setReferenceCounted(counted: Boolean) {
synchronized(wakeLock) {
wakeLock.setReferenceCounted(counted)
}
}
override fun release() {
val startTime = this.startTime
if (startTime != null) {
val endTime = SystemClock.elapsedRealtime()
Timber.v(
"AndroidWakeLock for tag %s / id %d: releasing after %d ms, timeout = %d ms",
tag, id, endTime - startTime, timeout
)
} else {
Timber.v("AndroidWakeLock for tag %s / id %d, timeout = %d ms: releasing", tag, id, timeout)
}
synchronized(wakeLock) {
wakeLock.release()
}
this.startTime = null
}
}
companion object {
private val wakeLockId = AtomicInteger(0)
}
}
| apache-2.0 | 40606d67ba7db11078cf82fd224a79a2 | 29.7 | 108 | 0.58451 | 4.813589 | false | false | false | false |
PolymerLabs/arcs | java/arcs/sdk/android/labs/host/IntentArcHostAdapter.kt | 1 | 4977 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.sdk.android.labs.host
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.ResultReceiver
import arcs.android.host.parcelables.ParcelableParticleIdentifier
import arcs.core.common.ArcId
import arcs.core.common.toArcId
import arcs.core.data.Plan
import arcs.core.host.ArcHost
import arcs.core.host.ArcState
import arcs.core.host.ArcStateChangeCallback
import arcs.core.host.ArcStateChangeRegistration
import arcs.core.host.ParticleIdentifier
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
/**
* An [ArcHost] stub that translates API calls into [Intent]s directed at a [Service] using
* [ArcHostHelper] to dispatch them to corresponding [ArcHost] methods.
*
* @param arcHostComponentName the [ComponentName] of the [Service]
* @property hostId the hostId of the remote [ArcHost] instance
* @param sender a callback used to fire the [Intent], overridable to allow testing
*/
class IntentArcHostAdapter(
arcHostComponentName: ComponentName,
override val hostId: String,
sender: (Intent) -> Unit
) : IntentHostAdapter(arcHostComponentName, sender), ArcHost {
override suspend fun registeredParticles(): List<ParticleIdentifier> {
return sendIntentToHostServiceForResult(
hostComponentName.createGetRegisteredParticlesIntent(hostId)
) {
(it as? List<*>)?.map { identifier ->
(identifier as ParcelableParticleIdentifier).actual
}
} ?: emptyList()
}
override suspend fun startArc(partition: Plan.Partition) {
sendIntentToHostServiceForResult(
partition.createStartArcHostIntent(hostComponentName, hostId)
)
}
override suspend fun stopArc(partition: Plan.Partition) {
sendIntentToHostService(
partition.createStopArcHostIntent(hostComponentName, hostId)
)
}
override suspend fun pause() {
sendIntentToHostServiceForResult(hostComponentName.createPauseArcHostIntent(hostId))
}
override suspend fun unpause() {
sendIntentToHostServiceForResult(hostComponentName.createUnpauseArcHostIntent(hostId))
}
override suspend fun waitForArcIdle(arcId: String) =
TODO("watForArcIdle not yet threaded through intent")
override suspend fun lookupArcHostStatus(partition: Plan.Partition): ArcState {
return sendIntentToHostServiceForResult(
partition.createLookupArcStatusIntent(hostComponentName, hostId)
) {
try {
ArcState.fromString(it.toString())
} catch (e: IllegalArgumentException) {
ArcState.errorWith(e)
}
} ?: ArcState.Error
}
override suspend fun isHostForParticle(particle: Plan.Particle) =
registeredParticles().contains(ParticleIdentifier.from(particle.location))
private class ResultReceiverStateChangeHandler(
val block: (ArcId, ArcState) -> Unit
) : ResultReceiver(Handler(Looper.getMainLooper())) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
val scope = CoroutineScope(
EmptyCoroutineContext + Dispatchers.Default + Job() + CoroutineName(
"ArcStateChange"
)
)
scope.launch {
val arcId = requireNotNull(
resultData?.getString(ArcHostHelper.EXTRA_ARCSTATE_CHANGED_ARCID)
) {
"Missing arcId in Intent for onArcStateChangeHandler callback."
}.toArcId()
val arcState = requireNotNull(
resultData?.getString(ArcHostHelper.EXTRA_ARCSTATE_CHANGED_ARCSTATE)
) {
"Missing state in Intent for onArcStateChangeHandler callback."
}.let {
ArcState.fromString(it)
}
block(arcId, arcState)
}
}
}
override suspend fun addOnArcStateChange(
arcId: ArcId,
block: ArcStateChangeCallback
): ArcStateChangeRegistration {
return sendIntentToHostServiceForResult(
hostComponentName.createAddOnArcStateChangeIntent(
hostId,
arcId,
ResultReceiverStateChangeHandler(block)
)
) {
ArcStateChangeRegistration(requireNotNull(it) {
"No callbackId supplied from addOnStateChangeCallback"
}.toString())
} ?: throw IllegalArgumentException("Unable to register state change listener")
}
override fun hashCode(): Int = hostId.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ArcHost
return hostId == other.hostId
}
}
| bsd-3-clause | 09a8055c113b7a86985cd9d7b1564a8f | 32.402685 | 96 | 0.734378 | 4.642724 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/presentation/reputation/ReputationPresenter.kt | 1 | 3395 | package forpdateam.ru.forpda.presentation.reputation
import moxy.InjectViewState
import forpdateam.ru.forpda.common.mvp.BasePresenter
import forpdateam.ru.forpda.entity.remote.reputation.RepData
import forpdateam.ru.forpda.entity.remote.reputation.RepItem
import forpdateam.ru.forpda.model.data.remote.api.reputation.ReputationApi
import forpdateam.ru.forpda.model.repository.avatar.AvatarRepository
import forpdateam.ru.forpda.model.repository.reputation.ReputationRepository
import forpdateam.ru.forpda.presentation.IErrorHandler
import forpdateam.ru.forpda.presentation.ILinkHandler
import forpdateam.ru.forpda.presentation.TabRouter
/**
* Created by radiationx on 03.01.18.
*/
@InjectViewState
class ReputationPresenter(
private val reputationRepository: ReputationRepository,
private val avatarRepository: AvatarRepository,
private val router: TabRouter,
private val linkHandler: ILinkHandler,
private val errorHandler: IErrorHandler
) : BasePresenter<ReputationView>() {
var currentData = RepData()
override fun onFirstViewAttach() {
super.onFirstViewAttach()
loadReputation()
}
fun loadReputation() {
reputationRepository
.loadReputation(currentData.id, currentData.mode, currentData.sort, currentData.pagination.st)
.doOnSubscribe { viewState.setRefreshing(true) }
.doAfterTerminate { viewState.setRefreshing(false) }
.subscribe({
currentData = it
viewState.showReputation(it)
tryShowAvatar(it)
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
fun changeReputation(type: Boolean, message: String) {
reputationRepository
.changeReputation(0, currentData.id, type, message)
.doOnSubscribe { viewState.setRefreshing(true) }
.doAfterTerminate { viewState.setRefreshing(false) }
.subscribe({
viewState.onChangeReputation(it)
loadReputation()
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
private fun tryShowAvatar(data: RepData) {
avatarRepository
.getAvatar(data.nick.orEmpty())
.subscribe({
viewState.showAvatar(it)
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
fun selectPage(page: Int) {
currentData.pagination.st = page
loadReputation()
}
fun setSort(sort: String) {
currentData.sort = sort
loadReputation()
}
fun changeReputationMode() {
currentData.mode = if (currentData.mode == ReputationApi.MODE_FROM) ReputationApi.MODE_TO else ReputationApi.MODE_FROM
loadReputation()
}
fun onItemClick(item: RepItem) {
viewState.showItemDialogMenu(item)
}
fun onItemLongClick(item: RepItem) {
viewState.showItemDialogMenu(item)
}
fun navigateToProfile(userId: Int) {
linkHandler.handle("https://4pda.to/forum/index.php?showuser=$userId", router)
}
fun navigateToMessage(item: RepItem) {
linkHandler.handle(item.sourceUrl, router)
}
}
| gpl-3.0 | c8eabdbc225376dd8dd567bcd4a40111 | 31.644231 | 126 | 0.631517 | 4.788434 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/about/UnifiedAboutTracker.kt | 1 | 1246 | package org.wordpress.android.ui.about
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class UnifiedAboutTracker @Inject constructor(
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper
) {
fun trackScreenShown(screen: String) {
analyticsTrackerWrapper.track(
stat = Stat.ABOUT_SCREEN_SHOWN,
properties = mapOf(
Property.SCREEN.value to screen
)
)
}
fun trackScreenDismissed(screen: String) {
analyticsTrackerWrapper.track(
stat = Stat.ABOUT_SCREEN_DISMISSED,
properties = mapOf(
Property.SCREEN.value to screen
)
)
}
fun trackButtonTapped(button: String) {
analyticsTrackerWrapper.track(
stat = Stat.ABOUT_SCREEN_BUTTON_TAPPED,
properties = mapOf(
Property.BUTTON.value to button
)
)
}
enum class Property(val value: String) {
SCREEN("screen"),
BUTTON("button")
}
}
| gpl-2.0 | 1b274408dd62a76887c122ed37934e95 | 27.976744 | 67 | 0.601124 | 5.257384 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/widget/today/TodayWidgetBlockListViewModel.kt | 1 | 3989 | package org.wordpress.android.ui.stats.refresh.lists.widget.today
import android.content.Context
import kotlinx.coroutines.runBlocking
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.stats.VisitsModel
import org.wordpress.android.fluxc.store.SiteStore
import org.wordpress.android.fluxc.store.stats.insights.TodayInsightsStore
import org.wordpress.android.ui.prefs.AppPrefsWrapper
import org.wordpress.android.ui.stats.refresh.lists.widget.WidgetBlockListProvider.BlockItemUiModel
import org.wordpress.android.ui.stats.refresh.lists.widget.WidgetBlockListProvider.WidgetBlockListViewModel
import org.wordpress.android.ui.stats.refresh.lists.widget.configuration.StatsColorSelectionViewModel.Color
import org.wordpress.android.ui.stats.refresh.utils.MILLION
import org.wordpress.android.ui.stats.refresh.utils.StatsUtils
import org.wordpress.android.viewmodel.ResourceProvider
import javax.inject.Inject
class TodayWidgetBlockListViewModel
@Inject constructor(
private val siteStore: SiteStore,
private val todayInsightsStore: TodayInsightsStore,
private val resourceProvider: ResourceProvider,
private val todayWidgetUpdater: TodayWidgetUpdater,
private val appPrefsWrapper: AppPrefsWrapper,
private val statsUtils: StatsUtils
) : WidgetBlockListViewModel {
private var siteId: Int? = null
private var colorMode: Color = Color.LIGHT
private var appWidgetId: Int? = null
private val mutableData = mutableListOf<BlockItemUiModel>()
override val data: List<BlockItemUiModel> = mutableData
override fun start(
siteId: Int,
colorMode: Color,
appWidgetId: Int
) {
this.siteId = siteId
this.colorMode = colorMode
this.appWidgetId = appWidgetId
}
override fun onDataSetChanged(context: Context) {
siteId?.apply {
val site = siteStore.getSiteByLocalId(this)
if (site != null) {
runBlocking {
todayInsightsStore.fetchTodayInsights(site)
}
todayInsightsStore.getTodayInsights(site)?.let { visitsAndViewsModel ->
val uiModels = buildListItemUiModel(visitsAndViewsModel, this)
if (uiModels != data) {
mutableData.clear()
mutableData.addAll(uiModels)
appWidgetId?.let {
appPrefsWrapper.setAppWidgetHasData(true, it)
}
}
}
} else {
appWidgetId?.let { nonNullAppWidgetId ->
todayWidgetUpdater.updateAppWidget(context, appWidgetId = nonNullAppWidgetId)
}
}
}
}
private fun buildListItemUiModel(
domainModel: VisitsModel,
localSiteId: Int
): List<BlockItemUiModel> {
val layout = when (colorMode) {
Color.DARK -> R.layout.stats_widget_block_item_dark
Color.LIGHT -> R.layout.stats_widget_block_item_light
}
return listOf(
BlockItemUiModel(
layout,
localSiteId,
resourceProvider.getString(R.string.stats_views),
statsUtils.toFormattedString(domainModel.views, MILLION),
resourceProvider.getString(R.string.stats_visitors),
statsUtils.toFormattedString(domainModel.visitors, MILLION)
),
BlockItemUiModel(
layout,
localSiteId,
resourceProvider.getString(R.string.likes),
statsUtils.toFormattedString(domainModel.likes, MILLION),
resourceProvider.getString(R.string.stats_comments),
statsUtils.toFormattedString(domainModel.comments, MILLION)
)
)
}
}
| gpl-2.0 | 183046484cb502d765d584823b6fbf70 | 41.43617 | 107 | 0.635748 | 5.153747 | false | false | false | false |
mdaniel/intellij-community | plugins/git4idea/src/git4idea/index/GitIndexStatusUtil.kt | 9 | 9985 | // 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 git4idea.index
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import git4idea.GitUtil
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.config.GitExecutable
import git4idea.config.GitExecutableManager
import git4idea.config.GitVersion
import git4idea.config.GitVersionSpecialty
import git4idea.i18n.GitBundle
import org.jetbrains.annotations.Nls
const val NUL = "\u0000"
/*
* `git status` output format (porcelain version 1):
*
* XY PATH
* XY PATH\u0000ORIG_PATH
*
* X Y Meaning
* -------------------------------------------------
* [AMD] not updated
* M [ MD] updated in index
* A [ MD] added to index
* D deleted from index
* R [ MD] renamed in index
* C [ MD] copied in index
* [MARC] index and work tree matches
* [ MARC] M work tree changed since index
* [ MARC] D deleted in work tree
* [ D] R renamed in work tree
* [ D] C copied in work tree
* -------------------------------------------------
* D D unmerged, both deleted
* A U unmerged, added by us
* U D unmerged, deleted by them
* U A unmerged, added by them
* D U unmerged, deleted by us
* A A unmerged, both added
* U U unmerged, both modified
* -------------------------------------------------
* ? ? untracked
* ! ! ignored
* -------------------------------------------------
*/
@Throws(VcsException::class)
fun getStatus(project: Project,
root: VirtualFile,
files: List<FilePath> = emptyList(),
withRenames: Boolean,
withUntracked: Boolean,
withIgnored: Boolean): List<GitFileStatus> {
return getFileStatus(project, root, files, withRenames, withUntracked, withIgnored)
.map { GitFileStatus(root, it) }
}
@Throws(VcsException::class)
fun getFileStatus(project: Project,
root: VirtualFile,
files: List<FilePath>,
withRenames: Boolean,
withUntracked: Boolean,
withIgnored: Boolean): List<LightFileStatus.StatusRecord> {
val h = GitUtil.createHandlerWithPaths(files) {
val h = GitLineHandler(project, root, GitCommand.STATUS)
h.setSilent(true)
h.appendParameters(GitExecutableManager.getInstance().tryGetVersion(project) ?: GitVersion.NULL,
withRenames = withRenames, withUntracked = withUntracked, withIgnored = withIgnored)
h
}
val output: String = Git.getInstance().runCommand(h).getOutputOrThrow()
return parseGitStatusOutput(output)
}
@Throws(VcsException::class)
fun getFileStatus(root: VirtualFile, filePath: FilePath, executable: GitExecutable): LightFileStatus {
val h = GitLineHandler(null, VfsUtilCore.virtualToIoFile(root), executable, GitCommand.STATUS, emptyList())
h.setSilent(true)
h.appendParameters(GitExecutableManager.getInstance().getVersion(executable),
withRenames = false, withUntracked = true, withIgnored = true)
h.endOptions()
h.addRelativePaths(filePath)
val output: String = Git.getInstance().runCommand(h).getOutputOrThrow()
if (output.isNotBlank()) {
val gitStatusOutput = parseGitStatusOutput(output)
return gitStatusOutput.firstOrNull() ?: LightFileStatus.Blank
}
val repositoryPath = getFilePath(root, filePath, executable) ?: return LightFileStatus.Blank
return LightFileStatus.NotChanged(repositoryPath)
}
private fun GitLineHandler.appendParameters(gitVersion: GitVersion,
withRenames: Boolean = true, withUntracked: Boolean = true, withIgnored: Boolean = false) {
addParameters("--porcelain", "-z")
if (!withRenames) {
if (GitVersionSpecialty.STATUS_SUPPORTS_NO_RENAMES.existsIn(gitVersion)) {
addParameters("--no-renames")
}
}
addParameters("--untracked-files=${if (withUntracked) "all" else "no"}")
if (GitVersionSpecialty.STATUS_SUPPORTS_IGNORED_MODES.existsIn(gitVersion)) {
if (withIgnored) {
addParameters("--ignored=matching")
}
else {
addParameters("--ignored=no")
}
}
else if (withIgnored) {
addParameters("--ignored")
}
}
@Throws(VcsException::class)
fun getFilePath(root: VirtualFile, filePath: FilePath, executable: GitExecutable): String? {
val handler = GitLineHandler(null, VfsUtilCore.virtualToIoFile(root),
executable, GitCommand.LS_FILES, emptyList())
handler.addParameters("--full-name")
handler.addRelativePaths(filePath)
handler.setSilent(true)
return Git.getInstance().runCommand(handler).getOutputOrThrow().lines().firstOrNull()
}
@Throws(VcsException::class)
private fun parseGitStatusOutput(output: String): List<LightFileStatus.StatusRecord> {
val result = mutableListOf<LightFileStatus.StatusRecord>()
val split = output.split(NUL).toTypedArray()
val it = split.iterator()
while (it.hasNext()) {
val line = it.next()
if (StringUtil.isEmptyOrSpaces(line)) continue // skip empty lines if any (e.g. the whole output may be empty on a clean working tree).
if (line.startsWith("starting fsmonitor-daemon in ")) continue // skip debug output from experimental daemon in git-for-windows-2.33
// format: XY_filename where _ stands for space.
if (line.length < 4 || line[2] != ' ') { // X, Y, space and at least one symbol for the file
throwGFE(GitBundle.message("status.exception.message.line.is.too.short"), output, line, '0', '0')
}
val xStatus = line[0]
val yStatus = line[1]
if (!isKnownStatus(xStatus) || !isKnownStatus(yStatus)) {
throwGFE(GitBundle.message("status.exception.message.unexpected"), output, line, xStatus, yStatus)
}
val pathPart = line.substring(3) // skipping the space
if (isRenamed(xStatus) || isRenamed(yStatus)) {
if (!it.hasNext()) {
throwGFE(GitBundle.message("status.exception.message.missing.path"), output, line, xStatus, yStatus)
continue
}
val origPath = it.next() // read the "from" filepath which is separated also by NUL character.
result.add(LightFileStatus.StatusRecord(xStatus, yStatus, pathPart, origPath = origPath))
}
else {
result.add(LightFileStatus.StatusRecord(xStatus, yStatus, pathPart))
}
}
return result
}
private fun throwGFE(@Nls message: String, @NlsSafe output: String, @NlsSafe line: String, @NlsSafe xStatus: Char, @NlsSafe yStatus: Char) {
throw VcsException(GitBundle.message("status.exception.message.format.message.xstatus.ystatus.line.output",
message, xStatus, yStatus, line, output))
}
private fun isKnownStatus(status: Char): Boolean {
return status == ' ' || status == 'M' || status == 'A' || status == 'D' || status == 'C' || status == 'R' || status == 'U' || status == 'T' || status == '!' || status == '?'
}
@Throws(VcsException::class)
internal fun getFileStatus(status: StatusCode): FileStatus? {
return when (status) {
' ' -> null
'M', 'R', 'C', 'T' -> FileStatus.MODIFIED
'A' -> FileStatus.ADDED
'D' -> FileStatus.DELETED
'U' -> FileStatus.MERGED_WITH_CONFLICTS
'!' -> FileStatus.IGNORED
'?' -> FileStatus.UNKNOWN
else -> throw VcsException(GitBundle.message("status.exception.message.unexpected.status", status))
}
}
typealias StatusCode = Char
internal fun isIgnored(status: StatusCode) = status == '!'
internal fun isUntracked(status: StatusCode) = status == '?'
fun isRenamed(status: StatusCode) = status == 'R' || status == 'C'
internal fun isAdded(status: StatusCode) = status == 'A'
internal fun isIntendedToBeAdded(index: StatusCode, workTree: StatusCode) = index == ' ' && workTree == 'A'
internal fun isDeleted(status: StatusCode) = status == 'D'
internal fun isConflicted(index: StatusCode, workTree: StatusCode): Boolean {
return (index == 'D' && workTree == 'D') ||
(index == 'A' && workTree == 'A') ||
(index == 'T' && workTree == 'T') ||
(index == 'U' || workTree == 'U')
}
sealed class LightFileStatus {
internal abstract fun getFileStatus(): FileStatus
object Blank : LightFileStatus() {
override fun getFileStatus(): FileStatus = FileStatus.NOT_CHANGED
}
data class NotChanged(val path: String) : LightFileStatus() {
override fun getFileStatus(): FileStatus = FileStatus.NOT_CHANGED
}
data class StatusRecord(val index: StatusCode,
val workTree: StatusCode,
val path: String,
val origPath: String? = null) : LightFileStatus() {
override fun getFileStatus(): FileStatus {
if (isConflicted()) return FileStatus.MERGED_WITH_CONFLICTS
return getFileStatus(index) ?: getFileStatus(workTree) ?: FileStatus.NOT_CHANGED
}
internal fun isConflicted(): Boolean = isConflicted(index, workTree)
}
}
fun LightFileStatus.isTracked(): Boolean {
return when (this) {
LightFileStatus.Blank -> false
is LightFileStatus.NotChanged -> true
is LightFileStatus.StatusRecord -> !isIgnored(index) && !isUntracked(index)
}
}
val LightFileStatus.repositoryPath: String?
get() = when (this) {
LightFileStatus.Blank -> null
is LightFileStatus.NotChanged -> path
is LightFileStatus.StatusRecord -> if (!isTracked() || index == 'A' || workTree == 'A') null else origPath ?: path
} | apache-2.0 | 4a84077aed9f6ffd1a282c13f2ef475d | 38.626984 | 175 | 0.655784 | 4.163887 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectFrameAllocator.kt | 1 | 14032 | // 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.openapi.project.impl
import com.intellij.configurationStore.saveSettings
import com.intellij.conversion.CannotConvertException
import com.intellij.diagnostic.runActivity
import com.intellij.ide.IdeBundle
import com.intellij.ide.RecentProjectsManagerBase
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.idea.SplashManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.application.impl.withModalContext
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.progress.TaskCancellation
import com.intellij.openapi.progress.util.ProgressDialogUI
import com.intellij.openapi.progress.util.ProgressDialogWrapper
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.impl.GlassPaneDialogWrapperPeer
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.*
import com.intellij.platform.ProjectSelfieUtil
import com.intellij.ui.IdeUICustomization
import com.intellij.ui.ScreenUtil
import com.intellij.ui.scale.ScaleContext
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus
import java.awt.Dimension
import java.awt.Frame
import java.awt.Image
import java.awt.Window
import java.io.EOFException
import java.nio.file.Path
import javax.swing.SwingUtilities
import kotlin.math.min
internal open class ProjectFrameAllocator(private val options: OpenProjectTask) {
open suspend fun <T : Any> run(scope: CoroutineScope, task: suspend (saveTemplateJob: Job?) -> T): T {
return task(scope.saveTemplateAsync(options))
}
/**
* Project is loaded and is initialized, project services and components can be accessed.
* But start-up and post start-up activities are not yet executed.
* Executed under a modal progress dialog.
*/
open suspend fun projectLoaded(project: Project) {}
open suspend fun projectNotLoaded(cannotConvertException: CannotConvertException?) {
cannotConvertException?.let { throw cannotConvertException }
}
open fun projectOpened(project: Project) {}
}
private fun CoroutineScope.saveTemplateAsync(options: OpenProjectTask): Job? {
if (options.isNewProject && options.useDefaultProjectAsTemplate && options.project == null) {
return launch(Dispatchers.IO) {
saveSettings(ProjectManager.getInstance().defaultProject, forceSavingAllSettings = true)
}
}
else {
return null
}
}
internal class ProjectUiFrameAllocator(val options: OpenProjectTask, val projectStoreBaseDir: Path) : ProjectFrameAllocator(options) {
private val deferredProjectFrameHelper = CompletableDeferred<ProjectFrameHelper>()
override suspend fun <T : Any> run(scope: CoroutineScope, task: suspend (saveTemplateJob: Job?) -> T): T {
val deferredWindow = scope.async(Dispatchers.EDT + ModalityState.any().asContextElement()) {
val frameManager = createFrameManager()
val frameHelper = frameManager.createFrameHelper(this@ProjectUiFrameAllocator)
frameHelper.init()
val window = frameManager.getWindow()
// implOptions == null - not via recents project - show frame immediately
if (options.showFrameAsap || options.implOptions == null) {
frameManager.getWindow().isVisible = true
}
deferredProjectFrameHelper.complete(frameHelper)
window
}
return withModalContext {
// execute saveTemplateAsync under modal progress - write-safe context for saving template settings
val saveTemplateDeferred = saveTemplateAsync(options)
val showIndicatorJob = showModalIndicatorForProjectLoading(
windowDeferred = deferredWindow,
title = getProgressTitle(),
)
try {
task(saveTemplateDeferred)
}
finally {
showIndicatorJob.cancel()
}
}
}
@NlsContexts.ProgressTitle
private fun getProgressTitle(): String {
val projectName = options.projectName ?: (projectStoreBaseDir.fileName ?: projectStoreBaseDir).toString()
return IdeUICustomization.getInstance().projectMessage("progress.title.project.loading.name", projectName)
}
// executed in EDT
private fun createFrameManager(): ProjectUiFrameManager {
options.frameManager?.let {
return it
}
(WindowManager.getInstance() as WindowManagerImpl).removeAndGetRootFrame()?.let { freeRootFrame ->
return object : ProjectUiFrameManager {
override suspend fun createFrameHelper(allocator: ProjectUiFrameAllocator) = freeRootFrame
override fun getWindow() = freeRootFrame.frameOrNull!!
}
}
return runActivity("create a frame") {
val preAllocated = SplashManager.getAndUnsetProjectFrame() as IdeFrameImpl?
if (preAllocated == null) {
val frameInfo = options.frameInfo
if (frameInfo == null) {
DefaultProjectUiFrameManager(frame = createNewProjectFrame(null))
}
else {
SingleProjectUiFrameManager(frameInfo = frameInfo, frame = createNewProjectFrame(frameInfo))
}
}
else {
SplashProjectUiFrameManager(preAllocated)
}
}
}
override suspend fun projectLoaded(project: Project) {
val windowManager = WindowManager.getInstance() as WindowManagerImpl
val frameHelper = deferredProjectFrameHelper.await()
withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
runActivity("project frame assigning") {
windowManager.assignFrame(frameHelper, project)
}
// not as a part of a project modal dialog
val projectScope = (project as ProjectEx).coroutineScope
projectScope.launch {
val toolWindowManager = ToolWindowManager.getInstance(project) as? ToolWindowManagerImpl ?: return@launch
// OpenFilesActivity inits component
val fileEditorManager = FileEditorManagerEx.getInstanceEx(project)
runActivity("tool window pane creation") {
toolWindowManager.init(frameHelper, fileEditorManager)
}
}
projectScope.launch(Dispatchers.EDT + ModalityState.any().asContextElement()) {
val rootPane = frameHelper.rootPane!!
runActivity("north components updating") {
rootPane.updateNorthComponents()
}
runActivity("toolbar updating") {
rootPane.initOrCreateToolbar(project)
}
frameHelper.frameOrNull?.isVisible = true
}
}
}
override suspend fun projectNotLoaded(cannotConvertException: CannotConvertException?) {
val frameHelper = if (deferredProjectFrameHelper.isCompleted) {
deferredProjectFrameHelper.await()
}
else {
deferredProjectFrameHelper.cancel("projectNotLoaded")
null
}
withContext(Dispatchers.EDT) {
if (cannotConvertException != null) {
Messages.showErrorDialog(
frameHelper?.frameOrNull,
IdeBundle.message("error.cannot.convert.project", cannotConvertException.message),
IdeBundle.message("title.cannot.convert.project")
)
}
if (frameHelper != null) {
// projectLoaded was called, but then due to some error, say cancellation, still projectNotLoaded is called
if (frameHelper.project == null) {
Disposer.dispose(frameHelper)
}
else {
WindowManagerEx.getInstanceEx().releaseFrame(frameHelper)
}
}
}
}
}
@Suppress("DuplicatedCode")
private fun CoroutineScope.showModalIndicatorForProjectLoading(
windowDeferred: Deferred<Window>,
title: @NlsContexts.ProgressTitle String,
): Job {
return launch(Dispatchers.IO) {
delay(300L)
val mainJob = [email protected]
val window = windowDeferred.await()
withContext(Dispatchers.EDT) {
val ui = ProgressDialogUI()
ui.progressBar.isIndeterminate = true
ui.initCancellation(TaskCancellation.cancellable()) {
mainJob.cancel("button cancel")
}
ui.backgroundButton.isVisible = false
ui.updateTitle(title)
val dialog = ProgressDialogWrapper(
panel = ui.panel,
cancelAction = {
mainJob.cancel("dialog cancel")
},
peerFactory = java.util.function.Function { GlassPaneDialogWrapperPeer(window, it) }
)
dialog.setUndecorated(true)
dialog.pack()
launch { // will be run in an inner event loop
val focusComponent = ui.cancelButton
val previousFocusOwner = SwingUtilities.getWindowAncestor(focusComponent)?.mostRecentFocusOwner
focusComponent.requestFocusInWindow()
try {
awaitCancellation()
}
finally {
dialog.close(DialogWrapper.OK_EXIT_CODE)
previousFocusOwner?.requestFocusInWindow()
}
}
window.isVisible = true
// will spin an inner event loop
dialog.show()
}
}
}
private fun restoreFrameState(frameHelper: ProjectFrameHelper, frameInfo: FrameInfo) {
val bounds = frameInfo.bounds?.let { FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(it) }
val frame = frameHelper.frameOrNull!!
if (bounds != null && FrameInfoHelper.isMaximized(frameInfo.extendedState) && frame.extendedState == Frame.NORMAL) {
frame.rootPane.putClientProperty(IdeFrameImpl.NORMAL_STATE_BOUNDS, bounds)
}
if (bounds != null) {
frame.bounds = bounds
}
frame.extendedState = frameInfo.extendedState
if (frameInfo.fullScreen && FrameInfoHelper.isFullScreenSupportedInCurrentOs()) {
frameHelper.toggleFullScreen(true)
}
}
@ApiStatus.Internal
internal fun createNewProjectFrame(frameInfo: FrameInfo?): IdeFrameImpl {
val frame = IdeFrameImpl()
SplashManager.hideBeforeShow(frame)
val deviceBounds = frameInfo?.bounds
if (deviceBounds == null) {
val size = ScreenUtil.getMainScreenBounds().size
size.width = min(1400, size.width - 20)
size.height = min(1000, size.height - 40)
frame.size = size
frame.setLocationRelativeTo(null)
}
else {
val bounds = FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(deviceBounds)
val state = frameInfo.extendedState
val isMaximized = FrameInfoHelper.isMaximized(state)
if (isMaximized && frame.extendedState == Frame.NORMAL) {
frame.rootPane.putClientProperty(IdeFrameImpl.NORMAL_STATE_BOUNDS, bounds)
}
frame.bounds = bounds
frame.extendedState = state
}
frame.minimumSize = Dimension(340, frame.minimumSize.height)
return frame
}
internal interface ProjectUiFrameManager {
// executed in EDT
suspend fun createFrameHelper(allocator: ProjectUiFrameAllocator): ProjectFrameHelper
fun getWindow(): Window
}
private class SplashProjectUiFrameManager(private val frame: IdeFrameImpl) : ProjectUiFrameManager {
override fun getWindow() = frame
override suspend fun createFrameHelper(allocator: ProjectUiFrameAllocator): ProjectFrameHelper {
runActivity("project frame initialization") {
return ProjectFrameHelper(frame, null)
}
}
}
private class DefaultProjectUiFrameManager(private val frame: IdeFrameImpl) : ProjectUiFrameManager {
override fun getWindow() = frame
override suspend fun createFrameHelper(allocator: ProjectUiFrameAllocator): ProjectFrameHelper {
runActivity("project frame initialization") {
val info = RecentProjectsManagerBase.getInstanceEx().getProjectMetaInfo(allocator.projectStoreBaseDir)
val frameInfo = info?.frame
val frameHelper = ProjectFrameHelper(frame, readProjectSelfie(info?.projectWorkspaceId, frame))
// must be after preInit (frame decorator is required to set full screen mode)
if (frameInfo?.bounds == null) {
(WindowManager.getInstance() as WindowManagerImpl).defaultFrameInfoHelper.info?.let {
restoreFrameState(frameHelper, it)
}
}
else {
restoreFrameState(frameHelper, frameInfo)
}
return frameHelper
}
}
}
private class SingleProjectUiFrameManager(private val frameInfo: FrameInfo, private val frame: IdeFrameImpl) : ProjectUiFrameManager {
override fun getWindow() = frame
override suspend fun createFrameHelper(allocator: ProjectUiFrameAllocator): ProjectFrameHelper {
runActivity("project frame initialization") {
val frameHelper = ProjectFrameHelper(frame, readProjectSelfie(allocator.options.projectWorkspaceId, frame))
if (frameInfo.fullScreen && FrameInfoHelper.isFullScreenSupportedInCurrentOs()) {
frameHelper.toggleFullScreen(true)
}
return frameHelper
}
}
}
private fun readProjectSelfie(projectWorkspaceId: String?, frame: IdeFrameImpl): Image? {
if (projectWorkspaceId != null && Registry.`is`("ide.project.loading.show.last.state", false)) {
try {
return ProjectSelfieUtil.readProjectSelfie(projectWorkspaceId, ScaleContext.create(frame))
}
catch (e: Throwable) {
if (e.cause !is EOFException) {
logger<ProjectFrameAllocator>().warn(e)
}
}
}
return null
}
internal val OpenProjectTask.frameInfo: FrameInfo?
get() = (implOptions as OpenProjectImplOptions?)?.frameInfo
internal val OpenProjectTask.frameManager: ProjectUiFrameManager?
get() = (implOptions as OpenProjectImplOptions?)?.frameManager
internal data class OpenProjectImplOptions(
@JvmField val frameInfo: FrameInfo? = null,
@JvmField val frameManager: ProjectUiFrameManager? = null,
) | apache-2.0 | d3993c6aaaa1057f3347463dd5bbd85c | 36.026385 | 134 | 0.735604 | 4.79235 | false | false | false | false |
andrewoma/kommon | src/test/kotlin/com/github/andrewoma/kommon/script/ProcessTest.kt | 1 | 3578 | /*
* Copyright (c) 2014 Andrew O'Malley
*
* 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 com.github.andrewoma.kommon.script
import org.junit.Ignore
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.fail
class ProcessTest {
@Test fun `shell should capture output by default`() {
val result = shell("echo 'Hello' && echo 'Goodbye' 1>&2")
assertEquals("Hello", result.out.trim())
assertEquals("Goodbye", result.error.trim())
}
@Test fun `shell without capture should not capture output`() {
val result = shell("echo 'Hello' && echo 'Goodbye' 1>&2", captureOut = false, captureError = false)
assertEquals("", result.out)
assertEquals("", result.error)
}
@Test fun `shell with redirected stderr should capture error in out`() {
val out = shell("echo 'Hello' && echo 'Goodbye' 1>&2", redirectError = true).out
assertEquals("Hello\nGoodbye", out.trim())
}
@Test fun `shell should have access to passed environment`() {
val out = shell("echo \$HELLO \$WORLD", environment = mapOf("HELLO" to "foo", "WORLD" to "bar")).out
assertEquals("foo bar", out.trim())
}
@Test(expected = IllegalStateException::class) fun `shell with default verification should fail on non-zero exit code`() {
shell("exit 1")
}
@Test fun `shell with default verification should succeed on zero exit code`() {
shell("exit 0")
}
@Test fun `shell should honour custom verification function`() {
shell("exit 1", verify = { true })
}
@Test fun `exec should allow verification`() {
val result = exec(listOf("/bin/bash", "-c", "echo 'Hello'")).result()
result.verify { it == 0 }
}
@Test fun `env should give access to environment variables`() {
assertNotNull(env("HOME"))
}
@Ignore @Test fun `shell should give meaningful errors on failure`() {
try {
shell("echo 'Hello' && echo 'Goodbye' 1>&2 && exit 1")
fail()
} catch(e: IllegalStateException) {
val expected = """Command exit code failed verification.
Command: echo 'Hello' && echo 'Goodbye' 1>&2 && exit 1
Directory: /Users/andrew/dev/projects/kommon
Environment: {}
RedirectError: false
CaptureOut: true
CaptureError: true
ExitCode: 1
Out: Hello
Error: Goodbye
"""
assertEquals(expected, e.message)
}
}
}
| mit | 539db9f714f4b9130c7fc0388905e1d7 | 36.663158 | 126 | 0.657909 | 4.321256 | false | true | false | false |
micolous/metrodroid | src/main/java/au/id/micolous/metrodroid/fragment/KeysFragment.kt | 1 | 15565 | /*
* CardKeysFragment.kt
*
* Copyright 2012 Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.fragment
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.database.MatrixCursor
import android.database.MergeCursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.*
import androidx.annotation.StringRes
import androidx.fragment.app.ListFragment
import androidx.loader.app.LoaderManager
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import au.id.micolous.farebot.R
import au.id.micolous.metrodroid.MetrodroidApplication
import au.id.micolous.metrodroid.activity.AddKeyActivity
import au.id.micolous.metrodroid.card.classic.ClassicAndroidReader
import au.id.micolous.metrodroid.key.*
import au.id.micolous.metrodroid.key.KeyFormat
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.provider.CardKeyProvider
import au.id.micolous.metrodroid.provider.KeysTableColumns
import au.id.micolous.metrodroid.serializers.CardSerializer
import au.id.micolous.metrodroid.util.BetterAsyncTask
import au.id.micolous.metrodroid.util.Preferences
import au.id.micolous.metrodroid.util.Utils
import kotlinx.serialization.json.Json
import kotlinx.serialization.toUtf8Bytes
import org.jetbrains.annotations.NonNls
class KeysFragment : ListFragment(), AdapterView.OnItemLongClickListener {
private var mActionMode: ActionMode? = null
private var mActionKeyId: Int = 0
private val mActionModeCallback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
val inflater = mode.menuInflater
inflater.inflate(R.menu.keys_contextual, menu)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
menu.findItem(R.id.export_key).isVisible = false
}
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
if (item.itemId == R.id.delete_key) {
if (Preferences.hideCardNumbers) {
AlertDialog.Builder(activity)
.setTitle(R.string.cant_delete_with_obfuscation)
.setMessage(R.string.cant_delete_with_obfuscation_message)
.setPositiveButton(android.R.string.ok) { dialog, _ -> dialog.dismiss() }
.show()
return true
}
var keys: CardKeys? = null
try {
keys = CardKeysDB(MetrodroidApplication.instance).forID(mActionKeyId)
} catch (e: Exception) {
Log.d(TAG, "error in deleting key?")
}
val deleteMessage = Localizer.localizeString(R.string.delete_key_confirm_message,
keys?.description ?: "??", keys?.fileType ?: "??")
AlertDialog.Builder(activity)
.setTitle(R.string.delete_key_confirm_title)
.setMessage(deleteMessage)
.setPositiveButton(R.string.delete) { dialog, _ ->
object : BetterAsyncTask<Void?>(activity!!, false, false) {
override fun doInBackground(): Void? {
val uri = ContentUris.withAppendedId(CardKeyProvider.CONTENT_URI, mActionKeyId.toLong())
activity!!.contentResolver.delete(uri, null, null)
return null
}
override fun onResult(result: Void?) {
mActionMode!!.finish()
(listAdapter as KeysAdapter).notifyDataSetChanged()
}
}.execute()
dialog.dismiss()
}
.setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.cancel() }
.show()
return true
} else if (item.itemId == R.id.export_key) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
val i = Intent(Intent.ACTION_CREATE_DOCUMENT)
i.addCategory(Intent.CATEGORY_OPENABLE)
i.type = "application/json"
i.putExtra(Intent.EXTRA_TITLE, STD_EXPORT_FILENAME)
startActivityForResult(Intent.createChooser(i, Localizer.localizeString(R.string.export_filename)), REQUEST_SAVE_FILE)
}
}
return false
}
override fun onDestroyActionMode(mode: ActionMode) {
mActionKeyId = 0
mActionMode = null
}
}
private val mLoaderCallbacks = object : LoaderManager.LoaderCallbacks<android.database.Cursor> {
override fun onCreateLoader(i: Int, bundle: Bundle?): Loader<Cursor> {
return KeyLoader(MetrodroidApplication.instance)
}
override fun onLoadFinished(cursorLoader: Loader<Cursor>, cursor: Cursor?) {
(listView.adapter as CursorAdapter).swapCursor(cursor)
setListShown(true)
}
override fun onLoaderReset(cursorLoader: Loader<Cursor>) {}
}
private class KeyLoader internal constructor(context: Context) : CursorLoader(context, CardKeyProvider.CONTENT_URI, null, null, null, KeysTableColumns.CREATED_AT + " DESC") {
private fun list2Cursor(list: List<CardKeysFromFiles.CardKeyRead>): Cursor {
val cur = MatrixCursor(arrayOf(KeysTableColumns._ID, KeysTableColumns.CARD_ID, KeysTableColumns.CARD_TYPE, KeysTableColumns.KEY_DATA))
for ((id, tagId, cardType, keyData) in list) {
cur.addRow(arrayOf(id, tagId, cardType, keyData))
}
return cur
}
override fun loadInBackground(): Cursor? {
val cursor: Cursor? = super.loadInBackground()
val embedList = ClassicAndroidReader.getKeyRetrieverEmbed(context).getKeyList()
if (embedList.isEmpty())
return cursor
val embedCursor = list2Cursor(embedList)
return MergeCursor(arrayOf(cursor, embedCursor))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setEmptyText(getString(R.string.no_keys))
listView.onItemLongClickListener = this
listAdapter = KeysAdapter(activity!!)
loaderManager.initLoader(0, null, mLoaderCallbacks)
}
override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
val cursor = listAdapter.getItem(position) as Cursor
mActionKeyId = cursor.getInt(cursor.getColumnIndex(KeysTableColumns._ID))
mActionMode = activity!!.startActionMode(mActionModeCallback)
return true
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_keys_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.add_key) {
val i = Utils.getContentIntent(listOf("application/json", "application/x-extension-bin"))
startActivityForResult(i, REQUEST_SELECT_FILE)
return true
} else if (item.itemId == R.id.key_more_info) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://micolous.github.io/metrodroid/key_formats")))
}
return false
}
@SuppressLint("StaticFieldLeak")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val uri: Uri? = data?.data
try {
if (resultCode == Activity.RESULT_OK && uri != null) {
when (requestCode) {
REQUEST_SELECT_FILE -> {
val type = activity!!.contentResolver.getType(uri)
Log.d(TAG, "REQUEST_SELECT_FILE content_type = $type")
val f: KeyFormat = Utils.detectKeyFormat(activity!!, uri)
Log.d(TAG, "Detected file format: " + f.name)
when (f) {
KeyFormat.JSON_MFC_STATIC -> {
// Static keys can't be prompted
@StringRes val err = importKeysFromStaticJSON(activity!!, uri)
if (err != 0) {
Toast.makeText(activity, err, Toast.LENGTH_SHORT).show()
}
}
KeyFormat.JSON_MFC, KeyFormat.JSON_MFC_NO_UID, KeyFormat.RAW_MFC -> startActivity(Intent(Intent.ACTION_VIEW, uri, activity, AddKeyActivity::class.java))
else -> Toast.makeText(activity, R.string.invalid_key_file, Toast.LENGTH_SHORT).show()
}
}
REQUEST_SAVE_FILE -> {
Log.d(TAG, "REQUEST_SAVE_FILE")
object : BetterAsyncTask<Void?>(activity!!, false, false) {
override fun doInBackground(): Void? {
val ctxt = MetrodroidApplication.instance
val os = ctxt.contentResolver.openOutputStream(uri)!!
val keys = ClassicAndroidReader.getKeyRetriever(ctxt).forID(mActionKeyId)!!
val json = keys.toJSON().toString()
os.write(json.toUtf8Bytes())
os.close()
return null
}
override fun onResult(result: Void?) {
Toast.makeText(MetrodroidApplication.instance, R.string.file_exported, Toast.LENGTH_SHORT).show()
mActionMode!!.finish()
}
}.execute()
}
}
}
} catch (ex: Exception) {
Utils.showError(activity!!, ex)
}
}
private class KeysAdapter internal constructor(activity: Activity) : ResourceCursorAdapter(activity, android.R.layout.simple_list_item_2, null, false) {
override fun bindView(view: View, context: Context, cursor: Cursor) {
@NonNls val id = cursor.getString(cursor.getColumnIndex(KeysTableColumns.CARD_ID))
val type = cursor.getString(cursor.getColumnIndex(KeysTableColumns.CARD_TYPE))
val textView1 = view.findViewById<TextView>(android.R.id.text1)
val textView2 = view.findViewById<TextView>(android.R.id.text2)
when (type) {
CardKeys.TYPE_MFC_STATIC -> {
val keyData = cursor.getString(cursor.getColumnIndex(KeysTableColumns.KEY_DATA))
var desc: String? = null
var fileType: String? = null
try {
val k = ClassicStaticKeys.fromJSON(
CardSerializer.jsonPlainStable.parseJson(keyData).jsonObject,
"cursor/$id")
desc = k!!.description
fileType = k.fileType
} catch (ignored: Exception) {
}
if (desc != null) {
textView1.text = desc
} else {
textView1.setText(R.string.untitled_key_group)
}
if (fileType != null) {
textView2.text = fileType
} else {
textView2.setText(R.string.unknown)
}
}
CardKeys.TYPE_MFC -> {
val keyData = cursor.getString(cursor.getColumnIndex(KeysTableColumns.KEY_DATA))
var fileType: String? = null
try {
val k = ClassicCardKeys.fromJSON(
CardSerializer.jsonPlainStable.parseJson(keyData).jsonObject,
"cursor/$id")
fileType = k.fileType
} catch (ignored: Exception) {
}
if (Preferences.hideCardNumbers) {
textView1.setText(R.string.hidden_card_number)
} else {
textView1.text = id
}
if (fileType != null) {
textView2.text = fileType
} else {
textView2.setText(R.string.unknown)
}
}
else -> {
textView1.setText(R.string.unknown)
textView2.setText(R.string.unknown)
}
}
}
}
companion object {
private const val REQUEST_SELECT_FILE = 1
private const val REQUEST_SAVE_FILE = 2
private const val STD_EXPORT_FILENAME = "Metrodroid-Keys.json"
private const val TAG = "KeysFragment"
@StringRes
private fun importKeysFromStaticJSON(activity: Activity, uri: Uri): Int {
val stream = activity.contentResolver.openInputStream(uri) ?: return R.string.key_file_empty
val keyData = stream.readBytes()
try {
val json = CardSerializer.jsonPlainStable.parseJson(String(keyData, Charsets.UTF_8))
Log.d(TAG, "inserting key")
// Test that we can deserialise this
val k = ClassicStaticKeys.fromJSON(json.jsonObject, uri.path ?: "unspecified")
if (k?.isEmpty() != false) {
return R.string.key_file_empty
}
InsertKeyTask(activity, k).execute()
return 0
} catch (ex: Exception) {
Log.d(TAG, "jsonException", ex)
return R.string.invalid_json
}
}
}
}
| gpl-3.0 | 506358c67d79ef19fb8b56dcf5dc4a7e | 40.954178 | 180 | 0.562287 | 5.061789 | false | false | false | false |
lnr0626/cfn-templates | base-models/src/main/kotlin/com/lloydramey/cfn/model/Template.kt | 1 | 2211 | /*
* Copyright 2017 Lloyd Ramey <[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.lloydramey.cfn.model
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.lloydramey.cfn.model.functions.ConditionFunction
import com.lloydramey.cfn.model.resources.Resource
import com.lloydramey.cfn.model.resources.ResourceProperties
internal object Jackson {
val mapper = jacksonObjectMapper()
init {
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper.propertyNamingStrategy = PropertyNamingStrategy.UPPER_CAMEL_CASE
mapper.enable(SerializationFeature.INDENT_OUTPUT)
}
}
@JsonPropertyOrder("AWSTemplateFormatVersion", "Description", "Metadata", "Parameters", "Mappings", "Conditions", "Resources", "Outputs")
data class Template(
var description: String = "",
val metadata: Map<String, Any> = mutableMapOf(),
val parameters: Map<String, Parameter> = mutableMapOf(),
val mappings: Map<String, Mapping> = mutableMapOf(),
val conditions: Map<String, ConditionFunction> = mutableMapOf(),
val resources: Map<String, Resource<ResourceProperties>> = mutableMapOf(),
val outputs: Map<String, Output> = mutableMapOf()
) {
@JsonProperty("AWSTemplateFormatVersion")
val version = "2010-09-09"
override fun toString(): String {
return Jackson.mapper.writeValueAsString(this)
}
} | apache-2.0 | 8ce7984b37de24c18b364e6e66ff3507 | 39.962963 | 137 | 0.762099 | 4.466667 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/learn/CourseManager.kt | 3 | 6702 | // 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 training.learn
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.KeyedLazyInstanceEP
import com.intellij.util.containers.MultiMap
import training.lang.LangManager
import training.lang.LangSupport
import training.learn.course.IftModule
import training.learn.course.LearningCourse
import training.learn.course.LearningCourseBase
import training.learn.course.Lesson
import training.learn.lesson.LessonManager
import training.statistic.LessonStartingWay
import training.util.*
@Service(Service.Level.APP)
class CourseManager internal constructor() : Disposable {
val previousOpenedVersion: BuildNumber?
init {
val strBuild = PropertiesComponent.getInstance().getValue(LEARNING_PANEL_OPENED_IN)
previousOpenedVersion = if (strBuild == null) {
null
}
else {
val parseVersion = BuildNumber.fromString(strBuild)
if (parseVersion == null) {
thisLogger().error("Cannot parse previous version $strBuild")
}
parseVersion
}
}
var unfoldModuleOnInit by WeakReferenceDelegator<IftModule>()
/**
* [isExternal] equals true if [module] comes from the third party plugin
*/
private class ModuleInfo(val module: IftModule, val isExternal: Boolean)
private val languageCourses: MultiMap<LangSupport, ModuleInfo> = MultiMap.create()
private val commonCourses: MultiMap<String, ModuleInfo> = MultiMap.create()
private var currentConfiguration = switchOnExperimentalLessons
val modules: Collection<IftModule>
get() {
prepareLangModules()
return LangManager.getInstance().getLangSupport()?.let { languageCourses[it].map(ModuleInfo::module) } ?: emptyList()
}
val lessonsForModules: List<Lesson>
get() = modules.map { it.lessons }.flatten()
val newLessons: List<Lesson>
get() {
val previousVersion = previousOpenedVersion ?: return lessonsForModules.filter { it.properties.availableSince != null }
return lessonsForModules.filter {
if (it.passed) return@filter false // It is strange situation actually
val availableSince = it.properties.availableSince ?: return@filter false
val lessonVersion = BuildNumber.fromString(availableSince)
if (lessonVersion == null) {
thisLogger().error("Invalid lesson version: $availableSince")
return@filter false
}
lessonVersion > previousVersion
}
}
val currentCourse: LearningCourse?
get() = LangManager.getInstance().getLanguageId()?.let { lang ->
COURSE_MODULES_EP.extensionList.find { lang.equals(it.language, ignoreCase = true) }?.instance
}
override fun dispose() {
}
init {
for (ep in listOf(COMMON_COURSE_MODULES_EP, COURSE_MODULES_EP)) {
ep.addChangeListener(Runnable {
clearModules()
for (toolWindow in getAllLearnToolWindows()) {
toolWindow.reinitViews()
}
}, this)
}
}
fun clearModules() {
languageCourses.clear()
commonCourses.clear()
}
/**
* @param projectWhereToOpen -- where to open projectWhereToOpen
* @param forceStartLesson -- force start lesson without check for passed status (passed lessons will be opened as completed text)
*/
fun openLesson(projectWhereToOpen: Project,
lesson: Lesson?,
startingWay: LessonStartingWay,
forceStartLesson: Boolean = false,
forceOpenLearningProject: Boolean = false,
) {
LessonManager.instance.stopLesson()
if (lesson == null) return //todo: remove null lessons
OpenLessonActivities.openLesson(OpenLessonParameters(projectWhereToOpen, lesson, forceStartLesson, startingWay, forceOpenLearningProject))
}
fun findLessonById(lessonId: String): Lesson? {
return lessonsForModules.firstOrNull { it.id == lessonId }
}
fun findCommonModules(commonCourseId: String): Collection<IftModule> {
if (commonCourses.isEmpty) reloadCommonModules()
return commonCourses[commonCourseId].map(ModuleInfo::module)
}
fun findCommonCourseById(id: String): LearningCourse? {
return COMMON_COURSE_MODULES_EP.extensionList.find { it.key == id }?.instance
}
fun isModuleExternal(module: IftModule): Boolean {
prepareLangModules()
if (commonCourses.isEmpty) reloadCommonModules()
return (languageCourses.values() + commonCourses.values()).any { it.isExternal && it.module.id == module.id }
}
private fun reloadLangModules() {
val extensions = COURSE_MODULES_EP.extensions.filter { courseCanBeUsed(it.language) }
for (e in extensions) {
val langSupport = LangManager.getInstance().getLangSupportById(e.language)
if (langSupport != null) {
languageCourses.putValues(langSupport, createModules(e.instance, e.pluginDescriptor))
}
}
}
private fun reloadCommonModules() {
val commonCoursesExtensions = COMMON_COURSE_MODULES_EP.extensions
for (e in commonCoursesExtensions) {
if (commonCourses[e.key].isEmpty()) {
commonCourses.put(e.key, createModules(e.instance, e.pluginDescriptor))
}
}
}
private fun createModules(course: LearningCourse, pluginDescriptor: PluginDescriptor): Collection<ModuleInfo> {
val isExternal = !getPluginInfoByDescriptor(pluginDescriptor).isDevelopedByJetBrains()
return course.modules().map { ModuleInfo(it, isExternal) }
}
private fun prepareLangModules() {
if (currentConfiguration != switchOnExperimentalLessons) {
languageCourses.clear()
currentConfiguration = switchOnExperimentalLessons
}
if (languageCourses.isEmpty) {
reloadLangModules()
}
}
companion object {
val instance: CourseManager
get() = ApplicationManager.getApplication().getService(CourseManager::class.java)
val COURSE_MODULES_EP = ExtensionPointName<LanguageExtensionPoint<LearningCourseBase>>("training.ift.learning.course")
val COMMON_COURSE_MODULES_EP = ExtensionPointName<KeyedLazyInstanceEP<LearningCourse>>("training.ift.learning.commonCourse")
}
} | apache-2.0 | 14834d600b279e4831c0f2f376f0a906 | 36.238889 | 158 | 0.73396 | 4.587269 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.