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
androidx/androidx
tv/tv-foundation/src/androidTest/java/androidx/tv/foundation/lazy/grid/TvLazyGridLayoutInfoTest.kt
3
17920
/* * 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.foundation.lazy.grid import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.tv.foundation.lazy.list.LayoutInfoTestParam import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @MediumTest @RunWith(Parameterized::class) class TvLazyGridLayoutInfoTest( param: LayoutInfoTestParam ) : BaseLazyGridTestWithOrientation(param.orientation) { companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun initParameters(): Array<Any> = arrayOf( LayoutInfoTestParam(Orientation.Vertical, false), LayoutInfoTestParam(Orientation.Vertical, true), LayoutInfoTestParam(Orientation.Horizontal, false), LayoutInfoTestParam(Orientation.Horizontal, true), ) } private val isVertical = param.orientation == Orientation.Vertical private val reverseLayout = param.reverseLayout private var itemSizePx: Int = 50 private var itemSizeDp: Dp = Dp.Infinity private var gridWidthPx: Int = itemSizePx * 2 private var gridWidthDp: Dp = Dp.Infinity @Before fun before() { with(rule.density) { itemSizeDp = itemSizePx.toDp() gridWidthDp = gridWidthPx.toDp() } } @Test fun visibleItemsAreCorrect() { lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 2, state = rememberTvLazyGridState().also { state = it }, reverseLayout = reverseLayout, modifier = Modifier.axisSize(gridWidthDp, itemSizeDp * 3.5f), ) { items((0..11).toList()) { Box(Modifier.mainAxisSize(itemSizeDp)) } } } rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 8, cells = 2) } } @Test fun visibleItemsAreCorrectAfterScroll() { lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 2, state = rememberTvLazyGridState().also { state = it }, reverseLayout = reverseLayout, modifier = Modifier.axisSize(gridWidthDp, itemSizeDp * 3.5f), ) { items((0..11).toList()) { Box(Modifier.mainAxisSize(itemSizeDp)) } } } rule.runOnIdle { runBlocking { state.scrollToItem(2, 10) } state.layoutInfo .assertVisibleItems(count = 8, startIndex = 2, startOffset = -10, cells = 2) } } @Test fun visibleItemsAreCorrectWithSpacing() { lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 1, state = rememberTvLazyGridState().also { state = it }, reverseLayout = reverseLayout, mainAxisSpacedBy = itemSizeDp, modifier = Modifier.axisSize(itemSizeDp, itemSizeDp * 3.5f), ) { items((0..11).toList()) { Box(Modifier.mainAxisSize(itemSizeDp)) } } } rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 2, spacing = itemSizePx, cells = 1) } } @Composable fun ObservingFun(state: TvLazyGridState, currentInfo: StableRef<TvLazyGridLayoutInfo?>) { currentInfo.value = state.layoutInfo } @Test fun visibleItemsAreObservableWhenWeScroll() { lateinit var state: TvLazyGridState val currentInfo = StableRef<TvLazyGridLayoutInfo?>(null) rule.setContent { LazyGrid( cells = 2, state = rememberTvLazyGridState().also { state = it }, reverseLayout = reverseLayout, modifier = Modifier.axisSize(itemSizeDp * 2f, itemSizeDp * 3.5f), ) { items((0..11).toList()) { Box(Modifier.mainAxisSize(itemSizeDp)) } } ObservingFun(state, currentInfo) } rule.runOnIdle { // empty it here and scrolling should invoke observingFun again currentInfo.value = null runBlocking { state.scrollToItem(2, 0) } } rule.runOnIdle { assertThat(currentInfo.value).isNotNull() currentInfo.value!! .assertVisibleItems(count = 8, startIndex = 2, cells = 2) } } @Test fun visibleItemsAreObservableWhenResize() { lateinit var state: TvLazyGridState var size by mutableStateOf(itemSizeDp * 2) var currentInfo: TvLazyGridLayoutInfo? = null @Composable fun observingFun() { currentInfo = state.layoutInfo } rule.setContent { LazyGrid( cells = 1, modifier = Modifier.crossAxisSize(itemSizeDp), reverseLayout = reverseLayout, state = rememberTvLazyGridState().also { state = it }, ) { item { Box(Modifier.size(size)) } } observingFun() } rule.runOnIdle { assertThat(currentInfo).isNotNull() currentInfo!!.assertVisibleItems( count = 1, expectedSize = if (isVertical) { IntSize(itemSizePx, itemSizePx * 2) } else { IntSize(itemSizePx * 2, itemSizePx) }, cells = 1 ) currentInfo = null size = itemSizeDp } rule.runOnIdle { assertThat(currentInfo).isNotNull() currentInfo!!.assertVisibleItems( count = 1, expectedSize = IntSize(itemSizePx, itemSizePx), cells = 1 ) } } @Test fun totalCountIsCorrect() { var count by mutableStateOf(10) lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 2, reverseLayout = reverseLayout, state = rememberTvLazyGridState().also { state = it }, ) { items((0 until count).toList()) { Box(Modifier.mainAxisSize(10.dp)) } } } rule.runOnIdle { assertThat(state.layoutInfo.totalItemsCount).isEqualTo(10) count = 20 } rule.runOnIdle { assertThat(state.layoutInfo.totalItemsCount).isEqualTo(20) } } @Test fun viewportOffsetsAndSizeAreCorrect() { val sizePx = 45 val sizeDp = with(rule.density) { sizePx.toDp() } lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 2, modifier = Modifier.axisSize(sizeDp * 2, sizeDp), reverseLayout = reverseLayout, state = rememberTvLazyGridState().also { state = it }, ) { items((0..7).toList()) { Box(Modifier.mainAxisSize(sizeDp)) } } } rule.runOnIdle { assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(0) assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(sizePx) assertThat(state.layoutInfo.viewportSize).isEqualTo( if (isVertical) { IntSize(sizePx * 2, sizePx) } else { IntSize(sizePx, sizePx * 2) } ) } } @Test fun viewportOffsetsAndSizeAreCorrectWithContentPadding() { val sizePx = 45 val startPaddingPx = 10 val endPaddingPx = 15 val sizeDp = with(rule.density) { sizePx.toDp() } val beforeContentPaddingDp = with(rule.density) { if (!reverseLayout) startPaddingPx.toDp() else endPaddingPx.toDp() } val afterContentPaddingDp = with(rule.density) { if (!reverseLayout) endPaddingPx.toDp() else startPaddingPx.toDp() } lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 2, modifier = Modifier.axisSize(sizeDp * 2, sizeDp), contentPadding = PaddingValues( beforeContent = beforeContentPaddingDp, afterContent = afterContentPaddingDp, beforeContentCrossAxis = 2.dp, afterContentCrossAxis = 2.dp ), reverseLayout = reverseLayout, state = rememberTvLazyGridState().also { state = it }, ) { items((0..7).toList()) { Box(Modifier.mainAxisSize(sizeDp)) } } } rule.runOnIdle { assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(-startPaddingPx) assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(sizePx - startPaddingPx) assertThat(state.layoutInfo.afterContentPadding).isEqualTo(endPaddingPx) assertThat(state.layoutInfo.viewportSize).isEqualTo( if (isVertical) { IntSize(sizePx * 2, sizePx) } else { IntSize(sizePx, sizePx * 2) } ) } } @Test fun emptyItemsInVisibleItemsInfo() { lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 2, state = rememberTvLazyGridState().also { state = it } ) { item { Box(Modifier) } item { } } } rule.runOnIdle { assertThat(state.layoutInfo.visibleItemsInfo.size).isEqualTo(2) assertThat(state.layoutInfo.visibleItemsInfo.first().index).isEqualTo(0) assertThat(state.layoutInfo.visibleItemsInfo.last().index).isEqualTo(1) } } @Test fun emptyContent() { lateinit var state: TvLazyGridState val sizePx = 45 val startPaddingPx = 10 val endPaddingPx = 15 val sizeDp = with(rule.density) { sizePx.toDp() } val beforeContentPaddingDp = with(rule.density) { if (!reverseLayout) startPaddingPx.toDp() else endPaddingPx.toDp() } val afterContentPaddingDp = with(rule.density) { if (!reverseLayout) endPaddingPx.toDp() else startPaddingPx.toDp() } rule.setContent { LazyGrid( cells = 1, modifier = Modifier.mainAxisSize(sizeDp).crossAxisSize(sizeDp * 2), state = rememberTvLazyGridState().also { state = it }, reverseLayout = reverseLayout, contentPadding = PaddingValues( beforeContent = beforeContentPaddingDp, afterContent = afterContentPaddingDp ) ) { } } rule.runOnIdle { assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(-startPaddingPx) assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(sizePx - startPaddingPx) assertThat(state.layoutInfo.beforeContentPadding).isEqualTo(startPaddingPx) assertThat(state.layoutInfo.afterContentPadding).isEqualTo(endPaddingPx) assertThat(state.layoutInfo.viewportSize).isEqualTo( if (vertical) IntSize(sizePx * 2, sizePx) else IntSize(sizePx, sizePx * 2) ) } } @Test fun viewportIsLargerThenTheContent() { lateinit var state: TvLazyGridState val sizePx = 45 val startPaddingPx = 10 val endPaddingPx = 15 val sizeDp = with(rule.density) { sizePx.toDp() } val beforeContentPaddingDp = with(rule.density) { if (!reverseLayout) startPaddingPx.toDp() else endPaddingPx.toDp() } val afterContentPaddingDp = with(rule.density) { if (!reverseLayout) endPaddingPx.toDp() else startPaddingPx.toDp() } rule.setContent { LazyGrid( cells = 1, modifier = Modifier.mainAxisSize(sizeDp).crossAxisSize(sizeDp * 2), state = rememberTvLazyGridState().also { state = it }, reverseLayout = reverseLayout, contentPadding = PaddingValues( beforeContent = beforeContentPaddingDp, afterContent = afterContentPaddingDp ) ) { item { Box(Modifier.size(sizeDp / 2)) } } } rule.runOnIdle { assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(-startPaddingPx) assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(sizePx - startPaddingPx) assertThat(state.layoutInfo.beforeContentPadding).isEqualTo(startPaddingPx) assertThat(state.layoutInfo.afterContentPadding).isEqualTo(endPaddingPx) assertThat(state.layoutInfo.viewportSize).isEqualTo( if (vertical) IntSize(sizePx * 2, sizePx) else IntSize(sizePx, sizePx * 2) ) } } @Test fun reverseLayoutIsCorrect() { lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 2, state = rememberTvLazyGridState().also { state = it }, reverseLayout = reverseLayout, modifier = Modifier.width(gridWidthDp).height(itemSizeDp * 3.5f), ) { items((0..11).toList()) { Box(Modifier.size(itemSizeDp)) } } } rule.runOnIdle { assertThat(state.layoutInfo.reverseLayout).isEqualTo(reverseLayout) } } @Test fun orientationIsCorrect() { lateinit var state: TvLazyGridState rule.setContent { LazyGrid( cells = 2, state = rememberTvLazyGridState().also { state = it }, reverseLayout = reverseLayout, modifier = Modifier.axisSize(gridWidthDp, itemSizeDp * 3.5f), ) { items((0..11).toList()) { Box(Modifier.mainAxisSize(itemSizeDp)) } } } rule.runOnIdle { assertThat(state.layoutInfo.orientation == Orientation.Vertical).isEqualTo(isVertical) } } fun TvLazyGridLayoutInfo.assertVisibleItems( count: Int, cells: Int, startIndex: Int = 0, startOffset: Int = 0, expectedSize: IntSize = IntSize(itemSizePx, itemSizePx), spacing: Int = 0 ) { assertThat(visibleItemsInfo.size).isEqualTo(count) if (count == 0) return assertThat(startIndex % cells).isEqualTo(0) assertThat(visibleItemsInfo.size % cells).isEqualTo(0) var currentIndex = startIndex var currentOffset = startOffset var currentLine = startIndex / cells var currentCell = 0 visibleItemsInfo.forEach { assertThat(it.index).isEqualTo(currentIndex) assertWithMessage("Offset of item $currentIndex") .that(if (isVertical) it.offset.y else it.offset.x) .isEqualTo(currentOffset) assertThat(it.size).isEqualTo(expectedSize) assertThat(if (isVertical) it.row else it.column) .isEqualTo(currentLine) assertThat(if (isVertical) it.column else it.row) .isEqualTo(currentCell) currentIndex++ currentCell++ if (currentCell == cells) { currentCell = 0 ++currentLine currentOffset += spacing + if (isVertical) it.size.height else it.size.width } } } } class LayoutInfoTestParam( val orientation: Orientation, val reverseLayout: Boolean ) { override fun toString(): String { return "orientation=$orientation;reverseLayout=$reverseLayout" } } @Stable class StableRef<T>(var value: T)
apache-2.0
5a61f98c0e94272caf2f54861c0abd9e
33.461538
98
0.56875
5.203252
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSettings.kt
1
2490
// 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 import com.intellij.openapi.components.* import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "KotlinRefactoringSettings", storages = [Storage("kotlinRefactoring.xml")]) class KotlinRefactoringSettings : PersistentStateComponent<KotlinRefactoringSettings> { @JvmField var MOVE_TO_UPPER_LEVEL_SEARCH_IN_COMMENTS = false @JvmField var MOVE_TO_UPPER_LEVEL_SEARCH_FOR_TEXT = false @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_PACKAGE = false @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_CLASS = false @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = false @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_FIELD = false @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_VARIABLE = false @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_PACKAGE = false @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_CLASS = false @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_METHOD = false @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_FIELD = false @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_VARIABLE = false @JvmField var MOVE_PREVIEW_USAGES = true @JvmField var MOVE_SEARCH_IN_COMMENTS = true @JvmField var MOVE_SEARCH_FOR_TEXT = true @JvmField var MOVE_DELETE_EMPTY_SOURCE_FILES = true @JvmField var MOVE_MPP_DECLARATIONS = true @JvmField var EXTRACT_INTERFACE_JAVADOC: Int = 0 @JvmField var EXTRACT_SUPERCLASS_JAVADOC: Int = 0 @JvmField var PULL_UP_MEMBERS_JAVADOC: Int = 0 @JvmField var PUSH_DOWN_PREVIEW_USAGES: Boolean = false var INLINE_METHOD_THIS: Boolean = false var INLINE_LOCAL_THIS: Boolean = false var INLINE_TYPE_ALIAS_THIS: Boolean = false var INLINE_METHOD_KEEP: Boolean = false var INLINE_PROPERTY_KEEP: Boolean = false var INLINE_TYPE_ALIAS_KEEP: Boolean = false var renameInheritors = true var renameParameterInHierarchy = true var renameVariables = true var renameTests = true var renameOverloads = true override fun getState() = this override fun loadState(state: KotlinRefactoringSettings) = XmlSerializerUtil.copyBean(state, this) companion object { @JvmStatic val instance: KotlinRefactoringSettings get() = service() } }
apache-2.0
58d04960806e6591d201b97f75704434
25.221053
158
0.704819
4.129353
false
false
false
false
jwren/intellij-community
uast/uast-common/src/org/jetbrains/uast/values/UConstant.kt
14
14819
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.values import com.intellij.psi.PsiEnumConstant import com.intellij.psi.PsiType import org.jetbrains.uast.* interface UConstant : UValue { val value: Any? val source: UExpression? // Used for string concatenation fun asString(): String // Used for logging / debugging purposes override fun toString(): String } abstract class UAbstractConstant : UValueBase(), UConstant { override fun valueEquals(other: UValue): UValue = when (other) { this -> UBooleanConstant.True is UConstant -> UBooleanConstant.False else -> super.valueEquals(other) } override fun equals(other: Any?): Boolean = other is UAbstractConstant && value == other.value override fun hashCode(): Int = value?.hashCode() ?: 0 override fun toString(): String = "$value" override fun asString(): String = toString() } enum class UNumericType(val prefix: String = "") { BYTE("(byte)"), SHORT("(short)"), INT(), LONG("(long)"), FLOAT("(float)"), DOUBLE(); fun merge(other: UNumericType): UNumericType { if (this == DOUBLE || other == DOUBLE) return DOUBLE if (this == FLOAT || other == FLOAT) return FLOAT if (this == LONG || other == LONG) return LONG return INT } } abstract class UNumericConstant(val type: UNumericType, override val source: ULiteralExpression?) : UAbstractConstant() { abstract override val value: Number override fun toString(): String = "${type.prefix}$value" override fun asString(): String = "$value" } private fun PsiType.toNumeric(): UNumericType = when (this) { PsiType.LONG -> UNumericType.LONG PsiType.INT -> UNumericType.INT PsiType.SHORT -> UNumericType.SHORT PsiType.BYTE -> UNumericType.BYTE PsiType.DOUBLE -> UNumericType.DOUBLE PsiType.FLOAT -> UNumericType.FLOAT else -> throw AssertionError("Conversion is impossible for type $canonicalText") } private fun Int.asType(type: UNumericType): Int = when (type) { UNumericType.BYTE -> toByte().toInt() UNumericType.SHORT -> toShort().toInt() else -> this } class UIntConstant( rawValue: Int, type: UNumericType = UNumericType.INT, override val source: ULiteralExpression? = null ) : UNumericConstant(type, source) { init { when (type) { UNumericType.INT, UNumericType.SHORT, UNumericType.BYTE -> { } else -> throw AssertionError("Incorrect UIntConstant type: $type") } } override val value: Int = rawValue.asType(type) constructor(value: Int, type: PsiType) : this(value, type.toNumeric()) override fun plus(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value + other.value, type.merge(other.type)) is ULongConstant -> other + this is UFloatConstant -> other + this else -> super.plus(other) } override fun times(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value * other.value, type.merge(other.type)) is ULongConstant -> other * this is UFloatConstant -> other * this else -> super.times(other) } override fun div(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value / other.value, type.merge(other.type)) is ULongConstant -> ULongConstant(value / other.value) is UFloatConstant -> UFloatConstant.create(value / other.value, type.merge(other.type)) else -> super.div(other) } override fun rem(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value % other.value, type.merge(other.type)) is ULongConstant -> ULongConstant(value % other.value) is UFloatConstant -> UFloatConstant.create(value % other.value, type.merge(other.type)) else -> super.rem(other) } override fun unaryMinus(): UIntConstant = UIntConstant(-value, type) override fun greater(other: UValue): UValue = when (other) { is UIntConstant -> UBooleanConstant.valueOf(value > other.value) is ULongConstant -> UBooleanConstant.valueOf(value > other.value) is UFloatConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun inc(): UIntConstant = UIntConstant(value + 1, type) override fun dec(): UIntConstant = UIntConstant(value - 1, type) override fun bitwiseAnd(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value and other.value, type.merge(other.type)) else -> super.bitwiseAnd(other) } override fun bitwiseOr(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value or other.value, type.merge(other.type)) else -> super.bitwiseOr(other) } override fun bitwiseXor(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value xor other.value, type.merge(other.type)) else -> super.bitwiseXor(other) } override fun shl(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value shl other.value, type.merge(other.type)) else -> super.shl(other) } override fun shr(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value shr other.value, type.merge(other.type)) else -> super.shr(other) } override fun ushr(other: UValue): UValue = when (other) { is UIntConstant -> UIntConstant(value ushr other.value, type.merge(other.type)) else -> super.ushr(other) } } class ULongConstant(override val value: Long, source: ULiteralExpression? = null) : UNumericConstant(UNumericType.LONG, source) { override fun plus(other: UValue): UValue = when (other) { is ULongConstant -> ULongConstant(value + other.value) is UIntConstant -> ULongConstant(value + other.value) is UFloatConstant -> other + this else -> super.plus(other) } override fun times(other: UValue): UValue = when (other) { is ULongConstant -> ULongConstant(value * other.value) is UIntConstant -> ULongConstant(value * other.value) is UFloatConstant -> other * this else -> super.times(other) } override fun div(other: UValue): UValue = when (other) { is ULongConstant -> ULongConstant(value / other.value) is UIntConstant -> ULongConstant(value / other.value) is UFloatConstant -> UFloatConstant.create(value / other.value, type.merge(other.type)) else -> super.div(other) } override fun rem(other: UValue): UValue = when (other) { is ULongConstant -> ULongConstant(value % other.value) is UIntConstant -> ULongConstant(value % other.value) is UFloatConstant -> UFloatConstant.create(value % other.value, type.merge(other.type)) else -> super.rem(other) } override fun unaryMinus(): ULongConstant = ULongConstant(-value) override fun greater(other: UValue): UValue = when (other) { is ULongConstant -> UBooleanConstant.valueOf(value > other.value) is UIntConstant -> UBooleanConstant.valueOf(value > other.value) is UFloatConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun inc(): ULongConstant = ULongConstant(value + 1) override fun dec(): ULongConstant = ULongConstant(value - 1) override fun bitwiseAnd(other: UValue): UValue = when (other) { is ULongConstant -> ULongConstant(value and other.value) else -> super.bitwiseAnd(other) } override fun bitwiseOr(other: UValue): UValue = when (other) { is ULongConstant -> ULongConstant(value or other.value) else -> super.bitwiseOr(other) } override fun bitwiseXor(other: UValue): UValue = when (other) { is ULongConstant -> ULongConstant(value xor other.value) else -> super.bitwiseXor(other) } override fun shl(other: UValue): UValue = when (other) { is UIntConstant -> ULongConstant(value shl other.value) else -> super.shl(other) } override fun shr(other: UValue): UValue = when (other) { is UIntConstant -> ULongConstant(value shr other.value) else -> super.shr(other) } override fun ushr(other: UValue): UValue = when (other) { is UIntConstant -> ULongConstant(value ushr other.value) else -> super.ushr(other) } } open class UFloatConstant protected constructor( override val value: Double, type: UNumericType = UNumericType.DOUBLE, source: ULiteralExpression? = null ) : UNumericConstant(type, source) { override fun plus(other: UValue): UValue = when (other) { is ULongConstant -> create(value + other.value, type.merge(other.type)) is UIntConstant -> create(value + other.value, type.merge(other.type)) is UFloatConstant -> create(value + other.value, type.merge(other.type)) else -> super.plus(other) } override fun times(other: UValue): UValue = when (other) { is ULongConstant -> create(value * other.value, type.merge(other.type)) is UIntConstant -> create(value * other.value, type.merge(other.type)) is UFloatConstant -> create(value * other.value, type.merge(other.type)) else -> super.times(other) } override fun div(other: UValue): UValue = when (other) { is ULongConstant -> create(value / other.value, type.merge(other.type)) is UIntConstant -> create(value / other.value, type.merge(other.type)) is UFloatConstant -> create(value / other.value, type.merge(other.type)) else -> super.div(other) } override fun rem(other: UValue): UValue = when (other) { is ULongConstant -> create(value % other.value, type.merge(other.type)) is UIntConstant -> create(value % other.value, type.merge(other.type)) is UFloatConstant -> create(value % other.value, type.merge(other.type)) else -> super.rem(other) } override fun greater(other: UValue): UValue = when (other) { is ULongConstant -> UBooleanConstant.valueOf(value > other.value) is UIntConstant -> UBooleanConstant.valueOf(value > other.value) is UFloatConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun unaryMinus(): UFloatConstant = create(-value, type) override fun inc(): UFloatConstant = create(value + 1, type) override fun dec(): UFloatConstant = create(value - 1, type) companion object { fun create(value: Double, type: UNumericType = UNumericType.DOUBLE, source: ULiteralExpression? = null): UFloatConstant = when (type) { UNumericType.DOUBLE, UNumericType.FLOAT -> { if (value.isNaN()) UNaNConstant.valueOf(type) else UFloatConstant(value, type, source) } else -> throw AssertionError("Incorrect UFloatConstant type: $type") } fun create(value: Double, type: PsiType): UFloatConstant = create(value, type.toNumeric()) } } sealed class UNaNConstant(type: UNumericType = UNumericType.DOUBLE) : UFloatConstant(kotlin.Double.NaN, type) { object Float : UNaNConstant(UNumericType.FLOAT) object Double : UNaNConstant(UNumericType.DOUBLE) override fun greater(other: UValue): UBooleanConstant.False = UBooleanConstant.False override fun less(other: UValue): UBooleanConstant.False = UBooleanConstant.False override fun greaterOrEquals(other: UValue): UBooleanConstant.False = UBooleanConstant.False override fun lessOrEquals(other: UValue): UBooleanConstant.False = UBooleanConstant.False override fun valueEquals(other: UValue): UBooleanConstant.False = UBooleanConstant.False companion object { fun valueOf(type: UNumericType): UNaNConstant = when (type) { UNumericType.DOUBLE -> Double UNumericType.FLOAT -> Float else -> throw AssertionError("NaN exists only for Float / Double, but not for $type") } } } class UCharConstant(override val value: Char, override val source: ULiteralExpression? = null) : UAbstractConstant() { override fun plus(other: UValue): UValue = when (other) { is UIntConstant -> UCharConstant(value + other.value) is UCharConstant -> UCharConstant(value + other.value.toInt()) else -> super.plus(other) } override fun minus(other: UValue): UValue = when (other) { is UIntConstant -> UCharConstant(value - other.value) is UCharConstant -> UIntConstant(value - other.value) else -> super.plus(other) } override fun greater(other: UValue): UValue = when (other) { is UCharConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun inc(): UValue = this + UIntConstant(1) override fun dec(): UValue = this - UIntConstant(1) override fun toString(): String = "\'$value\'" override fun asString(): String = "$value" } sealed class UBooleanConstant(override val value: Boolean) : UAbstractConstant() { override val source: Nothing? = null object True : UBooleanConstant(true) { override fun not(): False = False override fun and(other: UValue): UValue = other as? UBooleanConstant ?: super.and(other) override fun or(other: UValue): True = True } object False : UBooleanConstant(false) { override fun not(): True = True override fun and(other: UValue): False = False override fun or(other: UValue): UValue = other as? UBooleanConstant ?: super.or(other) } companion object { fun valueOf(value: Boolean): UBooleanConstant = if (value) True else False } } class UStringConstant(override val value: String, override val source: ULiteralExpression? = null) : UAbstractConstant() { override fun plus(other: UValue): UValue = when (other) { is UConstant -> UStringConstant(value + other.asString()) else -> super.plus(other) } override fun greater(other: UValue): UValue = when (other) { is UStringConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun asString(): String = value override fun toString(): String = "\"$value\"" } class UEnumEntryValueConstant(override val value: PsiEnumConstant, override val source: USimpleNameReferenceExpression? = null) : UAbstractConstant() { override fun equals(other: Any?): Boolean = other is UEnumEntryValueConstant && value.nameIdentifier.text == other.value.nameIdentifier.text && value.containingClass?.qualifiedName == other.value.containingClass?.qualifiedName override fun hashCode(): Int { var result = 19 result = result * 13 + value.nameIdentifier.text.hashCode() result = result * 13 + (value.containingClass?.qualifiedName?.hashCode() ?: 0) return result } override fun toString(): String = value.name.let { "$it (enum entry)" } override fun asString(): String = value.name } class UClassConstant(override val value: PsiType, override val source: UClassLiteralExpression? = null) : UAbstractConstant() { override fun toString(): String = value.name } object UNullConstant : UAbstractConstant() { override val value: Nothing? = null override val source: Nothing? = null }
apache-2.0
9fe36480ed124f5f3871ad987e8ac2a8
34.794686
140
0.700992
4.180254
false
false
false
false
vovagrechka/fucking-everything
attic/alraune/alraune-back-very-old/src/style.kt
1
15908
package alraune.back class Style( val accelerator: String? = null, val azimuth: String? = null, val background: String? = null, val backgroundAttachment: String? = null, val backgroundColor: String? = null, val backgroundImage: String? = null, val backgroundPosition: String? = null, val backgroundPositionX: String? = null, val backgroundPositionY: String? = null, val backgroundRepeat: String? = null, val behavior: String? = null, val border: String? = null, val borderBottom: String? = null, val borderBottomColor: String? = null, val borderBottomStyle: String? = null, val borderBottomWidth: String? = null, val borderCollapse: String? = null, val borderColor: String? = null, val borderLeft: String? = null, val borderLeftColor: String? = null, val borderLeftStyle: String? = null, val borderLeftWidth: String? = null, val borderRight: String? = null, val borderRightColor: String? = null, val borderRightStyle: String? = null, val borderRightWidth: String? = null, val borderSpacing: String? = null, val borderStyle: String? = null, val borderTop: String? = null, val borderTopColor: String? = null, val borderTopStyle: String? = null, val borderTopWidth: String? = null, val borderWidth: String? = null, val bottom: String? = null, val captionSide: String? = null, val clear: String? = null, val clip: String? = null, val color: String? = null, val content: String? = null, val counterIncrement: String? = null, val counterReset: String? = null, val cue: String? = null, val cueAfter: String? = null, val cueBefore: String? = null, val cursor: String? = null, val direction: String? = null, val display: String? = null, val elevation: String? = null, val emptyCells: String? = null, val filter: String? = null, val float: String? = null, val font: String? = null, val fontFamily: String? = null, val fontSize: String? = null, val fontSizeAdjust: String? = null, val fontStretch: String? = null, val fontStyle: String? = null, val fontVariant: String? = null, val fontWeight: String? = null, val height: String? = null, val imeMode: String? = null, val includeSource: String? = null, val layerBackgroundColor: String? = null, val layerBackgroundImage: String? = null, val layoutFlow: String? = null, val layoutGrid: String? = null, val layoutGridChar: String? = null, val layoutGridCharSpacing: String? = null, val layoutGridLine: String? = null, val layoutGridMode: String? = null, val layoutGridType: String? = null, val left: String? = null, val letterSpacing: String? = null, val lineBreak: String? = null, val lineHeight: String? = null, val listStyle: String? = null, val listStyleImage: String? = null, val listStylePosition: String? = null, val listStyleType: String? = null, val margin: String? = null, val marginBottom: String? = null, val marginLeft: String? = null, val marginRight: String? = null, val marginTop: String? = null, val markerOffset: String? = null, val marks: String? = null, val maxHeight: String? = null, val maxWidth: String? = null, val minHeight: String? = null, val minWidth: String? = null, val orphans: String? = null, val outline: String? = null, val outlineColor: String? = null, val outlineStyle: String? = null, val outlineWidth: String? = null, val overflow: String? = null, val overflowX: String? = null, val overflowY: String? = null, val padding: String? = null, val paddingBottom: String? = null, val paddingLeft: String? = null, val paddingRight: String? = null, val paddingTop: String? = null, val page: String? = null, val pageBreakAfter: String? = null, val pageBreakBefore: String? = null, val pageBreakInside: String? = null, val pause: String? = null, val pauseAfter: String? = null, val pauseBefore: String? = null, val pitch: String? = null, val pitchRange: String? = null, val playDuring: String? = null, val position: String? = null, val quotes: String? = null, val richness: String? = null, val right: String? = null, val rubyAlign: String? = null, val rubyOverhang: String? = null, val rubyPosition: String? = null, val size: String? = null, val speak: String? = null, val speakHeader: String? = null, val speakNumeral: String? = null, val speakPunctuation: String? = null, val speechRate: String? = null, val stress: String? = null, val scrollbarArrowColor: String? = null, val scrollbarBaseColor: String? = null, val scrollbarDarkShadowColor: String? = null, val scrollbarFaceColor: String? = null, val scrollbarHighlightColor: String? = null, val scrollbarShadowColor: String? = null, val scrollbar3dLightColor: String? = null, val scrollbarTrackColor: String? = null, val tableLayout: String? = null, val textAlign: String? = null, val textAlignLast: String? = null, val textDecoration: String? = null, val textIndent: String? = null, val textJustify: String? = null, val textOverflow: String? = null, val textShadow: String? = null, val textTransform: String? = null, val textAutospace: String? = null, val textKashidaSpace: String? = null, val textUnderlinePosition: String? = null, val top: String? = null, val unicodeBidi: String? = null, val verticalAlign: String? = null, val visibility: String? = null, val voiceFamily: String? = null, val volume: String? = null, val whiteSpace: String? = null, val widows: String? = null, val width: String? = null, val wordBreak: String? = null, val wordSpacing: String? = null, val wordWrap: String? = null, val writingMode: String? = null, val zIndex: String? = null, val zoom: String? = null ) { fun render(): String { return buildString { accelerator?.let {append("accelerator: $it;")} azimuth?.let {append("azimuth: $it;")} background?.let {append("background: $it;")} backgroundAttachment?.let {append("background-attachment: $it;")} backgroundColor?.let {append("background-color: $it;")} backgroundImage?.let {append("background-image: $it;")} backgroundPosition?.let {append("background-position: $it;")} backgroundPositionX?.let {append("background-position-x: $it;")} backgroundPositionY?.let {append("background-position-y: $it;")} backgroundRepeat?.let {append("background-repeat: $it;")} behavior?.let {append("behavior: $it;")} border?.let {append("border: $it;")} borderBottom?.let {append("border-bottom: $it;")} borderBottomColor?.let {append("border-bottom-color: $it;")} borderBottomStyle?.let {append("border-bottom-style: $it;")} borderBottomWidth?.let {append("border-bottom-width: $it;")} borderCollapse?.let {append("border-collapse: $it;")} borderColor?.let {append("border-color: $it;")} borderLeft?.let {append("border-left: $it;")} borderLeftColor?.let {append("border-left-color: $it;")} borderLeftStyle?.let {append("border-left-style: $it;")} borderLeftWidth?.let {append("border-left-width: $it;")} borderRight?.let {append("border-right: $it;")} borderRightColor?.let {append("border-right-color: $it;")} borderRightStyle?.let {append("border-right-style: $it;")} borderRightWidth?.let {append("border-right-width: $it;")} borderSpacing?.let {append("border-spacing: $it;")} borderStyle?.let {append("border-style: $it;")} borderTop?.let {append("border-top: $it;")} borderTopColor?.let {append("border-top-color: $it;")} borderTopStyle?.let {append("border-top-style: $it;")} borderTopWidth?.let {append("border-top-width: $it;")} borderWidth?.let {append("border-width: $it;")} bottom?.let {append("bottom: $it;")} captionSide?.let {append("caption-side: $it;")} clear?.let {append("clear: $it;")} clip?.let {append("clip: $it;")} color?.let {append("color: $it;")} content?.let {append("content: $it;")} counterIncrement?.let {append("counter-increment: $it;")} counterReset?.let {append("counter-reset: $it;")} cue?.let {append("cue: $it;")} cueAfter?.let {append("cue-after: $it;")} cueBefore?.let {append("cue-before: $it;")} cursor?.let {append("cursor: $it;")} direction?.let {append("direction: $it;")} display?.let {append("display: $it;")} elevation?.let {append("elevation: $it;")} emptyCells?.let {append("empty-cells: $it;")} filter?.let {append("filter: $it;")} float?.let {append("float: $it;")} font?.let {append("font: $it;")} fontFamily?.let {append("font-family: $it;")} fontSize?.let {append("font-size: $it;")} fontSizeAdjust?.let {append("font-size-adjust: $it;")} fontStretch?.let {append("font-stretch: $it;")} fontStyle?.let {append("font-style: $it;")} fontVariant?.let {append("font-variant: $it;")} fontWeight?.let {append("font-weight: $it;")} height?.let {append("height: $it;")} imeMode?.let {append("ime-mode: $it;")} includeSource?.let {append("include-source: $it;")} layerBackgroundColor?.let {append("layer-background-color: $it;")} layerBackgroundImage?.let {append("layer-background-image: $it;")} layoutFlow?.let {append("layout-flow: $it;")} layoutGrid?.let {append("layout-grid: $it;")} layoutGridChar?.let {append("layout-grid-char: $it;")} layoutGridCharSpacing?.let {append("layout-grid-char-spacing: $it;")} layoutGridLine?.let {append("layout-grid-line: $it;")} layoutGridMode?.let {append("layout-grid-mode: $it;")} layoutGridType?.let {append("layout-grid-type: $it;")} left?.let {append("left: $it;")} letterSpacing?.let {append("letter-spacing: $it;")} lineBreak?.let {append("line-break: $it;")} lineHeight?.let {append("line-height: $it;")} listStyle?.let {append("list-style: $it;")} listStyleImage?.let {append("list-style-image: $it;")} listStylePosition?.let {append("list-style-position: $it;")} listStyleType?.let {append("list-style-type: $it;")} margin?.let {append("margin: $it;")} marginBottom?.let {append("margin-bottom: $it;")} marginLeft?.let {append("margin-left: $it;")} marginRight?.let {append("margin-right: $it;")} marginTop?.let {append("margin-top: $it;")} markerOffset?.let {append("marker-offset: $it;")} marks?.let {append("marks: $it;")} maxHeight?.let {append("max-height: $it;")} maxWidth?.let {append("max-width: $it;")} minHeight?.let {append("min-height: $it;")} minWidth?.let {append("min-width: $it;")} orphans?.let {append("orphans: $it;")} outline?.let {append("outline: $it;")} outlineColor?.let {append("outline-color: $it;")} outlineStyle?.let {append("outline-style: $it;")} outlineWidth?.let {append("outline-width: $it;")} overflow?.let {append("overflow: $it;")} overflowX?.let {append("overflow-x: $it;")} overflowY?.let {append("overflow-y: $it;")} padding?.let {append("padding: $it;")} paddingBottom?.let {append("padding-bottom: $it;")} paddingLeft?.let {append("padding-left: $it;")} paddingRight?.let {append("padding-right: $it;")} paddingTop?.let {append("padding-top: $it;")} page?.let {append("page: $it;")} pageBreakAfter?.let {append("page-break-after: $it;")} pageBreakBefore?.let {append("page-break-before: $it;")} pageBreakInside?.let {append("page-break-inside: $it;")} pause?.let {append("pause: $it;")} pauseAfter?.let {append("pause-after: $it;")} pauseBefore?.let {append("pause-before: $it;")} pitch?.let {append("pitch: $it;")} pitchRange?.let {append("pitch-range: $it;")} playDuring?.let {append("play-during: $it;")} position?.let {append("position: $it;")} quotes?.let {append("quotes: $it;")} richness?.let {append("richness: $it;")} right?.let {append("right: $it;")} rubyAlign?.let {append("ruby-align: $it;")} rubyOverhang?.let {append("ruby-overhang: $it;")} rubyPosition?.let {append("ruby-position: $it;")} size?.let {append("size: $it;")} speak?.let {append("speak: $it;")} speakHeader?.let {append("speak-header: $it;")} speakNumeral?.let {append("speak-numeral: $it;")} speakPunctuation?.let {append("speak-punctuation: $it;")} speechRate?.let {append("speech-rate: $it;")} stress?.let {append("stress: $it;")} scrollbarArrowColor?.let {append("scrollbar-arrow-color: $it;")} scrollbarBaseColor?.let {append("scrollbar-base-color: $it;")} scrollbarDarkShadowColor?.let {append("scrollbar-dark-shadow-color: $it;")} scrollbarFaceColor?.let {append("scrollbar-face-color: $it;")} scrollbarHighlightColor?.let {append("scrollbar-highlight-color: $it;")} scrollbarShadowColor?.let {append("scrollbar-shadow-color: $it;")} scrollbar3dLightColor?.let {append("scrollbar-3d-light-color: $it;")} scrollbarTrackColor?.let {append("scrollbar-track-color: $it;")} tableLayout?.let {append("table-layout: $it;")} textAlign?.let {append("text-align: $it;")} textAlignLast?.let {append("text-align-last: $it;")} textDecoration?.let {append("text-decoration: $it;")} textIndent?.let {append("text-indent: $it;")} textJustify?.let {append("text-justify: $it;")} textOverflow?.let {append("text-overflow: $it;")} textShadow?.let {append("text-shadow: $it;")} textTransform?.let {append("text-transform: $it;")} textAutospace?.let {append("text-autospace: $it;")} textKashidaSpace?.let {append("text-kashida-space: $it;")} textUnderlinePosition?.let {append("text-underline-position: $it;")} top?.let {append("top: $it;")} unicodeBidi?.let {append("unicode-bidi: $it;")} verticalAlign?.let {append("vertical-align: $it;")} visibility?.let {append("visibility: $it;")} voiceFamily?.let {append("voice-family: $it;")} volume?.let {append("volume: $it;")} whiteSpace?.let {append("white-space: $it;")} widows?.let {append("widows: $it;")} width?.let {append("width: $it;")} wordBreak?.let {append("word-break: $it;")} wordSpacing?.let {append("word-spacing: $it;")} wordWrap?.let {append("word-wrap: $it;")} writingMode?.let {append("writing-mode: $it;")} zIndex?.let {append("z-index: $it;")} zoom?.let {append("zoom: $it;")} } } }
apache-2.0
877141f2df5a613337eb45e7ef6d5e83
46.628743
87
0.589326
3.784015
false
false
false
false
firebase/friendlyeats-android
app/src/main/java/com/google/firebase/example/fireeats/RestaurantDetailFragment.kt
1
6878
package com.google.firebase.example.fireeats import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import com.google.android.material.snackbar.Snackbar import com.google.firebase.example.fireeats.databinding.FragmentRestaurantDetailBinding import com.google.firebase.example.fireeats.adapter.RatingAdapter import com.google.firebase.example.fireeats.model.Rating import com.google.firebase.example.fireeats.model.Restaurant import com.google.firebase.example.fireeats.util.RestaurantUtil import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.EventListener import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.ktx.toObject import com.google.firebase.ktx.Firebase class RestaurantDetailFragment : Fragment(), EventListener<DocumentSnapshot>, RatingDialogFragment.RatingListener { private var ratingDialog: RatingDialogFragment? = null private lateinit var binding: FragmentRestaurantDetailBinding private lateinit var firestore: FirebaseFirestore private lateinit var restaurantRef: DocumentReference private lateinit var ratingAdapter: RatingAdapter private var restaurantRegistration: ListenerRegistration? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentRestaurantDetailBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Get restaurant ID from extras val restaurantId = RestaurantDetailFragmentArgs.fromBundle(requireArguments()).keyRestaurantId // Initialize Firestore firestore = Firebase.firestore // Get reference to the restaurant restaurantRef = firestore.collection("restaurants").document(restaurantId) // Get ratings val ratingsQuery = restaurantRef .collection("ratings") .orderBy("timestamp", Query.Direction.DESCENDING) .limit(50) // RecyclerView ratingAdapter = object : RatingAdapter(ratingsQuery) { override fun onDataChanged() { if (itemCount == 0) { binding.recyclerRatings.visibility = View.GONE binding.viewEmptyRatings.visibility = View.VISIBLE } else { binding.recyclerRatings.visibility = View.VISIBLE binding.viewEmptyRatings.visibility = View.GONE } } } binding.recyclerRatings.layoutManager = LinearLayoutManager(context) binding.recyclerRatings.adapter = ratingAdapter ratingDialog = RatingDialogFragment() binding.restaurantButtonBack.setOnClickListener { onBackArrowClicked() } binding.fabShowRatingDialog.setOnClickListener { onAddRatingClicked() } } public override fun onStart() { super.onStart() ratingAdapter.startListening() restaurantRegistration = restaurantRef.addSnapshotListener(this) } public override fun onStop() { super.onStop() ratingAdapter.stopListening() restaurantRegistration?.remove() restaurantRegistration = null } /** * Listener for the Restaurant document ([.restaurantRef]). */ override fun onEvent(snapshot: DocumentSnapshot?, e: FirebaseFirestoreException?) { if (e != null) { Log.w(TAG, "restaurant:onEvent", e) return } snapshot?.let { val restaurant = snapshot.toObject<Restaurant>() if (restaurant != null) { onRestaurantLoaded(restaurant) } } } private fun onRestaurantLoaded(restaurant: Restaurant) { binding.restaurantName.text = restaurant.name binding.restaurantRating.rating = restaurant.avgRating.toFloat() binding.restaurantNumRatings.text = getString(R.string.fmt_num_ratings, restaurant.numRatings) binding.restaurantCity.text = restaurant.city binding.restaurantCategory.text = restaurant.category binding.restaurantPrice.text = RestaurantUtil.getPriceString(restaurant) // Background image Glide.with(binding.restaurantImage.context) .load(restaurant.photo) .into(binding.restaurantImage) } private fun onBackArrowClicked() { requireActivity().onBackPressed() } private fun onAddRatingClicked() { ratingDialog?.show(childFragmentManager, RatingDialogFragment.TAG) } override fun onRating(rating: Rating) { // In a transaction, add the new rating and update the aggregate totals addRating(restaurantRef, rating) .addOnSuccessListener(requireActivity()) { Log.d(TAG, "Rating added") // Hide keyboard and scroll to top hideKeyboard() binding.recyclerRatings.smoothScrollToPosition(0) } .addOnFailureListener(requireActivity()) { e -> Log.w(TAG, "Add rating failed", e) // Show failure message and hide keyboard hideKeyboard() Snackbar.make( requireView().findViewById(android.R.id.content), "Failed to add rating", Snackbar.LENGTH_SHORT).show() } } private fun addRating(restaurantRef: DocumentReference, rating: Rating): Task<Void> { // TODO(developer): Implement return Tasks.forException(Exception("not yet implemented")) } private fun hideKeyboard() { val view = requireActivity().currentFocus if (view != null) { (requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(view.windowToken, 0) } } companion object { private const val TAG = "RestaurantDetail" const val KEY_RESTAURANT_ID = "key_restaurant_id" } }
apache-2.0
39571b3c0554f4991614f4ecc5a65607
36.380435
116
0.682757
5.348367
false
false
false
false
WillowChat/Kale
src/main/kotlin/chat/willow/kale/irc/message/rfc1459/NoticeMessage.kt
2
2460
package chat.willow.kale.irc.message.rfc1459 import chat.willow.kale.core.ICommand import chat.willow.kale.core.message.* import chat.willow.kale.irc.prefix.Prefix import chat.willow.kale.irc.prefix.PrefixParser import chat.willow.kale.irc.prefix.PrefixSerialiser object NoticeMessage : ICommand { override val command = "NOTICE" data class Command(val target: String, val message: String) { object Descriptor : KaleDescriptor<Command>(matcher = commandMatcher(command), parser = Parser) object Parser : MessageParser<Command>() { override fun parseFromComponents(components: IrcMessageComponents): Command? { if (components.parameters.size < 2) { return null } val target = components.parameters[0] val privMessage = components.parameters[1] return Command(target, privMessage) } } object Serialiser : MessageSerialiser<Command>(command) { override fun serialiseToComponents(message: Command): IrcMessageComponents { return IrcMessageComponents(parameters = listOf(message.target, message.message)) } } } data class Message(val source: Prefix, val target: String, val message: String) { object Descriptor : KaleDescriptor<Message>(matcher = commandMatcher(command), parser = Parser) object Parser : MessageParser<Message>() { override fun parseFromComponents(components: IrcMessageComponents): Message? { if (components.parameters.size < 2 || components.prefix == null) { return null } val source = PrefixParser.parse(components.prefix ?: "") ?: return null val target = components.parameters[0] val privMessage = components.parameters[1] return Message(source = source, target = target, message = privMessage) } } object Serialiser : MessageSerialiser<Message>(command) { override fun serialiseToComponents(message: Message): IrcMessageComponents { val prefix = PrefixSerialiser.serialise(message.source) return IrcMessageComponents(prefix = prefix, parameters = listOf(message.target, message.message)) } } } }
isc
cd12203535f93c82db24eafd7868f54c
32.256757
114
0.617073
5.371179
false
false
false
false
appmattus/layercache
layercache/src/test/kotlin/com/appmattus/layercache/CacheBatchGetShould.kt
1
4669
/* * Copyright 2021 Appmattus Limited * * 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.appmattus.layercache import kotlinx.coroutines.CancellationException import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test import java.util.concurrent.TimeUnit class CacheBatchGetShould { private val requestTimeInMills = 250L private val cache = TestCache<String, String>() @Test fun `throw exception when keys list is null`() { runBlocking { // when key is null val throwable = assertThrows(IllegalArgumentException::class.java) { runBlocking { cache.batchGet(TestUtils.uninitialized()) } } // expect exception assertTrue(throwable.message!!.startsWith("Required value was null")) } } @Test fun `throw exception when key in list is null`() { runBlocking { // when key in list is null val throwable = assertThrows(IllegalArgumentException::class.java) { runBlocking { cache.batchGet(listOf("key1", TestUtils.uninitialized(), "key3")) } } // expect exception assertTrue(throwable.message!!.startsWith("null element found in")) } } @Test(expected = CancellationException::class) fun `throw exception when job cancelled`() { runBlocking { // given we request the values for 3 keys cache.getFn = { delay(requestTimeInMills) "value" } val job = async { cache.batchGet(listOf("key1", "key2", "key3")) } // when we cancel the job job.cancel() // then a CancellationException is thrown job.await() } } @Test fun `execute internal requests in parallel`() { runBlocking { // given we start a timer and request the values for 3 keys cache.getFn = { delay(requestTimeInMills) "value" } val start = System.nanoTime() val job = async { cache.batchGet(listOf("key1", "key2", "key3")) } // when we wait for the job to complete job.await() // then the job completes in less than the time to execute all 3 requests in sequence val executionTimeInMills = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) assertTrue(executionTimeInMills > requestTimeInMills) assertTrue(executionTimeInMills < (requestTimeInMills * 3)) } } @Test fun `return values in key sequence`() { runBlocking { // given we request the values for 3 keys where the second value takes longer to return cache.getFn = { key -> if (key == "key2") { delay(requestTimeInMills) } key.replace("key", "value") } val job = async { cache.batchGet(listOf("key1", "key2", "key3")) } // when we wait for the job to complete val result = job.await() // then the job completes with the values in the same sequence as the keys assertEquals(listOf("value1", "value2", "value3"), result) } } @Test(expected = TestException::class) fun `throw internal exception`() { runBlocking { // given we request 3 keys where the second key throws an exception cache.getFn = { key -> if (key == "key2") { throw TestException() } key.replace("key", "value") } val job = async { cache.batchGet(listOf("key1", "key2", "key3")) } // when we wait for the job to complete job.await() // then the internal exception is thrown } } }
apache-2.0
8f7b75d3bfab3bcb3f48d91122494daa
31.65035
99
0.582138
4.823347
false
true
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRDataProviderRepositoryImpl.kt
1
6839
// 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.plugins.github.pullrequest.data import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.util.EventDispatcher import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.messages.ListenerDescriptor import com.intellij.util.messages.MessageBusFactory import com.intellij.util.messages.MessageBusOwner import org.jetbrains.plugins.github.api.data.GHIssueComment import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReview import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem import org.jetbrains.plugins.github.pullrequest.GHPRDiffRequestModelImpl import org.jetbrains.plugins.github.pullrequest.data.provider.* import org.jetbrains.plugins.github.pullrequest.data.service.* import org.jetbrains.plugins.github.util.DisposalCountingHolder import java.util.* internal class GHPRDataProviderRepositoryImpl(private val detailsService: GHPRDetailsService, private val stateService: GHPRStateService, private val reviewService: GHPRReviewService, private val filesService: GHPRFilesService, private val commentService: GHPRCommentService, private val changesService: GHPRChangesService, private val timelineLoaderFactory: (GHPRIdentifier) -> GHListLoader<GHPRTimelineItem>) : GHPRDataProviderRepository { private var isDisposed = false private val cache = mutableMapOf<GHPRIdentifier, DisposalCountingHolder<GHPRDataProvider>>() private val providerDetailsLoadedEventDispatcher = EventDispatcher.create(DetailsLoadedListener::class.java) @RequiresEdt override fun getDataProvider(id: GHPRIdentifier, disposable: Disposable): GHPRDataProvider { if (isDisposed) throw IllegalStateException("Already disposed") return cache.getOrPut(id) { DisposalCountingHolder { createDataProvider(it, id) }.also { Disposer.register(it, Disposable { cache.remove(id) }) } }.acquireValue(disposable) } @RequiresEdt override fun findDataProvider(id: GHPRIdentifier): GHPRDataProvider? = cache[id]?.value override fun dispose() { isDisposed = true cache.values.toList().forEach(Disposer::dispose) } private fun createDataProvider(parentDisposable: Disposable, id: GHPRIdentifier): GHPRDataProvider { val messageBus = MessageBusFactory.newMessageBus(object : MessageBusOwner { override fun isDisposed() = Disposer.isDisposed(parentDisposable) override fun createListener(descriptor: ListenerDescriptor) = throw UnsupportedOperationException() }) Disposer.register(parentDisposable, messageBus) val detailsData = GHPRDetailsDataProviderImpl(detailsService, commentService, id, messageBus).apply { addDetailsLoadedListener(parentDisposable) { loadedDetails?.let { providerDetailsLoadedEventDispatcher.multicaster.onDetailsLoaded(it) } } }.also { Disposer.register(parentDisposable, it) } val stateData = GHPRStateDataProviderImpl(stateService, id, messageBus, detailsData).also { Disposer.register(parentDisposable, it) } val changesData = GHPRChangesDataProviderImpl(changesService, id, detailsData).also { Disposer.register(parentDisposable, it) } val reviewData = GHPRReviewDataProviderImpl(commentService, reviewService, id, messageBus).also { Disposer.register(parentDisposable, it) } val viewedStateData = GHPRViewedStateDataProviderImpl(filesService, id).also { Disposer.register(parentDisposable, it) } val commentsData = GHPRCommentsDataProviderImpl(commentService, id, messageBus) val timelineLoaderHolder = DisposalCountingHolder { timelineDisposable -> timelineLoaderFactory(id).also { loader -> messageBus.connect(timelineDisposable).subscribe(GHPRDataOperationsListener.TOPIC, object : GHPRDataOperationsListener { override fun onStateChanged() = loader.loadMore(true) override fun onMetadataChanged() = loader.loadMore(true) override fun onCommentAdded() = loader.loadMore(true) override fun onCommentUpdated(commentId: String, newBody: String) { val comment = loader.loadedData.find { it is GHIssueComment && it.id == commentId } as? GHIssueComment if (comment != null) { val newComment = GHIssueComment(commentId, comment.author, newBody, comment.createdAt, comment.viewerCanDelete, comment.viewerCanUpdate) loader.updateData(newComment) } loader.loadMore(true) } override fun onCommentDeleted(commentId: String) { loader.removeData { it is GHIssueComment && it.id == commentId } loader.loadMore(true) } override fun onReviewsChanged() = loader.loadMore(true) override fun onReviewUpdated(reviewId: String, newBody: String) { val review = loader.loadedData.find { it is GHPullRequestReview && it.id == reviewId } as? GHPullRequestReview if (review != null) { val newReview = GHPullRequestReview(reviewId, review.url, review.author, newBody, review.state, review.createdAt, review.viewerCanUpdate) loader.updateData(newReview) } loader.loadMore(true) } }) Disposer.register(timelineDisposable, loader) } }.also { Disposer.register(parentDisposable, it) } messageBus.connect(stateData).subscribe(GHPRDataOperationsListener.TOPIC, object : GHPRDataOperationsListener { override fun onReviewsChanged() = stateData.reloadMergeabilityState() }) return GHPRDataProviderImpl( id, detailsData, stateData, changesData, commentsData, reviewData, viewedStateData, timelineLoaderHolder, GHPRDiffRequestModelImpl() ) } override fun addDetailsLoadedListener(disposable: Disposable, listener: (GHPullRequest) -> Unit) { providerDetailsLoadedEventDispatcher.addListener(object : DetailsLoadedListener { override fun onDetailsLoaded(details: GHPullRequest) { listener(details) } }, disposable) } private interface DetailsLoadedListener : EventListener { fun onDetailsLoaded(details: GHPullRequest) } }
apache-2.0
44168c93a360583d91ec3c905826ffb7
45.530612
158
0.708437
5.281081
false
false
false
false
smmribeiro/intellij-community
java/java-impl/src/com/intellij/internal/statistic/libraryUsage/LibraryUsageCollector.kt
1
1428
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistic.libraryUsage import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.openapi.project.Project internal class LibraryUsageCollector : ProjectUsagesCollector() { override fun getGroupId(): String = "libraryUsage" override fun getVersion(): Int = 1 override fun getMetrics(project: Project): Set<MetricEvent> { return LibraryUsageStatisticsStorageService.getInstance(project) .getStatisticsAndResetState() .mapNotNullTo(mutableSetOf()) { (usageInfo, count) -> val libraryName = usageInfo.name ?: return@mapNotNullTo null val libraryVersion = usageInfo.version ?: return@mapNotNullTo null val libraryFileType = usageInfo.fileTypeName ?: return@mapNotNullTo null val data = FeatureUsageData().apply { addData("library_name", libraryName) addVersionByString(libraryVersion) addData(EventFields.FileType.name, libraryFileType) addCount(count) addProject(project) } MetricEvent("library_used", data) } } }
apache-2.0
bf857555051f6f23001620965bcfe74e
42.30303
120
0.748599
4.941176
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/ui/appdetail/AppDetailFragmentViewModel.kt
1
16420
package sk.styk.martin.apkanalyzer.ui.appdetail import android.Manifest import android.app.Activity import android.content.pm.PackageManager import android.graphics.drawable.Drawable import android.net.Uri import android.os.Build import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultCallback import androidx.lifecycle.* import androidx.palette.graphics.Target import androidx.palette.graphics.get import com.google.android.material.appbar.AppBarLayout import com.google.android.material.snackbar.Snackbar import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import sk.styk.martin.apkanalyzer.R import sk.styk.martin.apkanalyzer.manager.analytics.AnalyticsTracker import sk.styk.martin.apkanalyzer.manager.appanalysis.AppDetailDataManager import sk.styk.martin.apkanalyzer.manager.file.ApkSaveManager import sk.styk.martin.apkanalyzer.manager.file.DrawableSaveManager import sk.styk.martin.apkanalyzer.manager.file.FileManager import sk.styk.martin.apkanalyzer.manager.notification.NotificationManager import sk.styk.martin.apkanalyzer.manager.permission.PermissionManager import sk.styk.martin.apkanalyzer.manager.permission.hasScopedStorage import sk.styk.martin.apkanalyzer.manager.resources.ActivityColorThemeManager import sk.styk.martin.apkanalyzer.manager.resources.ResourcesManager import sk.styk.martin.apkanalyzer.model.detail.AppDetailData import sk.styk.martin.apkanalyzer.ui.manifest.ManifestRequest import sk.styk.martin.apkanalyzer.util.* import sk.styk.martin.apkanalyzer.util.components.SnackBarComponent import sk.styk.martin.apkanalyzer.util.coroutines.DispatcherProvider import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent import timber.log.Timber import java.io.File import kotlin.math.abs internal const val LOADING_STATE = 0 internal const val ERROR_STATE = 1 internal const val DATA_STATE = 2 private const val ANALYZED_APK_NAME = "analyzed.apk" class AppDetailFragmentViewModel @AssistedInject constructor( @Assisted val appDetailRequest: AppDetailRequest, private val dispatcherProvider: DispatcherProvider, private val appDetailDataManager: AppDetailDataManager, private val resourcesManager: ResourcesManager, private val permissionManager: PermissionManager, private val appActionsAdapter: AppActionsSpeedMenuAdapter, private val drawableSaveManager: DrawableSaveManager, private val notificationManager: NotificationManager, private val apkSaveManager: ApkSaveManager, private val fileManager: FileManager, private val packageManager: PackageManager, private val activityColorThemeManager: ActivityColorThemeManager, private val analyticsTracker: AnalyticsTracker, ) : ViewModel(), AppBarLayout.OnOffsetChangedListener, DefaultLifecycleObserver { private val viewStateLiveData = MutableLiveData(LOADING_STATE) val viewState: LiveData<Int> = viewStateLiveData private val appDetailsLiveData = MutableLiveData<AppDetailData>() val appDetails: LiveData<AppDetailData> = appDetailsLiveData private val actionButtonVisibilityLiveData = MutableLiveData(false) val actionButtonVisibility: LiveData<Boolean> = actionButtonVisibilityLiveData private val actionButtonAdapterLiveData = MutableLiveData<AppActionsSpeedMenuAdapter>() val actionButtonAdapter: LiveData<AppActionsSpeedMenuAdapter> = actionButtonAdapterLiveData private val showSnackEvent = SingleLiveEvent<SnackBarComponent>() val showSnack: LiveData<SnackBarComponent> = showSnackEvent private val closeEvent = SingleLiveEvent<Unit>() val close: LiveData<Unit> = closeEvent private val installAppEvent = SingleLiveEvent<String>() val installApp: LiveData<String> = installAppEvent private val openSettingsInstallPermissionEvent = SingleLiveEvent<Unit>() val openSettingsInstallPermission: LiveData<Unit> = openSettingsInstallPermissionEvent private val openImageEvent = SingleLiveEvent<Uri>() val openImage: LiveData<Uri> = openImageEvent private val openExportFilePickerEvent = SingleLiveEvent<OutputFilePickerRequest>() val openExportFilePicker: LiveData<OutputFilePickerRequest> = openExportFilePickerEvent private val showManifestEvent = SingleLiveEvent<ManifestRequest>() val showManifest: LiveData<ManifestRequest> = showManifestEvent private val openGooglePlayEvent = SingleLiveEvent<String>() val openGooglePlay: LiveData<String> = openGooglePlayEvent private val openSystemInfoEvent = SingleLiveEvent<String>() val openSystemInfo: LiveData<String> = openSystemInfoEvent val toolbarTitle: LiveData<TextInfo> = viewStateLiveData.map { val details = appDetails.value when { it == LOADING_STATE -> TextInfo.from(R.string.loading) details != null -> TextInfo.from(details.generalData.applicationName) else -> TextInfo.from(R.string.loading_failed) } } val toolbarSubtitle: LiveData<TextInfo> = appDetails.map { TextInfo.from(it.generalData.packageName) } val toolbarSubtitleVisibility: LiveData<Boolean> = viewStateLiveData.map { it == DATA_STATE } private val accentColorLiveData = MutableLiveData(ColorInfo.SECONDARY) val accentColor: LiveData<ColorInfo> = accentColorLiveData val toolbarIcon: LiveData<Drawable> = appDetails.map { it.generalData.icon!! } val installPermissionResult = ActivityResultCallback<ActivityResult> { val apkPath = appDetailsLiveData.value?.generalData?.apkDirectory ?: return@ActivityResultCallback if (it?.resultCode == Activity.RESULT_OK && apkPath.isNotBlank() && (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || packageManager.canRequestPackageInstalls())) { installAppEvent.value = apkPath } } val exportFilePickerResult = ActivityResultCallback<ActivityResult> { if (it.resultCode == Activity.RESULT_OK) { val uri = it.data?.data if (uri != null) { saveApk(uri) } else { showSnackEvent.value = SnackBarComponent(TextInfo.from(R.string.app_export_failed)) } } } init { Timber.tag(TAG_APP_DETAIL).i("Open app detail for request $appDetailRequest") loadDetail() observeApkActions() } override fun onCreate(owner: LifecycleOwner) { super.onCreate(owner) updateActionButtonAdapter() } private fun loadDetail() = viewModelScope.launch { try { val detail = withContext(dispatcherProvider.default()) { when (appDetailRequest) { is AppDetailRequest.InstalledPackage -> appDetailDataManager.loadForInstalledPackage(appDetailRequest.packageName) is AppDetailRequest.ExternalPackage -> { val tempFile = fileManager.createTempFileFromUri(appDetailRequest.packageUri, ANALYZED_APK_NAME) appDetailDataManager.loadForExternalPackage(tempFile) } } } setupToolbar(detail) appDetailsLiveData.value = detail viewStateLiveData.value = DATA_STATE actionButtonVisibilityLiveData.value = true } catch (e: Exception) { viewStateLiveData.value = ERROR_STATE actionButtonVisibilityLiveData.value = false Timber.tag(TAG_APP_DETAIL).w(e, "Loading detail for $appDetailRequest failed") } } private suspend fun setupToolbar(detail: AppDetailData) { val palette = resourcesManager.generatePalette(detail.generalData.icon!!) val range = if (activityColorThemeManager.isNightMode()) 0.1..0.35 else 0.09..0.45 val accentColor = listOf(Target.DARK_VIBRANT, Target.DARK_MUTED, Target.VIBRANT, Target.MUTED, Target.LIGHT_VIBRANT, Target.LIGHT_MUTED) .mapNotNull { palette[it]?.rgb } .firstOrNull { resourcesManager.luminance(it) in range } ?.let { ColorInfo.fromColorInt(it) } accentColorLiveData.postValue(accentColor ?: ColorInfo.SECONDARY) } override fun onOffsetChanged(bar: AppBarLayout, verticalOffset: Int) { actionButtonVisibilityLiveData.value = (abs(verticalOffset) - bar.totalScrollRange != 0) && viewState.value == DATA_STATE } private fun updateActionButtonAdapter() { val displayHeight = resourcesManager.getDisplayHeight() appActionsAdapter.menuItems = when (appDetailRequest) { is AppDetailRequest.ExternalPackage -> if (displayHeight < 420) { listOf(AppActionsSpeedMenuAdapter.AppActions.SAVE_ICON, AppActionsSpeedMenuAdapter.AppActions.SHOW_MANIFEST, AppActionsSpeedMenuAdapter.AppActions.INSTALL) } else { listOf(AppActionsSpeedMenuAdapter.AppActions.OPEN_PLAY, AppActionsSpeedMenuAdapter.AppActions.SAVE_ICON, AppActionsSpeedMenuAdapter.AppActions.SHOW_MANIFEST, AppActionsSpeedMenuAdapter.AppActions.INSTALL) } is AppDetailRequest.InstalledPackage -> if (displayHeight < 420) { listOf(AppActionsSpeedMenuAdapter.AppActions.SAVE_ICON, AppActionsSpeedMenuAdapter.AppActions.EXPORT_APK, AppActionsSpeedMenuAdapter.AppActions.SHOW_MANIFEST) } else { listOf(AppActionsSpeedMenuAdapter.AppActions.OPEN_PLAY, AppActionsSpeedMenuAdapter.AppActions.BUILD_INFO, AppActionsSpeedMenuAdapter.AppActions.SAVE_ICON, AppActionsSpeedMenuAdapter.AppActions.EXPORT_APK, AppActionsSpeedMenuAdapter.AppActions.SHOW_MANIFEST) } } actionButtonAdapterLiveData.value = appActionsAdapter } private fun observeApkActions() { viewModelScope.launch { appActionsAdapter.installApp.collect { analyticsTracker.trackAppActionAction(AnalyticsTracker.AppAction.INSTALL) appDetails.value?.let { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || packageManager.canRequestPackageInstalls()) { installAppEvent.value = it.generalData.apkDirectory } else { openSettingsInstallPermissionEvent.call() } } } } viewModelScope.launch { appActionsAdapter.exportApp.collect { analyticsTracker.trackAppActionAction(AnalyticsTracker.AppAction.EXPORT_APK) appDetails.value?.let { data -> if (hasScopedStorage() || permissionManager.hasPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { exportAppFileSelection() } else { permissionManager.requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, object : PermissionManager.PermissionCallback { override fun onPermissionDenied(permission: String) { showSnackEvent.value = SnackBarComponent(TextInfo.from(R.string.permission_not_granted), Snackbar.LENGTH_LONG) } override fun onPermissionGranted(permission: String) { exportAppFileSelection() } }) } } } } viewModelScope.launch { appActionsAdapter.saveIcon.collect { analyticsTracker.trackAppActionAction(AnalyticsTracker.AppAction.SAVE_ICON) appDetails.value?.let { data -> if (hasScopedStorage() || permissionManager.hasPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { saveImage() } else { permissionManager.requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, object : PermissionManager.PermissionCallback { override fun onPermissionDenied(permission: String) { showSnackEvent.value = SnackBarComponent(TextInfo.from(R.string.permission_not_granted), Snackbar.LENGTH_LONG) } override fun onPermissionGranted(permission: String) { saveImage() } }) } } } } viewModelScope.launch { analyticsTracker.trackAppActionAction(AnalyticsTracker.AppAction.SHOW_MANIFEST) appActionsAdapter.showManifest.collect { appDetails.value?.generalData?.let { showManifestEvent.value = ManifestRequest( appName = it.applicationName, packageName = it.packageName, apkPath = it.apkDirectory, versionName = it.versionName, versionCode = it.versionCode) } } } viewModelScope.launch { analyticsTracker.trackAppActionAction(AnalyticsTracker.AppAction.OPEN_GOOGLE_PLAY) appActionsAdapter.openGooglePlay.collect { appDetails.value?.let { openGooglePlayEvent.value = it.generalData.packageName } } } viewModelScope.launch { analyticsTracker.trackAppActionAction(AnalyticsTracker.AppAction.OPEN_SYSTEM_ABOUT) appActionsAdapter.openSystemInfo.collect { appDetails.value?.let { openSystemInfoEvent.value = it.generalData.packageName } } } } fun onNavigationClick() { closeEvent.call() } private fun saveImage() { val data = appDetails.value ?: return val icon = data.generalData.icon if (icon != null) { viewModelScope.launch { val target = "${data.generalData.packageName}_${data.generalData.versionName}_${data.generalData.versionCode}_icon.png" try { val exportedFileUri = drawableSaveManager.saveDrawable(icon, target, "image/png") showSnackEvent.value = SnackBarComponent(TextInfo.from(R.string.icon_saved), action = TextInfo.from(R.string.action_show), callback = { openImageEvent.value = exportedFileUri }) notificationManager.showImageExportedNotification(data.generalData.applicationName, exportedFileUri) } catch (e: Exception) { Timber.tag(TAG_EXPORTS).e(e, "Saving icon failed. Data ${data.generalData}") showSnackEvent.value = SnackBarComponent(TextInfo.from(R.string.icon_export_failed)) } } } } private fun exportAppFileSelection() { val data = appDetails.value ?: return val source = File(data.generalData.apkDirectory) if (!source.exists()) { showSnackEvent.value = SnackBarComponent(TextInfo.from(R.string.app_export_failed)) } openExportFilePickerEvent.value = OutputFilePickerRequest("${data.generalData.packageName}_${data.generalData.versionName}.apk", "application/vnd.android.package-archive") } private fun saveApk(targetUri: Uri) { val data = appDetails.value ?: return viewModelScope.launch { showSnackEvent.value = SnackBarComponent(TextInfo.from(R.string.saving_app, data.generalData.applicationName)) apkSaveManager.saveApk(data.generalData.applicationName, File(data.generalData.apkDirectory), targetUri) } } override fun onCleared() { super.onCleared() if (appDetailRequest is AppDetailRequest.ExternalPackage) { fileManager.deleteTempFile(ANALYZED_APK_NAME) } } @AssistedFactory interface Factory { fun create(appDetailRequest: AppDetailRequest): AppDetailFragmentViewModel } }
gpl-3.0
91bb958276a278837a2c69827f629dbc
46.459538
277
0.670889
5.140889
false
false
false
false
vivchar/RendererRecyclerViewAdapter
example/src/main/java/com/github/vivchar/example/MainActivity.kt
1
1395
package com.github.vivchar.example import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar class MainActivity : AppCompatActivity() { var router: UIRouter? = null var menuController: OptionsMenuController? = null private var presenter: MainPresenter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) router = UIRouter(this) menuController = OptionsMenuController(this) setContentView(R.layout.main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val firstInit = savedInstanceState == null presenter = MainPresenter(menuController!!, router!!, firstInit) } override fun onStart() { super.onStart() presenter?.viewShown() } override fun onStop() { super.onStop() presenter?.viewHidden() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuController?.onCreateOptionsMenu(menu, menuInflater) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu): Boolean { menuController?.onPrepareOptionsMenu(menu, menuInflater) return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { menuController?.onOptionsItemSelected(item) return super.onOptionsItemSelected(item) } }
apache-2.0
8fff4d71dcb99779e7aa1d96b958ec3d
27.489796
66
0.784946
4.164179
false
false
false
false
filipproch/reactor-android
library/src/androidTest/java/cz/filipproch/reactor/util/view/translatorfragment/TranslatorFragmentTestActivity.kt
1
1508
package cz.filipproch.reactor.util.view.translatorfragment import android.support.v7.app.AppCompatActivity import cz.filipproch.reactor.base.translator.ReactorTranslator import cz.filipproch.reactor.base.translator.SimpleTranslatorFactory import cz.filipproch.reactor.ui.ReactorTranslatorFragment import cz.filipproch.reactor.ui.ReactorTranslatorHelper /** * TODO * * @author Filip Prochazka (@filipproch) */ class TranslatorFragmentTestActivity : AppCompatActivity() { val translatorFactory = SimpleTranslatorFactory(TranslatorFragmentTestTranslator::class.java) var translator: TranslatorFragmentTestTranslator? = null private set var translatorFragment: ReactorTranslatorFragment<TranslatorFragmentTestTranslator>? = null private set override fun onStart() { super.onStart() translator = ReactorTranslatorHelper .getTranslatorFromFragment(supportFragmentManager, translatorFactory) translatorFragment = ReactorTranslatorHelper .findTranslatorFragment(supportFragmentManager) } class TranslatorFragmentTestTranslator : ReactorTranslator() { override fun onCreated() { } } fun replaceFragmentWithNewInstance(fragment: ReactorTranslatorFragment<TranslatorFragmentTestTranslator>) { supportFragmentManager.beginTransaction() .remove(translatorFragment) .add(fragment, ReactorTranslatorFragment.TAG) .commitNow() } }
mit
8cdadda956c4ba3b12cc12d81a8c45ef
32.533333
111
0.748674
5.64794
false
true
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/note_editor/cells/viewmodel/TextPropertyCellViewModel.kt
1
1473
package com.ivanovsky.passnotes.presentation.note_editor.cells.viewmodel import androidx.lifecycle.MutableLiveData import com.ivanovsky.passnotes.R import com.ivanovsky.passnotes.data.entity.Property import com.ivanovsky.passnotes.domain.ResourceProvider import com.ivanovsky.passnotes.presentation.core.BaseCellViewModel import com.ivanovsky.passnotes.presentation.core.event.EventProvider import com.ivanovsky.passnotes.presentation.note_editor.cells.model.TextPropertyCellModel import com.ivanovsky.passnotes.util.StringUtils.EMPTY class TextPropertyCellViewModel( override val model: TextPropertyCellModel, private val eventProvider: EventProvider, private val resourceProvider: ResourceProvider ) : BaseCellViewModel(model), PropertyViewModel { val text = MutableLiveData(model.value) val error = MutableLiveData<String?>(null) override fun createProperty(): Property { return Property( type = model.propertyType, name = model.propertyName, value = text.value?.toString()?.trim(), isProtected = false ) } override fun isDataValid(): Boolean { return model.isAllowEmpty || getText().isNotEmpty() } override fun displayError() { if (!model.isAllowEmpty && getText().isEmpty()) { error.value = resourceProvider.getString(R.string.should_not_be_empty) } } private fun getText(): String = text.value?.trim() ?: EMPTY }
gpl-2.0
77f23a48ea25e7cfb4b998052ef85b64
34.95122
89
0.730482
4.736334
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/speakercall/EditSpeakerFragment.kt
1
11841
package org.fossasia.openevent.general.speakercall import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Bundle import android.util.Base64 import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.navArgs import com.squareup.picasso.MemoryPolicy import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerName import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerImage import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerOrganization import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerEmail import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerPosition import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerShortBio import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerWebsite import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerTwitter import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.submitButton import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerEmailLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerNameLayout import org.fossasia.openevent.general.CircleTransform import org.fossasia.openevent.general.ComplexBackPressFragment import org.fossasia.openevent.general.R import org.fossasia.openevent.general.RotateBitmap import org.fossasia.openevent.general.auth.User import org.fossasia.openevent.general.auth.UserId import org.fossasia.openevent.general.event.EventId import org.fossasia.openevent.general.speakers.Speaker import org.fossasia.openevent.general.utils.Utils.progressDialog import org.fossasia.openevent.general.utils.Utils.show import org.fossasia.openevent.general.utils.Utils.hideSoftKeyboard import org.fossasia.openevent.general.utils.Utils.requireDrawable import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.checkEmpty import org.fossasia.openevent.general.utils.emptyToNull import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.nullToEmpty import org.fossasia.openevent.general.utils.setRequired import org.jetbrains.anko.design.snackbar import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber import java.io.FileNotFoundException import java.io.File import java.io.IOException import java.io.FileOutputStream import java.io.ByteArrayOutputStream class EditSpeakerFragment : Fragment(), ComplexBackPressFragment { private lateinit var rootView: View private val editSpeakerViewModel by viewModel<EditSpeakerViewModel>() private val safeArgs: EditSpeakerFragmentArgs by navArgs() private var isCreatingNewSpeaker = true private var permissionGranted = false private val PICK_IMAGE_REQUEST = 100 private val READ_STORAGE = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) private val REQUEST_CODE = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) isCreatingNewSpeaker = (safeArgs.speakerId == -1L) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(R.layout.fragment_proposal_speaker, container, false) setToolbar(activity, getString(R.string.proposal_speaker)) setHasOptionsMenu(true) editSpeakerViewModel.user .nonNull() .observe(viewLifecycleOwner, Observer { autoFillByUserInformation(it) }) val currentSpeaker = editSpeakerViewModel.speaker.value if (currentSpeaker == null) { if (isCreatingNewSpeaker) { editSpeakerViewModel.user.value?.let { autoFillByUserInformation(it) } ?: editSpeakerViewModel.loadUser(editSpeakerViewModel.getId()) } else { editSpeakerViewModel.loadSpeaker(safeArgs.speakerId) } } else loadSpeakerUI(currentSpeaker) editSpeakerViewModel.speaker .nonNull() .observe(viewLifecycleOwner, Observer { loadSpeakerUI(it) }) val progressDialog = progressDialog(context) editSpeakerViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressDialog.show(it) }) editSpeakerViewModel.message .nonNull() .observe(viewLifecycleOwner, Observer { rootView.snackbar(it) }) editSpeakerViewModel.submitSuccess .nonNull() .observe(viewLifecycleOwner, Observer { if (it) findNavController(rootView).popBackStack() }) rootView.speakerNameLayout.setRequired() rootView.speakerEmailLayout.setRequired() rootView.submitButton.text = getString(if (isCreatingNewSpeaker) R.string.add_speaker else R.string.edit_speaker) return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) editSpeakerViewModel.getUpdatedTempFile() .nonNull() .observe(viewLifecycleOwner, Observer { file -> Picasso.get() .load(file) .placeholder(requireDrawable(requireContext(), R.drawable.ic_person_black)) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) .transform(CircleTransform()) .into(rootView.speakerImage) }) rootView.speakerImage.setOnClickListener { if (permissionGranted) { showFileChooser() } else { requestPermissions(READ_STORAGE, REQUEST_CODE) } } rootView.submitButton.setOnClickListener { if (!checkSpeakerSuccess()) return@setOnClickListener val speaker = Speaker( id = editSpeakerViewModel.speaker.value?.id ?: editSpeakerViewModel.getId(), name = rootView.speakerName.text.toString(), email = rootView.speakerEmail.text.toString(), organisation = rootView.speakerOrganization.text.toString(), position = rootView.speakerPosition.text.toString(), shortBiography = rootView.speakerShortBio.text.toString(), website = rootView.speakerWebsite.text.toString().emptyToNull(), twitter = rootView.speakerTwitter.text.toString().emptyToNull(), event = EventId(safeArgs.eventId), user = UserId(editSpeakerViewModel.getId()) ) if (isCreatingNewSpeaker) editSpeakerViewModel.submitSpeaker(speaker) else editSpeakerViewModel.editSpeaker(speaker) } } override fun handleBackPress() { hideSoftKeyboard(context, rootView) AlertDialog.Builder(requireContext()) .setMessage(getString(R.string.changes_not_saved)) .setNegativeButton(R.string.discard) { _, _ -> findNavController(rootView).popBackStack() } .setPositiveButton(getString(R.string.continue_string)) { _, _ -> /*Do Nothing*/ } .create() .show() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } override fun onActivityResult(requestCode: Int, resultCode: Int, intentData: Intent?) { super.onActivityResult(requestCode, resultCode, intentData) if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && intentData?.data != null) { val imageUri = intentData.data ?: return try { val selectedImage = RotateBitmap().handleSamplingAndRotationBitmap(requireContext(), imageUri) editSpeakerViewModel.encodedImage = selectedImage?.let { encodeImage(it) } } catch (e: FileNotFoundException) { Timber.d(e, "File Not Found Exception") } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { permissionGranted = true rootView.snackbar(getString(R.string.permission_granted_message, getString(R.string.external_storage))) showFileChooser() } else { rootView.snackbar(getString(R.string.permission_denied_message, getString(R.string.external_storage))) } } } private fun showFileChooser() { val intent = Intent() intent.type = "image/*" intent.action = Intent.ACTION_GET_CONTENT startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)), PICK_IMAGE_REQUEST) } private fun autoFillByUserInformation(user: User) { rootView.speakerName.setText("${user.firstName.nullToEmpty()} ${user.lastName.nullToEmpty()}") rootView.speakerEmail.setText(user.email) rootView.speakerShortBio.setText(user.details) Picasso.get() .load(user.avatarUrl) .placeholder(R.drawable.ic_account_circle_grey) .transform(CircleTransform()) .into(rootView.speakerImage) } private fun encodeImage(bitmap: Bitmap): String { val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) val bytes = baos.toByteArray() // create temp file try { val tempAvatar = File(context?.cacheDir, "tempAvatar") if (tempAvatar.exists()) { tempAvatar.delete() } val fos = FileOutputStream(tempAvatar) fos.write(bytes) fos.flush() fos.close() editSpeakerViewModel.setUpdatedTempFile(tempAvatar) } catch (e: IOException) { e.printStackTrace() } return "data:image/jpeg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT) } private fun checkSpeakerSuccess(): Boolean = rootView.speakerEmail.checkEmpty() && rootView.speakerName.checkEmpty() private fun loadSpeakerUI(speaker: Speaker) { Picasso.get() .load(speaker.photoUrl) .placeholder(R.drawable.ic_account_circle_grey) .transform(CircleTransform()) .into(rootView.speakerImage) rootView.speakerName.setText(speaker.name) rootView.speakerEmail.setText(speaker.email) rootView.speakerOrganization.setText(speaker.organisation) rootView.speakerPosition.setText(speaker.position) rootView.speakerShortBio.setText(speaker.shortBiography) rootView.speakerWebsite.setText(speaker.website) rootView.speakerTwitter.setText(speaker.twitter) } }
apache-2.0
1b07a34fba13f1d49715ec7f1d677884
40.402098
119
0.679081
4.878863
false
false
false
false
derkork/test-data-builder
src/main/kotlin/de/janthomae/databuilder/expressions/MetaExpressions.kt
1
1668
package de.janthomae.databuilder.expressions import com.google.gson.JsonElement import com.google.gson.JsonNull import de.janthomae.databuilder.MyComputedExpression import de.janthomae.databuilder.MyExpression import de.janthomae.databuilder.MyObject import de.janthomae.databuilder.Nil public fun nil(): MyExpression<Nil> = object : MyExpression<Nil> { override fun toElement(): JsonElement = JsonNull.INSTANCE override fun computeValue(): Nil = Nil override fun materialize(): MyExpression<Nil> = this override fun isNil(): Boolean = true } @Suppress("UNCHECKED_CAST") public fun nilOr(inExpression:MyExpression<*>, expression:MyExpression<*>) : MyExpression<Any> = MyComputedExpression { if (inExpression.isNil()) { nil() as MyExpression<Any> } else { expression as MyExpression<Any> } } public fun get(expression: MyExpression<Any>, path: String): MyExpression<*> = MyComputedExpression { val obj = expression.asMyObject() @Suppress("UNCHECKED_CAST") (get(obj, path) as MyExpression<Any>) } private fun get(obj: MyObject, path:String) : MyExpression<*> { val index = path.indexOf(".") if (index != -1) { val propertyName = path.substring(0, index) val rest = path.substring(index + 1) val value = obj.properties[propertyName] if ( value is MyObject) { return get(value, rest) } throw IllegalArgumentException("The property at path $path is no object.") } val result = obj.properties[path] if (result != null) { return result } throw IllegalArgumentException("The property at path $path does not exist.") }
mit
db7d7a37003a182cc465a08d749b1923
32.38
119
0.693046
3.915493
false
false
false
false
Zubnix/westmalle
compositor/src/main/kotlin/org/westford/nativ/linux/stat.kt
3
1855
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.nativ.linux import org.freedesktop.jaccall.CType import org.freedesktop.jaccall.Field import org.freedesktop.jaccall.Struct @Struct(Field(name = "st_dev", type = CType.UNSIGNED_LONG_LONG), Field(name = "st_ino", type = CType.UNSIGNED_LONG), Field(name = "st_mode", type = CType.UNSIGNED_INT), Field(name = "st_nlink", type = CType.UNSIGNED_INT), Field(name = "st_uid", type = CType.UNSIGNED_INT), Field(name = "st_gid", type = CType.UNSIGNED_INT), Field(name = "st_rdev", type = CType.UNSIGNED_INT), Field(name = "st_size", type = CType.LONG), Field(name = "st_blksize", type = CType.LONG), Field(name = "blkcnt_t", type = CType.UNSIGNED_LONG), Field(name = "st_atime", type = CType.LONG), Field(name = "st_mtime", type = CType.LONG), Field(name = "st_ctime", type = CType.LONG)) class stat : Struct_stat()
apache-2.0
c9cb78ed0462226ef881cf241b1c2332
36.857143
75
0.612399
3.946809
false
false
false
false
CyroPCJr/Kotlin-Koans
src/main/kotlin/builders/ExtensionFunctionLiterals.kt
1
218
package builders fun task(): List<Boolean> { val isEven: Int.() -> Boolean = { this % 2 == 0 } val isOdd: Int.() -> Boolean = { this % 2 != 0 } return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven()) }
apache-2.0
de50939d36a9e28ef1785c93a7fac08a
26.375
62
0.568807
3.460317
false
false
false
false
sunghwanJo/workshop-jb
src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt
1
971
package i_introduction._9_Extension_Functions import util.* fun String.lastChar() = this.get(this.length - 1) // 'this' can be omitted fun String.lastChar1() = get(length - 1) fun use() { // try Ctrl+Space "default completion" after the dot: lastChar() is visible "abc".lastChar() } // 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension) fun todoTask9(): Nothing = TODO( """ Task 9. Implement the extension functions Int.r(), Pair<Int, Int>.r() to support the following manner of creating rational numbers: 1.r(), Pair(1, 2).r() """, documentation = doc9(), references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) }) data class RationalNumber(val numerator: Int, val denominator: Int) fun Int.r(): RationalNumber { return RationalNumber(this, 1) } fun Pair<Int, Int>.r(): RationalNumber { return RationalNumber(this.first, this.second) }
mit
abfdd2b1f9ed57c40e17c3d5b1d7ad79
25.243243
109
0.664264
3.650376
false
false
false
false
RomanBelkov/TrikKotlinDemos
TrikoSegway/src/Main.kt
1
3787
import rx.Observable import java.io.File import java.util.concurrent.TimeUnit /** * Created by Roman Belkov on 17.10.15. */ fun sgn(x: Double) = Math.signum(x) fun abs(x: Double) = Math.abs(x) const val c_fb = 12.7 //full battery value const val c_p2d = 0.0175 //parrots to degree const val c_itnum = 100 //number of iterations for gyro drift calculations const val c_minpower = 5 //min power const val c_mainperiod : Long = 1 //ms fun main(args: Array<String>) { //init routines, ugly for now I2cTrik.open() File("/sys/class/gpio/gpio62/value").writeText("1") File("/sys/class/misc/l3g42xxd/fs_selection").writeText("1") File("/sys/class/misc/l3g42xxd/odr_selection").writeText("2") I2cTrik.writeWord(0x12, 0x0500) I2cTrik.writeWord(0x13, 0x0500) val leftMotor = PowerMotor(MotorPorts.M3) val rightMotor = PowerMotor(MotorPorts.M4) val gyroscope = Gyroscope() val accelerometer = Accelerometer() val battery = Battery() val buttons = Buttons() //PIDc var c_ck = 0.0044 var c_pk = 15 //10 var c_ik = 3 //2 var c_dk = 12 //10 //global values var g_bc = 1.0 //battery coefficient var g_gd = 0 var g_od = 0.0 //out data (gyro accel fusion) var g_angle2 = 0.0 var g_angle3 = 0.0 var g_offset = 0.0 var g_te = System.currentTimeMillis() fun Exit() { leftMotor.stop() rightMotor.stop() I2cTrik.close() System.exit(0) } val observableButtons = buttons.toObservable() observableButtons.filter { it.button == ButtonEventCode.Power }.subscribe { Exit() } observableButtons.filter { it.button == ButtonEventCode.Down }.subscribe { g_offset = g_od } fun setBatteryTimer() { fun batteryLoop() { g_bc = c_fb / battery.readVoltage() } Observable.interval(500, TimeUnit.MILLISECONDS).subscribe { batteryLoop() } } fun calibrateGyrDrift() { println("Gyro drift calculating..."); var gd = 0; for(i in 0..c_itnum) { gd += gyroscope.read()?.x!! Thread.sleep(50) } g_gd = gd / c_itnum; println("Gyro drift is: $g_gd") } var g_cnt = 0 fun startBalancing() { fun balanceLoop() { var accfd = accelerometer.read() //accel full data //println("ACC: ${accfd?.x}, ${accfd?.y}, ${accfd?.z}") var accd = -Math.atan2(accfd?.z!!.toDouble(), -accfd?.x!!.toDouble()) * 180.0/3.14159 var tmp = System.currentTimeMillis() - g_te var gyrd = (gyroscope.read()!!.x - g_gd)*tmp.toDouble()*c_p2d/1000.0 //ms to s g_te = System.currentTimeMillis() g_od = (1 - c_ck)*(g_od + gyrd) + c_ck*accd var angle = g_od - g_offset var yaw = g_bc*(sgn(angle)*c_minpower + angle*c_pk + (angle - g_angle2)*c_dk + (angle + g_angle2 + g_angle3)*c_ik) g_angle3 = g_angle2 g_angle2 = angle //println("Yaw: $yaw ||| Angle: $angle") if (abs(angle) < 45) { leftMotor.setPower(yaw.toInt()) rightMotor.setPower(yaw.toInt()) } else { leftMotor.stop() rightMotor.stop() } if(g_cnt == 20) { //println("YAAW: $yaw, ANGLE: $angle, TMP: $tmp") g_cnt = 0 } g_cnt += 1 } Observable.interval(c_mainperiod, TimeUnit.MILLISECONDS).subscribe { balanceLoop() } print("balancing started") } buttons.start() accelerometer.start() gyroscope.start() setBatteryTimer() calibrateGyrDrift() startBalancing() }
apache-2.0
475cd29b183c87b820a94a7f1f17594f
29.063492
126
0.555321
3.366222
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/main/tut11/gaussianSpecularLighting.kt
2
13925
package main.tut11 import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.MouseEvent import com.jogamp.opengl.GL2ES3.* import com.jogamp.opengl.GL3 import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP import glNext.* import glm.glm import glm.mat.Mat4 import glm.quat.Quat import glm.vec._3.Vec3 import glm.vec._4.Vec4 import main.framework.Framework import main.framework.Semantic import main.framework.component.Mesh import main.tut11.GaussianSpecularLighting_.LightingModel.BlinnOnly import main.tut11.GaussianSpecularLighting_.LightingModel.BlinnSpecular import main.tut11.GaussianSpecularLighting_.LightingModel.GaussianSpecular import main.tut11.GaussianSpecularLighting_.LightingModel.PhongOnly import main.tut11.GaussianSpecularLighting_.LightingModel.PhongSpecular import uno.buffer.destroy import uno.buffer.intBufferBig import uno.glm.MatrixStack import uno.glsl.programOf import uno.mousePole.* import uno.time.Timer /** * Created by GBarbieri on 24.03.2017. */ fun main(args: Array<String>) { GaussianSpecularLighting_().setup("Tutorial 11 - Gaussian Specular Lighting") } class GaussianSpecularLighting_ : Framework() { lateinit var programs: Array<ProgramPairs> lateinit var unlit: UnlitProgData val initialViewData = ViewData( Vec3(0.0f, 0.5f, 0.0f), Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f), 5.0f, 0.0f) val viewScale = ViewScale( 3.0f, 20.0f, 1.5f, 0.5f, 0.0f, 0.0f, //No camera movement. 90.0f / 250.0f) val initialObjectData = ObjectData( Vec3(0.0f, 0.5f, 0.0f), Quat(1.0f, 0.0f, 0.0f, 0.0f)) val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1) val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole) lateinit var cylinder: Mesh lateinit var plane: Mesh lateinit var cube: Mesh var lightModel = LightingModel.BlinnSpecular var drawColoredCyl = false var drawLightSource = false var scaleCyl = false var drawDark = false var lightHeight = 1.5f var lightRadius = 1.0f val lightAttenuation = 1.2f val darkColor = Vec4(0.2f, 0.2f, 0.2f, 1.0f) val lightColor = Vec4(1.0f) val lightTimer = Timer(Timer.Type.Loop, 5.0f) val projectionUniformBuffer = intBufferBig(1) override fun init(gl: GL3) = with(gl) { initializePrograms(gl) cylinder = Mesh(gl, javaClass, "tut11/UnitCylinder.xml") plane = Mesh(gl, javaClass, "tut11/LargePlane.xml") cube = Mesh(gl, javaClass, "tut11/UnitCube.xml") val depthZNear = 0.0f val depthZFar = 1.0f glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glFrontFace(GL_CW) glEnable(GL_DEPTH_TEST) glDepthMask(true) glDepthFunc(GL_LEQUAL) glDepthRangef(depthZNear, depthZFar) glEnable(GL_DEPTH_CLAMP) glGenBuffer(projectionUniformBuffer) glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer) glBufferData(GL_UNIFORM_BUFFER, Mat4.SIZE, GL_DYNAMIC_DRAW) //Bind the static buffers. glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.PROJECTION, projectionUniformBuffer, 0, Mat4.SIZE) glBindBuffer(GL_UNIFORM_BUFFER) } fun initializePrograms(gl: GL3) { val FRAGMENTS = arrayOf("phong-lighting", "phong-only", "blinn-lighting", "blinn-only", "gaussian-lighting", "gaussian-only") programs = Array(LightingModel.MAX, { ProgramPairs(ProgramData(gl, "pn.vert", "${FRAGMENTS[it]}.frag"), ProgramData(gl, "pcn.vert", "${FRAGMENTS[it]}.frag")) }) unlit = UnlitProgData(gl, "pos-transform.vert", "uniform-color.frag") } override fun display(gl: GL3) = with(gl) { lightTimer.update() glClearBufferf(GL_COLOR, 0) glClearBufferf(GL_DEPTH) val modelMatrix = MatrixStack() modelMatrix.setMatrix(viewPole.calcMatrix()) val worldLightPos = calcLightPosition() val lightPosCameraSpace = modelMatrix.top() * worldLightPos val whiteProg = programs[lightModel].whiteProgram val colorProg = programs[lightModel].colorProgram glUseProgram(whiteProg.theProgram) glUniform4f(whiteProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f) glUniform4f(whiteProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f) glUniform3f(whiteProg.cameraSpaceLightPosUnif, lightPosCameraSpace) glUniform1f(whiteProg.lightAttenuationUnif, lightAttenuation) glUniform1f(whiteProg.shininessFactorUnif, MaterialParameters.getSpecularValue(lightModel)) glUniform4f(whiteProg.baseDiffuseColorUnif, if (drawDark) darkColor else lightColor) glUseProgram(colorProg.theProgram) glUniform4f(colorProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f) glUniform4f(colorProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f) glUniform3f(colorProg.cameraSpaceLightPosUnif, lightPosCameraSpace) glUniform1f(colorProg.lightAttenuationUnif, lightAttenuation) glUniform1f(colorProg.shininessFactorUnif, MaterialParameters.getSpecularValue(lightModel)) glUseProgram() modelMatrix run { //Render the ground plane. run { val normMatrix = top().toMat3() normMatrix.inverse_().transpose_() glUseProgram(whiteProg.theProgram) glUniformMatrix4f(whiteProg.modelToCameraMatrixUnif, top()) glUniformMatrix3f(whiteProg.normalModelToCameraMatrixUnif, normMatrix) plane.render(gl) glUseProgram() } //Render the Cylinder run { applyMatrix(objectPole.calcMatrix()) if (scaleCyl) scale(1.0f, 1.0f, 0.2f) val normMatrix = modelMatrix.top().toMat3() normMatrix.inverse_().transpose_() val prog = if (drawColoredCyl) colorProg else whiteProg glUseProgram(prog.theProgram) glUniformMatrix4f(prog.modelToCameraMatrixUnif, top()) glUniformMatrix3f(prog.normalModelToCameraMatrixUnif, normMatrix) cylinder.render(gl, if (drawColoredCyl) "lit-color" else "lit") glUseProgram() } //Render the light if (drawLightSource) run { translate(worldLightPos) scale(0.1f) glUseProgram(unlit.theProgram) glUniformMatrix4f(unlit.modelToCameraMatrixUnif, modelMatrix.top()) glUniform4f(unlit.objectColorUnif, 0.8078f, 0.8706f, 0.9922f, 1.0f) cube.render(gl, "flat") } } } fun calcLightPosition(): Vec4 { val currentTimeThroughLoop = lightTimer.getAlpha() val ret = Vec4(0.0f, lightHeight, 0.0f, 1.0f) ret.x = glm.cos(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius ret.z = glm.sin(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius return ret } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { val zNear = 1.0f val zFar = 1_000f val perspMatrix = MatrixStack() val proj = perspMatrix.perspective(45.0f, w.toFloat() / h, zNear, zFar).top() glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer) glBufferSubData(GL_UNIFORM_BUFFER, proj) glBindBuffer(GL_UNIFORM_BUFFER) glViewport(w, h) } override fun mousePressed(e: MouseEvent) { viewPole.mousePressed(e) objectPole.mousePressed(e) } override fun mouseDragged(e: MouseEvent) { viewPole.mouseDragged(e) objectPole.mouseDragged(e) } override fun mouseReleased(e: MouseEvent) { viewPole.mouseReleased(e) objectPole.mouseReleased(e) } override fun mouseWheelMoved(e: MouseEvent) { viewPole.mouseWheel(e) } override fun keyPressed(e: KeyEvent) { var changedShininess = false when (e.keyCode) { KeyEvent.VK_ESCAPE -> quit() KeyEvent.VK_SPACE -> drawColoredCyl = !drawColoredCyl KeyEvent.VK_I -> lightHeight += if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_K -> lightHeight -= if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_L -> lightRadius += if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_J -> lightRadius -= if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_O -> { MaterialParameters.increment(lightModel, !e.isShiftDown) changedShininess = true } KeyEvent.VK_U -> { MaterialParameters.decrement(lightModel, !e.isShiftDown) changedShininess = true } KeyEvent.VK_Y -> drawLightSource = !drawLightSource KeyEvent.VK_T -> scaleCyl = !scaleCyl KeyEvent.VK_B -> lightTimer.togglePause() KeyEvent.VK_G -> drawDark = !drawDark KeyEvent.VK_H -> { if (e.isShiftDown) if (lightModel % 2 != 0) lightModel -= 1 else lightModel += 1 else lightModel = (lightModel + 2) % LightingModel.MAX println(when (lightModel) { PhongSpecular -> "PhongSpecular" PhongOnly -> "PhongOnly" BlinnSpecular -> "BlinnSpecular" BlinnOnly -> "BlinnOnly" GaussianSpecular -> "GaussianSpecular" else -> "GaussianOnly" }) } } if (lightRadius < 0.2f) lightRadius = 0.2f if (changedShininess) println("Shiny: " + MaterialParameters.getSpecularValue(lightModel)) } override fun end(gl: GL3) = with(gl) { programs.forEach { glDeletePrograms(it.whiteProgram.theProgram, it.colorProgram.theProgram) } glDeleteProgram(unlit.theProgram) glDeleteBuffer(projectionUniformBuffer) cylinder.dispose(gl) plane.dispose(gl) cube.dispose(gl) projectionUniformBuffer.destroy() } object LightingModel { val PhongSpecular = 0 val PhongOnly = 1 val BlinnSpecular = 2 val BlinnOnly = 3 val GaussianSpecular = 4 val GaussianOnly = 5 val MAX = 6 } class ProgramPairs(val whiteProgram: ProgramData, val colorProgram: ProgramData) class ProgramData(gl: GL3, vertex: String, fragment: String) { val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment) val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix") val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity") val ambientIntensityUnif = gl.glGetUniformLocation(theProgram, "ambientIntensity") val normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix") val cameraSpaceLightPosUnif = gl.glGetUniformLocation(theProgram, "cameraSpaceLightPos") val lightAttenuationUnif = gl.glGetUniformLocation(theProgram, "lightAttenuation") val shininessFactorUnif = gl.glGetUniformLocation(theProgram, "shininessFactor") val baseDiffuseColorUnif = gl.glGetUniformLocation(theProgram, "baseDiffuseColor") init { gl.glUniformBlockBinding( theProgram, gl.glGetUniformBlockIndex(theProgram, "Projection"), Semantic.Uniform.PROJECTION) } } inner class UnlitProgData(gl: GL3, vertex: String, fragment: String) { val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment) val objectColorUnif = gl.glGetUniformLocation(theProgram, "objectColor") val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix") init { gl.glUniformBlockBinding( theProgram, gl.glGetUniformBlockIndex(theProgram, "Projection"), Semantic.Uniform.PROJECTION) } } object MaterialParameters { var phongExponent = 4.0f var blinnExponent = 4.0f var gaussianRoughness = 0.5f fun getSpecularValue(model: Int) = when (model) { PhongSpecular, PhongOnly -> phongExponent BlinnSpecular, BlinnOnly -> blinnExponent else -> gaussianRoughness } fun increment(model: Int, isLarge: Boolean) { when (model) { PhongSpecular, PhongOnly -> phongExponent += if (isLarge) 0.5f else 0.1f BlinnSpecular, BlinnOnly -> blinnExponent += if (isLarge) 0.5f else 0.1f else -> gaussianRoughness += if (isLarge) 0.1f else 0.01f } clampParam(model) } fun decrement(model: Int, isLarge: Boolean) { when (model) { PhongSpecular, PhongOnly -> phongExponent -= if (isLarge) 0.5f else 0.1f BlinnSpecular, BlinnOnly -> blinnExponent -= if (isLarge) 0.5f else 0.1f else -> gaussianRoughness -= if (isLarge) 0.1f else 0.01f } clampParam(model) } fun clampParam(model: Int) { when (model) { PhongSpecular, PhongOnly -> if (phongExponent <= 0.0f) phongExponent = 0.0001f BlinnSpecular, BlinnOnly -> if (blinnExponent <= 0.0f) blinnExponent = 0.0001f else -> gaussianRoughness = glm.clamp(gaussianRoughness, 0.00001f, 1.0f) } } } }
mit
c4311a88a9c52a3fd1b337d60f1946f7
32.800971
133
0.621903
4.078793
false
false
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/module/common/player/BaseMusicPlayer.kt
1
5429
/* * Copyright (C) 2017 YangBin * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package tech.summerly.quiet.module.common.player import android.content.Context import com.google.gson.Gson import com.google.gson.reflect.TypeToken import tech.summerly.quiet.AppContext import tech.summerly.quiet.extensions.edit import tech.summerly.quiet.extensions.log import tech.summerly.quiet.module.common.bean.Music import tech.summerly.quiet.module.common.bus.RxBus import tech.summerly.quiet.module.common.bus.event.MusicPlayerEvent import tech.summerly.quiet.module.common.player.coreplayer.CoreMediaPlayer /** * author : yangbin10 * date : 2017/11/20 */ abstract class BaseMusicPlayer : IMusicPlayer { companion object { @JvmStatic private val KEY_PLAY_LIST = "music_list" @JvmStatic private val KEY_CURRENT_MUSIC = "music_current" @JvmStatic private val KEY_PLAY_MODE = "play_mode" // @JvmStatic // private val KEY_POSITION = "position" } private var current: Music? = null override var playMode: PlayMode = PlayMode.SEQUENCE override fun currentPlaying(): Music? = current override fun isPlaying(): Boolean = _corePlayer?.isPlaying ?: false private var _corePlayer: CoreMediaPlayer? = null private val musicCorePlayer: CoreMediaPlayer get() { if (_corePlayer == null) { synchronized(this@BaseMusicPlayer) { if (_corePlayer == null) { _corePlayer = CoreMediaPlayer() } } } return _corePlayer!! } /** * everything get ready , just to start play music */ protected fun performPlay(music: Music) { current = music musicCorePlayer.play(music) } override fun playNext() { val next = getNextMusic(current) ?: return performPlay(next) } abstract fun getNextMusic(current: Music?): Music? abstract fun getPreviousMusic(current: Music?): Music? override fun playPrevious() { val previous = getPreviousMusic(current) ?: return performPlay(previous) } override fun playPause() { if (musicCorePlayer.isPlaying) { musicCorePlayer.pause() return } if (musicCorePlayer.isPausing) { musicCorePlayer.start() return } if (current != null) { performPlay(current!!) return } val shouldBePlay = current ?: getNextMusic(null) ?: return performPlay(shouldBePlay) } override fun stop() { _corePlayer?.stop() } override fun play(music: Music) { log { music.toShortString() } addToNext(music) performPlay(music) } override fun setPlaylist(musics: List<Music>) { if (musics.isEmpty()) { current = null RxBus.publish(MusicPlayerEvent.OnPlayerStateChange()) } save() } override fun seekToPosition(position: Long) { musicCorePlayer.seekTo(position) } override fun currentPosition(): Long = _corePlayer?.currentPosition() ?: 0 override fun destroy() { if (_corePlayer == null) { return } musicCorePlayer.stop() // musicCorePlayer.destroy() _corePlayer = null save() } private val preference = AppContext.instance .getSharedPreferences("music_player_info", Context.MODE_PRIVATE) private val gson = Gson() override fun save() { preference.edit { putString(KEY_PLAY_LIST, gson.toJson(getPlaylist())) putString(KEY_CURRENT_MUSIC, gson.toJson(currentPlaying())) putString(KEY_PLAY_MODE, playMode.name) // putLong(KEY_POSITION, currentPosition()) } log { """ $KEY_PLAY_LIST = ${getPlaylist().joinToString { it.toShortString() }} $KEY_CURRENT_MUSIC = ${currentPlaying()?.toShortString()} $KEY_PLAY_MODE = ${playMode.name} """.trimIndent() } } override fun restore() { //恢复current必须在setPlaylist之前,因为setPlaylist之中有save()操作 current = gson.fromJson(preference.getString(KEY_CURRENT_MUSIC, null), Music::class.java) setPlaylist(gson.fromJson( preference.getString(KEY_PLAY_LIST, null), object : TypeToken<List<Music>>() {}.type) ?: emptyList()) playMode = PlayMode.valueOf(preference.getString(KEY_PLAY_MODE, PlayMode.SEQUENCE.name)) //TODO set to current position } }
gpl-2.0
2e8efe562700d700ecdd1f7496ea5cd2
28.834254
97
0.620115
4.458299
false
false
false
false
j-selby/kotgb
core/src/main/kotlin/net/jselby/kotgb/cpu/interpreter/instructions/alu/BitRotation.kt
1
5264
package net.jselby.kotgb.cpu.interpreter.instructions.alu import net.jselby.kotgb.Gameboy import net.jselby.kotgb.cpu.CPU import net.jselby.kotgb.cpu.Registers import kotlin.experimental.and import kotlin.reflect.KMutableProperty1 /** * Instructions that rotate bits through registers. */ /** * **0x17** - *RL X* - Rotate X left through Carry. */ val x_RL : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = { _, registers, _, register -> val value = register.get(registers).toInt() val oldFlag = if (registers.flagC) 1 else 0 val result = (((value shl 1) and 0b11111110) or oldFlag).toShort() register.set(registers, result) registers.f = 0 registers.flagC = (value shr 7) and 0x1 == 1 registers.flagZ = result.toInt() == 0 /*Cycles: */ 8 } /** * **0x17** - *RLA* - Rotate A left through Carry. */ val x17 : (CPU, Registers, Gameboy) -> (Int) = { cpu, regs, gb -> x_RL(cpu, regs, gb, Registers::a) regs.flagZ = false /*Cycles: */ 4 } /** * **0xCB 0x16** - *RL (hl)* - Rotate (hl) left through Carry. */ val xCB16 : (CPU, Registers, Gameboy) -> (Int) = { _, registers, gb -> val value = (gb.ram.readByte(registers.hl.toLong()) and 0xFF).toInt() val oldFlag = if (registers.flagC) 1 else 0 val result = (((value shl 1) and 0b11111110) or oldFlag).toShort() gb.ram.writeByte(registers.hl.toLong(), result) registers.f = 0 registers.flagC = (value shr 7) and 0x1 == 1 registers.flagZ = result.toInt() == 0 /*Cycles: */ 16 } /** * **0xCB 0x08 ~ 0xCB 0x0F** - *RRC X* - Rotate X right. Bit 0 into Carry. */ val x_RRC : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = { _, registers, _, target -> val value = target.get(registers).toInt() target.set(registers, (((value shr 1) and 0b1111111) or ((value and 0x1) shl 7)).toShort()) registers.f = 0 registers.flagC = (value and 0x1) == 1 registers.flagZ = target.get(registers).toInt() == 0 /*Cycles: */ 8 } /** * **0xCB 0x0E** - *RRC (hl)* - Rotate (hl) right. Bit 0 into Carry. */ val xCB0E : (CPU, Registers, Gameboy) -> (Int) = { _, registers, gb -> val value = (gb.ram.readByte(registers.hl.toLong()) and 0xFF).toInt() gb.ram.writeByte(registers.hl.toLong(), (((value shr 1) and 0b1111111) or ((value and 0x1) shl 7)).toShort()) registers.f = 0 registers.flagZ = (gb.ram.readByte(registers.hl.toLong()) and 0xFF).toInt() == 0 registers.flagC = (value and 0x1) == 1 /*Cycles: */ 4 } /** * **0x0F** - *RRCA* - Rotate a right. Bit 0 into Carry. */ val x0F : (CPU, Registers, Gameboy) -> (Int) = { cpu, registers, gb -> x_RRC(cpu, registers, gb, Registers::a) registers.flagZ = false /*Cycles: */ 4 } /** * **0x1F** - *RRA* - Rotate a right through Carry. */ val x1F : (CPU, Registers, Gameboy) -> (Int) = { cpu, registers, gb -> x_RR(cpu, registers, gb, Registers::a) registers.flagZ = false /*Cycles: */ 4 } /** * **0xCB 0x00** - *RLC X* - Rotate X left. Bit 7 into Carry. */ val x_RLC : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = { _, registers, _, prop -> val value = prop.get(registers).toInt() prop.set(registers, (((value shl 1) and 0b11111110) or ((value shr 7) and 0x1)).toShort()) registers.f = 0 //if (prop != Registers::a) { registers.flagZ = prop.get(registers).toInt() == 0 //} registers.flagC = ((value shr 7) and 0x1) == 1 /*Cycles: */ 8 } /** * **0xCB 0x06** - *RLC (hl)* - Rotate (hl) left. Bit 7 into Carry. */ val xCB06 : (CPU, Registers, Gameboy) -> (Int) = { _, registers, gb -> val value = gb.ram.readByte(registers.hl.toLong()).toInt() gb.ram.writeByte(registers.hl.toLong(), ((value shl 1) or ((value shr 7) and 0x1)).toShort()) registers.f = 0 registers.flagZ = gb.ram.readByte(registers.hl.toLong()).toInt() == 0 registers.flagC = ((value shr 7) and 0x1) == 1 /*Cycles: */ 16 } /** * **0x07** - *RLCA* - Rotate a left. Bit 7 into Carry. */ val x07 : (CPU, Registers, Gameboy) -> (Int) = { cpu, registers, gb -> x_RLC(cpu, registers, gb, Registers::a) registers.flagZ = false /*Cycles: */ 4 } /** * **0xCB 0x19** - *RR X* - Rotate X right through Carry. */ val x_RR : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = { _, registers, _, prop -> val value = prop.get(registers).toInt() val oldFlag = if (registers.flagC) (1 shl 7) else 0 prop.set(registers, ((value shr 1) or oldFlag).toShort()) registers.f = 0 registers.flagC = value and 0x1 == 1 registers.flagZ = prop.get(registers).toInt() == 0 /*Cycles: */ 8 } /** * **0xCB 0x1E** - *RR (hl)* - Rotate (hl) right through Carry. */ val xCB1E : (CPU, Registers, Gameboy) -> (Int) = { _, registers, gb -> val value = (gb.ram.readByte(registers.hl.toLong()) and 0xFF).toInt() val oldFlag = if (registers.flagC) (1 shl 7) else 0 gb.ram.writeByte(registers.hl.toLong(), ((value shr 1) or oldFlag).toShort()) registers.f = 0 registers.flagC = value and 0x1 == 1 registers.flagZ = gb.ram.readByte(registers.hl.toLong()).toInt() == 0 /*Cycles: */ 16 }
mit
38de0efb1c0b2361abf04f6e90417dfa
26.560209
113
0.601254
2.994312
false
false
false
false
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/util/FormatUtil.kt
1
11917
package org.miaowo.miaowo.util import android.content.Context import android.graphics.Paint import android.graphics.Point import android.graphics.Rect import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.support.v4.content.res.ResourcesCompat import android.text.* import android.view.WindowManager import com.blankj.utilcode.util.ActivityUtils import com.squareup.picasso.Picasso import org.miaowo.miaowo.App import org.miaowo.miaowo.R import org.miaowo.miaowo.other.Const import org.xml.sax.XMLReader import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.ThreadFactory import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import kotlin.math.max import kotlin.math.min /** * 格式化工具类 * Created by luqin on 17-1-23. */ object FormatUtil { private var mCachedScreenSize: Point? = null private var mCachedTextSize = mutableMapOf<Int, Point>() private val mTextPaint by lazy { TextPaint(Paint.ANTI_ALIAS_FLAG).apply { density = App.i.resources.displayMetrics.density } } private val hErrorDrawable = { val eIcon = ResourcesCompat.getDrawable(App.i.resources, R.drawable.ic_error, null) val sSize = FormatUtil.screenSize val iSize = min(sSize.x, sSize.y) / 4 eIcon?.setBounds(0, 0, iSize, iSize) eIcon }.invoke() private val hPlaceDrawable = { val pIcon = ResourcesCompat.getDrawable(App.i.resources, R.drawable.ic_loading, null) val sSize = FormatUtil.screenSize val iSize = min(sSize.x, sSize.y) / 4 pIcon?.setBounds(0, 0, iSize, iSize) pIcon }.invoke() val screenSize: Point get() { if (mCachedScreenSize == null) loadScreenSize() return mCachedScreenSize!! } fun textSize(textSize: Float): Point { val intSize = textSize.toInt() if (!mCachedTextSize.containsKey(intSize)) { val size = Point() val bound = Rect() mTextPaint.textSize = textSize mTextPaint.measureText("t") mTextPaint.getTextBounds("t", 0, 1, bound) size.set(bound.right - bound.left, bound.bottom - bound.top) mCachedTextSize[intSize] = size } return mCachedTextSize[intSize]!! } fun time(time: Long?): String { if (time == null || time < 0) { return "无效时间" } val second = (System.currentTimeMillis() - time) / 1000 return when { second >= 60 * 60 * 24 * 365 -> "至少 ${(second / (60 * 60 * 24 * 365)).toInt()} 年" second >= 60 * 60 * 24 * 30 -> "至少 ${(second / (60 * 60 * 24 * 30)).toInt()} 个月" second >= 60 * 60 * 24 -> "${(second / (60 * 60 * 24)).toInt()} 天" second >= 60 * 60 -> "${(second / (60 * 60)).toInt()} 小时" second >= 60 -> "${(second / 60)} 分钟" second >= 3 -> "$second 秒" else -> "片刻" } } fun html(html: String?, textSize: Float, config: HtmlFormatConfig): SpannableStringBuilder { val imgGetterExist = Html.ImageGetter { resizeImage(HtmlImageDownloader[it], textSize) ?: hErrorDrawable } var tagHandler: Html.TagHandler? = null val imgGetter = Html.ImageGetter { HtmlImageDownloader.newTask(it) { ActivityUtils.getTopActivity().runOnUiThread { config.resetHandler(Html.fromHtml(html ?: "", Html.FROM_HTML_MODE_LEGACY, imgGetterExist, tagHandler, App.i)) } } hPlaceDrawable } tagHandler = CustomTagHandler(config, imgGetter) val rHtml = CustomTagHandler.renameTag(html ?: "", *config.getTagArray()) return Html.fromHtml(rHtml, Html.FROM_HTML_MODE_LEGACY, imgGetter, tagHandler, App.i) as SpannableStringBuilder } private fun loadScreenSize() { val wm = App.i.getSystemService(Context.WINDOW_SERVICE) as WindowManager mCachedScreenSize = Point() wm.defaultDisplay.getSize(mCachedScreenSize) } private fun resizeImage(drawable: Drawable?, charSize: Float): Drawable? { if (drawable == null) return null val sSize = FormatUtil.screenSize val cSize = FormatUtil.textSize(charSize) val maxSize = min(sSize.x, sSize.y) * 3 / 5 val minSize = max(cSize.x, cSize.y) val dHeight = drawable.intrinsicHeight val dWidth = drawable.intrinsicWidth if (dWidth <= 0 || dHeight <= 0) drawable.setBounds(0, 0, maxSize, maxSize) else if (dWidth < minSize && dHeight < minSize) { val eW = minSize / dWidth val eH = minSize / dHeight val e = max(eW, eH) drawable.setBounds(0, 0, dWidth * e, dHeight * e) } else if (dWidth > maxSize || dHeight > maxSize) { val eW = dWidth / maxSize val eH = dHeight / maxSize val e = max(eW, eH) drawable.setBounds(0, 0, dWidth / e, dHeight / e) } return drawable } class HtmlFormatConfig { private val tagHandlerMap = mutableMapOf<String, (spanMark: SpanMark, imgHandler: Html.ImageGetter?) -> Array<Any>>() private val tagList = mutableListOf<String>() @Suppress("UNREACHABLE_CODE") private var _resetHandler = { _: Spanned -> throw Exception("No Reset Handler") Unit } val resetHandler get() = _resetHandler fun addTagHandler(tag: String, handler: (spanMark: SpanMark, imgHandler: Html.ImageGetter?) -> Array<Any>): HtmlFormatConfig { tagList.add(tag) tagHandlerMap["${CustomTagHandler.CUSTOM_TAG}$tag"] = handler return this } fun getTagHandler(tag: String) = tagHandlerMap["${CustomTagHandler.CUSTOM_TAG}$tag"] fun getTagArray() = tagList.toTypedArray() fun registerContentReset(reset: (content: Spanned) -> Unit): HtmlFormatConfig { _resetHandler = reset return this } } class CustomTagHandler(private val config: HtmlFormatConfig, private val imgHandler: Html.ImageGetter?): Html.TagHandler { companion object { const val CUSTOM_TAG = "CUSTOM_TAG_" fun fixTag(tag: String?): String { return if (tag == null) return "" else if (!tag.startsWith(CUSTOM_TAG)) tag else tag.replaceFirst(CUSTOM_TAG, "") } fun renameTag(html: String, vararg tags: String): String { var r = html tags.forEach { r = r .replace("<$it ", "<${CustomTagHandler.CUSTOM_TAG}$it ", true) .replace("<$it>", "<${CustomTagHandler.CUSTOM_TAG}$it>", true) .replace("<$it\n", "<${CustomTagHandler.CUSTOM_TAG}$it\n", true) .replace("</$it ", "</${CustomTagHandler.CUSTOM_TAG}$it ", true) .replace("</$it>", "</${CustomTagHandler.CUSTOM_TAG}$it>", true) .replace("</$it\n", "</${CustomTagHandler.CUSTOM_TAG}$it\n", true) .replace("<$it/>", "<${CustomTagHandler.CUSTOM_TAG}$it/>", true) } return r } } private val mAttributeMap = mutableMapOf<String, String>() private val mMarkStartMap = mutableMapOf<String, Int>() override fun handleTag(opening: Boolean, tag: String?, output: Editable?, xmlReader: XMLReader?) { val rTag = fixTag(tag) if (rTag.isBlank() || output == null || xmlReader == null || !config.getTagArray().contains(rTag)) return if (opening) handleStart(rTag, output, xmlReader) else handleEnd(rTag, output) } private fun handleStart(tag: String, output: Editable, xmlReader: XMLReader) { mAttributeMap.clear() buildAttribute(xmlReader) val spanMask = SpanMark(tag, output.toString(), mAttributeMap.toMap()) val len = output.length output.setSpan(spanMask, len, len, Spannable.SPAN_MARK_MARK) mMarkStartMap[tag] = len } private fun handleEnd(tag: String, output: Editable) { val len = output.length val mark = output.getSpans(mMarkStartMap[tag] ?: len, len, SpanMark::class.java).lastOrNull() ?: return val start = output.getSpanStart(mark) output.removeSpan(mark) val spanList = config.getTagHandler(tag)?.invoke(mark, imgHandler) mark.extra(output) val newLen = output.length spanList?.forEach { output.setSpan(it, start, newLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } private fun buildAttribute(xmlReader: XMLReader) { try { val elementField = xmlReader.javaClass.getDeclaredField("theNewElement") elementField.isAccessible = true val element = elementField.get(xmlReader) val attrsField = element.javaClass.getDeclaredField("theAtts") attrsField.isAccessible = true val attrs = attrsField.get(element) val dataField = attrs.javaClass.getDeclaredField("data") dataField.isAccessible = true val data = dataField.get(attrs) as Array<*> val lengthField = attrs.javaClass.getDeclaredField("length") lengthField.isAccessible = true val len = lengthField.get(attrs) as Int for (i in 0 until len) { mAttributeMap[data[i * 5 + 1].toString()] = data[i * 5 + 4].toString() } } catch (e: Exception) { e.printStackTrace() } } } data class SpanMark(val tag: String, val value: String, val attrs: Map<String, String>) { var extra: (text: Editable) -> Unit = {} } @Suppress("unused") object HtmlImageDownloader : MutableMap<String, Drawable?> by mutableMapOf() { private val sTaskMap = mutableMapOf<String, () -> Unit>() private val threadPool = ThreadPoolExecutor(2, 10, 5000, TimeUnit.MILLISECONDS, ArrayBlockingQueue<Runnable>(20), ThreadFactory { val count = AtomicInteger(1) return@ThreadFactory Thread(it, "ImageDownloadThread-${count.getAndIncrement()}") }).apply { allowCoreThreadTimeOut(true) } fun newTask(url: String, apply: () -> Unit) { sTaskMap[url] = { try { val context = App.i.applicationContext val bmp = Picasso.with(context).load(fixImagePath(url)).error(hErrorDrawable).get() this[url] = BitmapDrawable(context.resources, bmp) apply.invoke() } catch (e: Exception) { this[url] = hErrorDrawable } finally { if (sTaskMap.containsKey(url)) sTaskMap.remove(url) } } threadPool.execute { sTaskMap[url]?.invoke() } } fun removeTask(url: String) = threadPool.remove(sTaskMap[url]) fun clearTask() = sTaskMap.values.forEach { threadPool.remove(it) } fun clearCache() = this.clear() } fun fixImagePath(url: String): String { return if (url.startsWith("http")) url else "${Const.URL_BASE}$url" } }
apache-2.0
cc75fc28a2b77cff31d4255c5d0fa948
38.036184
134
0.576051
4.382201
false
false
false
false
DataDozer/DataDozer
core/src/main/kotlin/org/datadozer/search/AstParser.kt
1
3094
package org.datadozer.search import org.antlr.v4.runtime.CharStreams import org.antlr.v4.runtime.CommonTokenStream import org.antlr.v4.runtime.tree.ParseTreeWalker import org.apache.lucene.search.Query import org.datadozer.parser.FlexQueryBaseListener import org.datadozer.parser.FlexQueryLexer import org.datadozer.parser.FlexQueryParser import java.io.StringReader /* * Licensed to DataDozer under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. DataDozer licenses this file to you 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. */ fun parseQueryString(query: String): FlexQueryParser.StatementContext { val lexer = FlexQueryLexer(CharStreams.fromReader(StringReader(query))) lexer.removeErrorListeners() val tokens = CommonTokenStream(lexer) val parser = FlexQueryParser(tokens) parser.removeErrorListeners() parser.errorHandler = OperationMessageErrorStrategy() return parser.statement() } fun getQuery(context: FlexQueryParser.StatementContext?): Query? { val walker = ParseTreeWalker() val listener = QueryListener() walker.walk(listener, context) return listener.query } /** * Generates a lucene query by listening to the ANTLR parser events */ class QueryListener : FlexQueryBaseListener() { var query: Query? = null private set(value) { field = value } /** * Enter a parse tree produced by [FlexQueryParser.statement]. * @param ctx the parse tree */ override fun enterStatement(ctx: FlexQueryParser.StatementContext?) { } /** * Exit a parse tree produced by [FlexQueryParser.statement]. * @param ctx the parse tree */ override fun exitStatement(ctx: FlexQueryParser.StatementContext?) { } /** * Enter a parse tree produced by [FlexQueryParser.query]. * @param ctx the parse tree */ override fun enterQuery(ctx: FlexQueryParser.QueryContext?) { } /** * Exit a parse tree produced by [FlexQueryParser.query]. * @param ctx the parse tree */ override fun exitQuery(ctx: FlexQueryParser.QueryContext?) { } /** * Enter a parse tree produced by [FlexQueryParser.group]. * @param ctx the parse tree */ override fun enterGroup(ctx: FlexQueryParser.GroupContext?) { } /** * Exit a parse tree produced by [FlexQueryParser.group]. * @param ctx the parse tree */ override fun exitGroup(ctx: FlexQueryParser.GroupContext?) { } }
apache-2.0
5aa524ef175ecf38d5bb9badb6c7143c
29.038835
75
0.712346
4.22101
false
false
false
false
kotlintest/kotlintest
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/funspec/FunSpecExample.kt
1
1804
package com.sksamuel.kotest.specs.funspec import io.kotest.core.spec.IsolationMode import io.kotest.core.Tag import io.kotest.core.listeners.TestListener import io.kotest.core.test.TestCase import io.kotest.core.test.TestCaseOrder import io.kotest.core.test.TestResult import io.kotest.core.spec.Spec import io.kotest.core.spec.description import io.kotest.core.spec.style.FunSpec import io.kotest.extensions.locale.LocaleTestListener import io.kotest.extensions.locale.TimeZoneTestListener import java.util.Locale import java.util.TimeZone import kotlin.time.ExperimentalTime import kotlin.time.milliseconds @UseExperimental(ExperimentalTime::class) class FunSpecExample : FunSpec() { private val linuxTag = Tag("linux") private val jvmTag = Tag("JVM") override fun tags(): Set<Tag> = setOf(jvmTag, linuxTag) override fun beforeTest(testCase: TestCase) { println("Starting test ${testCase.description}") } override fun beforeSpec(spec: Spec) { println("Starting spec ${spec::class.description()}") } override fun afterSpec(spec: Spec) { println("Completed spec ${spec::class.description()}") } override fun afterTest(testCase: TestCase, result: TestResult) { println("Test ${testCase.description} completed with result $result") } override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf override fun listeners(): List<TestListener> = listOf(LocaleTestListener(Locale.CANADA_FRENCH), TimeZoneTestListener(TimeZone.getTimeZone("GMT"))) override fun testCaseOrder(): TestCaseOrder? = TestCaseOrder.Random init { test("this is a test") { // test here } test("this test has config").config(timeout = 412.milliseconds, enabled = true) { // test here } } }
apache-2.0
40c5547732a1822a7f10996c976303c4
30.103448
105
0.734479
4.264775
false
true
false
false
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/freenet/wot/IdentityManagerImpl.kt
1
4460
/* * Sone - IdentityManagerImpl.kt - Copyright © 2010–2020 David Roden * * 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 net.pterodactylus.sone.freenet.wot import com.google.common.eventbus.EventBus import com.google.common.eventbus.Subscribe import com.google.inject.Inject import com.google.inject.Singleton import net.pterodactylus.sone.core.event.StrictFilteringActivatedEvent import net.pterodactylus.sone.core.event.StrictFilteringDeactivatedEvent import net.pterodactylus.util.service.AbstractService import java.util.concurrent.TimeUnit.SECONDS import java.util.concurrent.atomic.AtomicBoolean import java.util.logging.Level import java.util.logging.Logger import java.util.logging.Logger.getLogger /** * The identity manager takes care of loading and storing identities, their * contexts, and properties. It does so in a way that does not expose errors via * exceptions but it only logs them and tries to return sensible defaults. * * * It is also responsible for polling identities from the Web of Trust plugin * and sending events to the [EventBus] when [Identity]s and * [OwnIdentity]s are discovered or disappearing. */ @Singleton class IdentityManagerImpl @Inject constructor( private val eventBus: EventBus, private val webOfTrustConnector: WebOfTrustConnector, private val identityLoader: IdentityLoader ) : AbstractService("Sone Identity Manager", false), IdentityManager { private val currentOwnIdentities = mutableSetOf<OwnIdentity>() private val strictFiltering = AtomicBoolean(false) override val isConnected: Boolean get() = notThrowing { webOfTrustConnector.ping() } override val allOwnIdentities: Set<OwnIdentity> get() = synchronized(currentOwnIdentities) { currentOwnIdentities.toSet() } override fun serviceRun() { var oldIdentities = mapOf<OwnIdentity, Collection<Identity>>() while (!shouldStop()) { try { val currentIdentities = identityLoader.loadAllIdentities().applyStrictFiltering() val identityChangeEventSender = IdentityChangeEventSender(eventBus, oldIdentities) identityChangeEventSender.detectChanges(currentIdentities) oldIdentities = currentIdentities synchronized(currentOwnIdentities) { currentOwnIdentities.clear() currentOwnIdentities.addAll(currentIdentities.keys) } } catch (wote1: WebOfTrustException) { logger.log(Level.WARNING, "WoT has disappeared!", wote1) } catch (e: Exception) { logger.log(Level.SEVERE, "Uncaught exception in IdentityManager thread!", e) } /* wait a minute before checking again. */ sleep(SECONDS.toMillis(60)) } } private fun Map<OwnIdentity, Set<Identity>>.applyStrictFiltering() = if (strictFiltering.get()) { val identitiesWithTrust = values.flatten() .groupBy { it.id } .mapValues { (_, identities) -> identities.reduce { accIdentity, identity -> identity.trust.forEach { (ownIdentity: OwnIdentity?, trust: Trust?) -> accIdentity.setTrust(ownIdentity, trust) } accIdentity } } mapValues { (_, trustedIdentities) -> trustedIdentities.filter { trustedIdentity -> identitiesWithTrust[trustedIdentity.id]!!.trust.all { it.value.hasZeroOrPositiveTrust() } } } } else { this } @Subscribe fun strictFilteringActivated(event: StrictFilteringActivatedEvent) { strictFiltering.set(true) } @Subscribe fun strictFilteringDeactivated(event: StrictFilteringDeactivatedEvent) { strictFiltering.set(false) } } private val logger: Logger = getLogger(IdentityManagerImpl::class.java.name) private fun notThrowing(action: () -> Unit): Boolean = try { action() true } catch (e: Exception) { false } private fun Trust.hasZeroOrPositiveTrust() = if (explicit == null) { implicit == null || implicit >= 0 } else { explicit >= 0 }
gpl-3.0
7ac7df91bc62603029529e7d2badcab7
31.532847
95
0.742876
4.008094
false
false
false
false
ffgiraldez/rx-mvvm-android
app/src/main/java/es/ffgiraldez/comicsearch/comics/data/storage/ComicDao.kt
1
1801
package es.ffgiraldez.comicsearch.comics.data.storage import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import androidx.room.Transaction import es.ffgiraldez.comicsearch.comics.domain.Volume import kotlinx.coroutines.flow.Flow @Dao abstract class SuspendSuggestionDao { @Query("SELECT * FROM queries WHERE search_term like :searchTerm") abstract fun findQueryByTerm(searchTerm: String): Flow<QueryEntity?> @Query("SELECT * FROM suggestions WHERE query_id = :queryId") abstract fun findSuggestionByQuery(queryId: Long): Flow<List<SuggestionEntity>> @Insert abstract suspend fun insert(query: QueryEntity): Long @Insert abstract suspend fun insert(vararg suggestions: SuggestionEntity) @Transaction @Insert suspend fun insert(query: String, volumeTitles: List<String>) { val id = insert(QueryEntity(0, query)) val suggestions = volumeTitles.map { SuggestionEntity(0, id, it) } insert(*suggestions.toTypedArray()) } } @Dao abstract class SuspendingVolumeDao { @Query("SELECT * FROM search WHERE search_term like :searchTerm") abstract fun findQueryByTerm(searchTerm: String): Flow<SearchEntity?> @Query("SELECT * FROM volumes WHERE search_id = :queryId") abstract fun findVolumeByQuery(queryId: Long): Flow<List<VolumeEntity>> @Insert abstract suspend fun insert(query: SearchEntity): Long @Insert abstract suspend fun insert(vararg suggestions: VolumeEntity) @Transaction @Insert suspend fun insert(query: String, volumeTitles: List<Volume>) { val id = insert(SearchEntity(0, query)) val suggestions = volumeTitles.map { VolumeEntity(0, id, it.title, it.author, it.cover) } insert(*suggestions.toTypedArray()) } }
apache-2.0
1ee233ed16d17b6672ecb329f2d5485a
29.542373
97
0.726263
4.267773
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/util/createSideEffect.kt
1
1684
package app.lawnchair.util import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember class PropsContainer<P>(var props: P) class SideEffect<S, P>( val consume: @Composable (@Composable (S) -> Unit) -> Unit, val provide: @Composable (P) -> Unit ) inline fun <S, P> createSideEffect(crossinline reducePropsToState: (List<P>) -> S): SideEffect<S, P> { val mountedInstances = mutableListOf<PropsContainer<P>>() var currentState = reducePropsToState(emptyList()) var onChangeHandler: (() -> Unit)? = null val emitChange = { currentState = reducePropsToState(mountedInstances.map { it.props }) onChangeHandler?.invoke() } return SideEffect( consume = @Composable { block -> val localState = remember { mutableStateOf(currentState) } DisposableEffect(null) { onChangeHandler = { localState.value = currentState } onDispose { onChangeHandler = null } } block(localState.value) }, provide = @Composable { props -> val currentProps = remember { PropsContainer(props) } DisposableEffect(key1 = currentProps) { mountedInstances.add(currentProps) onDispose { mountedInstances.remove(currentProps) emitChange() } } DisposableEffect(key1 = props) { currentProps.props = props emitChange() onDispose { } } } ) }
gpl-3.0
9cb0a1e266ccc2f5dd3bd884dd0e8fb5
32.68
102
0.601544
4.952941
false
false
false
false
xfournet/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/project/loadSaveModuleRenameMapping.kt
6
5028
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions.project import com.intellij.CommonBundle import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.fileChooser.FileSaverDescriptor import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ModuleRenamingHistoryState import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.wm.IdeFocusManager import com.intellij.util.loadElement import com.intellij.util.ui.UIUtil import com.intellij.util.write import com.intellij.util.xmlb.XmlSerializationException import com.intellij.util.xmlb.XmlSerializer import java.awt.event.ActionEvent import javax.swing.AbstractAction private val LOG = Logger.getInstance(LoadModuleRenamingSchemeAction::class.java) class LoadModuleRenamingSchemeAction(private val dialog: ConvertModuleGroupsToQualifiedNamesDialog) : AbstractAction() { init { UIUtil.setActionNameAndMnemonic(ProjectBundle.message("module.renaming.scheme.load.button.text"), this) } override fun actionPerformed(e: ActionEvent?) { val descriptor = FileChooserDescriptorFactory.createSingleFileDescriptor(StdFileTypes.XML) val file = FileChooser.chooseFile(descriptor, dialog.project, getDefaultRenamingSchemeFile(dialog.project)) ?: return fun showError(message: String) { Messages.showErrorDialog(dialog.project, ProjectBundle.message("module.renaming.scheme.cannot.load.error", file.presentableUrl, message), ProjectBundle.message("module.renaming.scheme.cannot.import.error.title")) } val renamingState = try { XmlSerializer.deserialize(loadElement(file.inputStream), ModuleRenamingHistoryState::class.java) } catch (e: XmlSerializationException) { LOG.info(e) showError(e.message ?: "unknown error") return } val moduleManager = ModuleManager.getInstance(dialog.project) renamingState.oldToNewName.keys.forEach { if (moduleManager.findModuleByName(it) == null) { showError(ProjectBundle.message("module.renaming.scheme.unknown.module.error", it)) return } } dialog.importRenamingScheme(renamingState.oldToNewName) IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown { IdeFocusManager.getGlobalInstance().requestFocus(dialog.preferredFocusedComponent, true) } } } class SaveModuleRenamingSchemeAction(private val dialog: ConvertModuleGroupsToQualifiedNamesDialog, private val onSaved: () -> Unit) : AbstractAction() { init { UIUtil.setActionNameAndMnemonic(ProjectBundle.message("module.renaming.scheme.save.button.text"), this) } override fun actionPerformed(e: ActionEvent?) { if (saveModuleRenamingScheme(dialog)) { onSaved() } } } internal fun saveModuleRenamingScheme(dialog: ConvertModuleGroupsToQualifiedNamesDialog): Boolean { val project = dialog.project val descriptor = FileSaverDescriptor(ProjectBundle.message("module.renaming.scheme.save.chooser.title"), ProjectBundle.message("module.renaming.scheme.save.chooser.description"), "xml") val baseDir = getDefaultRenamingSchemeFile(project)?.parent ?: project.baseDir val fileWrapper = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, project).save(baseDir, "module-renaming-scheme.xml") if (fileWrapper != null) { saveDefaultRenamingSchemeFilePath(project, FileUtil.toSystemIndependentName(fileWrapper.file.absolutePath)) val state = ModuleRenamingHistoryState() state.oldToNewName.putAll(dialog.getRenamingScheme()) try { XmlSerializer.serialize(state).write(fileWrapper.file.toPath()) fileWrapper.virtualFile?.refresh(true, false) return true } catch (e: Exception) { LOG.info(e) Messages.showErrorDialog(project, CommonBundle.getErrorTitle(), ProjectBundle.message("module.renaming.scheme.cannot.save.error", e.message ?: "")) } } return false } private const val EXPORTED_PATH_PROPERTY = "module.renaming.scheme.file" private fun saveDefaultRenamingSchemeFilePath(project: Project, filePath: String?) { PropertiesComponent.getInstance(project).setValue(EXPORTED_PATH_PROPERTY, filePath) } private fun getDefaultRenamingSchemeFile(project: Project) = PropertiesComponent.getInstance(project).getValue(EXPORTED_PATH_PROPERTY)?.let { LocalFileSystem.getInstance().refreshAndFindFileByPath(it) }
apache-2.0
f9fd8ebf947d17a8bcd038ea62d0520f
44.297297
153
0.777049
4.721127
false
false
false
false
hotshotmentors/Yengg-App-Android
app/src/main/java/in/yeng/user/newsupdates/helpers/NewsAdapter.kt
2
3150
package `in`.yeng.user.newsupdates.helpers import `in`.yeng.user.R import `in`.yeng.user.helpers.AnimUtil import `in`.yeng.user.helpers.DateHelper import `in`.yeng.user.helpers.NetworkHelper import `in`.yeng.user.helpers.viewbinders.BinderTypes import `in`.yeng.user.network.APIClient import `in`.yeng.user.newsupdates.ExpandedNews import `in`.yeng.user.newsupdates.dom.NewsRes import android.content.Intent import android.support.v4.content.FileProvider import android.support.v7.app.AppCompatActivity import android.support.v7.widget.RecyclerView import android.view.View import jp.satorufujiwara.binder.recycler.RecyclerBinder import kotlinx.android.synthetic.main.news_and_updates_card.view.* import org.jetbrains.anko.intentFor import org.jetbrains.anko.toast import java.io.File class NewsAdapter(activity: AppCompatActivity, val data: NewsRes) : RecyclerBinder<BinderTypes>(activity, BinderTypes.TYPE_NEWS_UPDATE) { override fun layoutResId(): Int = R.layout.news_and_updates_card override fun onCreateViewHolder(v: View): ViewHolder = ViewHolder(v) override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) { val holder = viewHolder as ViewHolder with(holder.view) { AnimUtil.fadeIn(this, 300) title.text = data.tittle news.text = data.news display_date.text = "Published ".plus(DateHelper.getRelativeDate(data.displayDate)) news_content.setOnClickListener { AnimUtil.clickAnimation(it) activity.startActivity(activity.intentFor<ExpandedNews>( "title" to data.tittle, "content" to data.news, "attachment" to data.attachmentPath )) } data.attachmentPath?.let { attachment_view.visibility = View.VISIBLE attachment_name.text = "View Attachment" attachment_view.setOnClickListener { progressBar.smoothToShow() AnimUtil.clickAnimation(it) NetworkHelper.onPDFDownloaded(activity, APIClient.YENG_BASEURL + "/" + data.attachmentPath.replace("public/", "")) { progressBar.smoothToHide() val file = File(activity.cacheDir, "pdfFile.pdf") val sharedURI = FileProvider.getUriForFile(activity, "in.yeng.user.PDFPROVIDER", file) val intent = Intent(Intent.ACTION_VIEW) intent.setDataAndType(sharedURI, "application/pdf") intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) val activities = activity.packageManager.queryIntentActivities(intent, 0) if (activities.isEmpty()) activity.toast("No PDF Viewers found. Get Adobe reader!..") else activity.startActivity(intent) } } } } } inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) }
gpl-3.0
eaca47bf1fe5e9441fd1c79d8abf1c98
39.397436
137
0.633651
4.525862
false
false
false
false
talhacohen/android
app/src/main/java/com/etesync/syncadapter/journalmanager/JournalAuthenticator.kt
1
1501
package com.etesync.syncadapter.journalmanager import com.etesync.syncadapter.GsonHelper import okhttp3.FormBody import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.Request import java.io.IOException import java.net.HttpURLConnection class JournalAuthenticator(private val client: OkHttpClient, remote: HttpUrl) { private val remote: HttpUrl init { this.remote = remote.newBuilder() .addPathSegments("api-token-auth") .addPathSegment("") .build() } private inner class AuthResponse private constructor() { val token: String? = null } @Throws(Exceptions.HttpException::class, IOException::class) fun getAuthToken(username: String, password: String): String? { val formBuilder = FormBody.Builder() .add("username", username) .add("password", password) val request = Request.Builder() .post(formBuilder.build()) .url(remote) .build() val response = client.newCall(request).execute() if (response.isSuccessful) { return GsonHelper.gson.fromJson(response.body()!!.charStream(), AuthResponse::class.java).token } else if (response.code() == HttpURLConnection.HTTP_BAD_REQUEST) { throw Exceptions.UnauthorizedException(response, "Username or password incorrect") } else { throw Exceptions.HttpException(response) } } }
gpl-3.0
4e7e875367cd44f3b90a3ffeb56ce30b
32.355556
107
0.644903
4.841935
false
false
false
false
toastkidjp/Yobidashi_kt
about/src/main/java/jp/toastkid/about/view/AboutThisAppUi.kt
1
8796
/* * Copyright (c) 2022 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.about.view import android.content.Intent import android.net.Uri import android.webkit.WebChromeClient import android.webkit.WebSettings import android.webkit.WebView import androidx.activity.ComponentActivity import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.TabRowDefaults import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.compose.ui.window.Dialog import androidx.core.net.toUri import androidx.lifecycle.ViewModelProvider import jp.toastkid.about.R import jp.toastkid.about.license.LicenseContentLoaderUseCase import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.intent.GooglePlayIntentFactory import jp.toastkid.lib.view.scroll.usecase.ScrollerUseCase import java.nio.charset.StandardCharsets @Composable fun AboutThisAppUi(versionName: String) { val context = LocalContext.current as? ComponentActivity ?: return val scrollState = rememberScrollState() val openLicense = remember { mutableStateOf(false) } val progress = remember { mutableStateOf(0f) } val invoke = LicenseContentLoaderUseCase(context.assets).invoke() val webView = WebView(context) webView.settings.also { it.javaScriptCanOpenWindowsAutomatically = false it.javaScriptEnabled = false it.blockNetworkLoads = false it.databaseEnabled = false it.domStorageEnabled = false it.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW } webView.webChromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView?, newProgress: Int) { super.onProgressChanged(view, newProgress) progress.value = newProgress.toFloat() / 100f } } webView.loadDataWithBaseURL( null, invoke, "text/html", StandardCharsets.UTF_8.name(), null ) Surface(elevation = 4.dp) { Column( Modifier .verticalScroll(scrollState) .padding(8.dp) ) { Text( text = stringResource(R.string.message_about_this_app), fontSize = 16.sp, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) InsetDivider() Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(56.dp) .clickable(onClick = { val packageName = context.applicationContext?.packageName ?: return@clickable context.startActivity(GooglePlayIntentFactory()(packageName)) }) .padding(start = 16.dp, end = 16.dp) ) { Image( painter = painterResource(id = R.drawable.ic_store_black), contentDescription = stringResource(R.string.title_go_google_play) ) Text( text = stringResource(R.string.title_go_google_play), fontSize = 16.sp ) } InsetDivider() Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(56.dp) .clickable(onClick = { val browserViewModel = ViewModelProvider(context).get(BrowserViewModel::class.java) browserViewModel.open( context .getString(R.string.link_privacy_policy) .toUri() ) }) .padding(start = 16.dp, end = 16.dp) ) { Image( painter = painterResource(id = R.drawable.ic_privacy), contentDescription = stringResource(R.string.privacy_policy) ) Text( text = stringResource(R.string.privacy_policy), fontSize = 16.sp ) } InsetDivider() Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(56.dp) .clickable(onClick = { openLicense.value = true }) .padding(start = 16.dp, end = 16.dp) ) { Image( painter = painterResource(id = R.drawable.ic_license_black), contentDescription = stringResource(R.string.title_licenses) ) Text( text = stringResource(R.string.title_licenses), fontSize = 16.sp ) } InsetDivider() Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(56.dp) .padding(start = 16.dp, end = 16.dp) ) { Text( text = stringResource(R.string.title_app_version) + versionName, fontSize = 16.sp ) } InsetDivider() Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(56.dp) .clickable(onClick = { context.startActivity( Intent(Intent.ACTION_VIEW) .also { it.data = Uri.parse("market://search?q=pub:toastkidjp") } ) }) .padding(start = 16.dp, end = 16.dp) ) { Text( text = stringResource(R.string.copyright), fontSize = 16.sp ) } } } if (openLicense.value) { Dialog( onDismissRequest = { openLicense.value = false } ) { Surface(elevation = 4.dp) { AndroidView( factory = { webView }, modifier = Modifier.fillMaxSize() ) if (progress.value < 0.75f) { CircularProgressIndicator( progress = progress.value, color = MaterialTheme.colors.primary ) } } } } val contentViewModel = ViewModelProvider(context).get(ContentViewModel::class.java) ScrollerUseCase(contentViewModel, scrollState).invoke(LocalLifecycleOwner.current) } @Composable private fun InsetDivider() { TabRowDefaults.Divider( color = colorResource(id = R.color.gray_500_dd), modifier = Modifier .fillMaxWidth() .height(1.dp) .padding(start = 16.dp, end = 16.dp) ) }
epl-1.0
d385c649860b146415cb2f5974f9d59a
34.467742
97
0.566962
5.305187
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsCompositeElement.kt
1
3060
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.extapi.psi.StubBasedPsiElementBase import com.intellij.lang.ASTNode import com.intellij.openapi.module.ModuleUtilCore import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.stubs.StubElement import com.intellij.psi.util.PsiTreeUtil import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.project.workspace.cargoWorkspace import org.rust.cargo.util.modules import org.rust.lang.core.psi.RsFile interface RsCompositeElement : PsiElement { /** * Find parent module *in this file*. See [RsMod.super] */ val containingMod: RsMod } val RsCompositeElement.cargoWorkspace: CargoWorkspace? get() { // It's important to look the module for `containingFile` file // and not the element itself. Otherwise this will break for // elements in libraries. val module = ModuleUtilCore.findModuleForPsiElement(containingFile) if (module != null) return module.cargoWorkspace // The element is outside of a module. Most likely, it is an element // from the library created by `RootsProvider`. Let's just hope there's // a single workspace in this case and return it. // Ideally, we need something more clever here, because there may be two // workspaces, which share the same library. return project.modules.map { it.cargoWorkspace }.firstOrNull { it != null } } val RsCompositeElement.crateRoot: RsMod? get() { return if (this is RsFile) { val root = superMods.lastOrNull() if (root != null && root.isCrateRoot) root else null } else { (context as? RsCompositeElement)?.crateRoot } } val RsCompositeElement.containingCargoTarget: CargoWorkspace.Target? get() { val ws = cargoWorkspace ?: return null val root = crateRoot ?: return null val file = root.containingFile.originalFile.virtualFile ?: return null return ws.findTargetByCrateRoot(file) } val RsCompositeElement.containingCargoPackage: CargoWorkspace.Package? get() = containingCargoTarget?.pkg abstract class RsCompositeElementImpl(node: ASTNode) : ASTWrapperPsiElement(node), RsCompositeElement { override val containingMod: RsMod get() = PsiTreeUtil.getStubOrPsiParentOfType(this, RsMod::class.java) ?: error("Element outside of module: $text") } abstract class RsStubbedElementImpl<StubT : StubElement<*>> : StubBasedPsiElementBase<StubT>, RsCompositeElement { constructor(node: ASTNode) : super(node) constructor(stub: StubT, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override val containingMod: RsMod get() = PsiTreeUtil.getStubOrPsiParentOfType(this, RsMod::class.java) ?: error("Element outside of module: $text") override fun toString(): String = "${javaClass.simpleName}($elementType)" }
mit
f0d5dba5a69bee46076e88713d6102f7
36.317073
114
0.732026
4.467153
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/centerdetails/CenterDetailsFragment.kt
1
7745
package com.mifos.mifosxdroid.online.centerdetails import android.app.Activity import android.os.Bundle import android.view.* import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.core.MifosBaseActivity import com.mifos.mifosxdroid.core.MifosBaseFragment import com.mifos.mifosxdroid.core.util.Toaster import com.mifos.mifosxdroid.online.activate.ActivateFragment import com.mifos.objects.group.CenterInfo import com.mifos.objects.group.CenterWithAssociations import com.mifos.utils.Constants import com.mifos.utils.FragmentConstants import com.mifos.utils.Utils import javax.inject.Inject /** * Created by Rajan Maurya on 05/02/17. */ class CenterDetailsFragment : MifosBaseFragment(), CenterDetailsMvpView { @JvmField @BindView(R.id.tv_center_activation_date) var tvActivationDate: TextView? = null @JvmField @BindView(R.id.tv_staff_name) var tvStaffName: TextView? = null @JvmField @BindView(R.id.tv_meeting_date) var tvMeetingDate: TextView? = null @JvmField @BindView(R.id.tv_meeting_frequency) var tvMeetingFrequency: TextView? = null @JvmField @BindView(R.id.tv_active_clients) var tvActiveClients: TextView? = null @JvmField @BindView(R.id.tv_active_group_loans) var tvActiveGroupLoans: TextView? = null @JvmField @BindView(R.id.tv_active_client_loans) var tvActiveClientLoans: TextView? = null @JvmField @BindView(R.id.tv_active_group_borrowers) var tvActiveGroupBorrowers: TextView? = null @JvmField @BindView(R.id.tv_active_client_borrowers) var tvActiveClientBorrowers: TextView? = null @JvmField @BindView(R.id.tv_active_overdue_group_loans) var tvActiveOverdueGroupLoans: TextView? = null @JvmField @BindView(R.id.tv_active_overdue_client_loans) var tvActiveOverdueClientLoans: TextView? = null @JvmField @BindView(R.id.rl_center) var rlCenter: RelativeLayout? = null @JvmField @BindView(R.id.ll_bottom_panel) var llBottomPanel: LinearLayout? = null @JvmField @Inject var centerDetailsPresenter: CenterDetailsPresenter? = null lateinit var rootView: View private var centerId = 0 private var listener: OnFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as MifosBaseActivity?)!!.activityComponent.inject(this) if (arguments != null) { centerId = requireArguments().getInt(Constants.CENTER_ID) } setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(R.layout.fragment_center_details, container, false) ButterKnife.bind(this, rootView) centerDetailsPresenter!!.attachView(this) centerDetailsPresenter!!.loadCentersGroupAndMeeting(centerId) centerDetailsPresenter!!.loadSummaryInfo(centerId) return rootView } @OnClick(R.id.btn_activate_center) fun onClickActivateCenter() { val activateFragment = ActivateFragment.newInstance(centerId, Constants.ACTIVATE_CENTER) val fragmentTransaction = requireActivity().supportFragmentManager .beginTransaction() fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CENTER_DETAIL) fragmentTransaction.replace(R.id.container, activateFragment) fragmentTransaction.commit() } override fun showProgressbar(show: Boolean) { if (show) { rlCenter!!.visibility = View.GONE showMifosProgressBar() } else { rlCenter!!.visibility = View.VISIBLE hideMifosProgressBar() } } override fun showCenterDetails(centerWithAssociations: CenterWithAssociations?) { setToolbarTitle(centerWithAssociations!!.name) if (!centerWithAssociations.activationDate.isEmpty()) { if (centerWithAssociations.staffName != null) { tvStaffName!!.text = centerWithAssociations.staffName } else { tvStaffName!!.setText(R.string.no_staff) } tvActivationDate!!.text = Utils.getStringOfDate(centerWithAssociations.activationDate) } } override fun showMeetingDetails(centerWithAssociations: CenterWithAssociations?) { if (!centerWithAssociations!!.active) { llBottomPanel!!.visibility = View.VISIBLE showErrorMessage(R.string.error_center_inactive) } if (centerWithAssociations.collectionMeetingCalendar.calendarInstanceId == null) { tvMeetingDate!!.text = getString(R.string.unassigned) if (view != null) { view!!.findViewById<View>(R.id.row_meeting_frequency).visibility = View.GONE } } else { tvMeetingDate!!.text = Utils.getStringOfDate(centerWithAssociations .collectionMeetingCalendar.nextTenRecurringDates[0]) if (view != null) { view!!.findViewById<View>(R.id.row_meeting_frequency).visibility = View.VISIBLE tvMeetingFrequency!!.text = centerWithAssociations.collectionMeetingCalendar .humanReadable } } } override fun showSummaryInfo(centerInfos: List<CenterInfo?>?) { val centerInfo = centerInfos?.get(0) tvActiveClients!!.text = centerInfo!!.activeClients.toString() tvActiveGroupLoans!!.text = centerInfo.activeGroupLoans.toString() tvActiveClientLoans!!.text = centerInfo.activeClientLoans.toString() tvActiveClientBorrowers!!.text = centerInfo.activeClientBorrowers.toString() tvActiveGroupBorrowers!!.text = centerInfo.activeGroupBorrowers.toString() tvActiveOverdueClientLoans!!.text = centerInfo.overdueClientLoans.toString() tvActiveOverdueGroupLoans!!.text = centerInfo.overdueGroupLoans.toString() } override fun showErrorMessage(message: Int) { Toaster.show(rootView, message) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_center, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val menuItemId = item.itemId when (menuItemId) { R.id.add_savings_account -> listener!!.addCenterSavingAccount(centerId) R.id.view_group_list -> listener!!.loadGroupsOfCenter(centerId) } return super.onOptionsItemSelected(item) } override fun onAttach(activity: Activity) { super.onAttach(activity) listener = try { activity as OnFragmentInteractionListener } catch (e: ClassCastException) { throw ClassCastException(activity.toString() + " must implement " + "OnFragmentInteractionListener") } } interface OnFragmentInteractionListener { fun addCenterSavingAccount(centerId: Int) fun loadGroupsOfCenter(centerId: Int) } override fun onDestroyView() { super.onDestroyView() centerDetailsPresenter!!.detachView() } companion object { @JvmStatic fun newInstance(centerId: Int): CenterDetailsFragment { val fragment = CenterDetailsFragment() val args = Bundle() args.putInt(Constants.CENTER_ID, centerId) fragment.arguments = args return fragment } } }
mpl-2.0
cee10ca287e2564146367cc33869efe1
35.027907
116
0.687669
4.668475
false
false
false
false
microg/android_packages_apps_GmsCore
play-services-maps-core-mapbox/src/main/kotlin/org/microg/gms/maps/mapbox/model/Markup.kt
1
1491
/* * Copyright (C) 2019 microG Project Team * * 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.microg.gms.maps.mapbox.model import android.util.Log import com.mapbox.mapboxsdk.plugins.annotation.Annotation import com.mapbox.mapboxsdk.plugins.annotation.AnnotationManager import com.mapbox.mapboxsdk.plugins.annotation.Options interface Markup<T : Annotation<*>, S : Options<T>> { var annotation: T? val annotationOptions: S val removed: Boolean fun update(manager: AnnotationManager<*, T, S, *, *, *>) { synchronized(this) { if (removed && annotation != null) { manager.delete(annotation) annotation = null } else if (annotation != null) { manager.update(annotation) } else if (!removed) { annotation = manager.create(annotationOptions) } } } companion object { private val TAG = "GmsMapMarkup" } }
apache-2.0
647791159790e16d5cc3598379aad416
32.155556
75
0.665325
4.359649
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/ui/ViewExtensions.kt
1
3512
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.ui import android.annotation.SuppressLint import android.os.Build import android.view.View import android.webkit.WebChromeClient import android.webkit.WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE import android.webkit.WebView import android.webkit.WebViewDatabase import android.widget.ImageView import android.widget.RemoteViews import androidx.appcompat.widget.TooltipCompat import androidx.core.graphics.drawable.DrawableCompat import androidx.core.net.toUri import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import okhttp3.HttpUrl import org.openhab.habdroid.R import org.openhab.habdroid.core.connection.Connection import org.openhab.habdroid.util.openInBrowser import org.openhab.habdroid.util.resolveThemedColor /** * Sets [SwipeRefreshLayout] color scheme according to colorPrimary and colorAccent */ fun SwipeRefreshLayout.applyColors() { val colors = listOf(R.attr.colorPrimary, R.attr.colorAccent) .map { attr -> context.resolveThemedColor(attr) } .toIntArray() setColorSchemeColors(*colors) } fun WebView.setUpForConnection( connection: Connection, url: HttpUrl, avoidAuthentication: Boolean = false, progressCallback: (progress: Int) -> Unit ) { if (!avoidAuthentication && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val webViewDatabase = WebViewDatabase.getInstance(context) webViewDatabase.setHttpAuthUsernamePassword(url.host, "", connection.username, connection.password) } else if (!avoidAuthentication) { @Suppress("DEPRECATION") setHttpAuthUsernamePassword(url.host, "", connection.username, connection.password) } with(settings) { domStorageEnabled = true @SuppressLint("SetJavaScriptEnabled") javaScriptEnabled = true mixedContentMode = MIXED_CONTENT_COMPATIBILITY_MODE } webViewClient = ConnectionWebViewClient(connection) webChromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView?, newProgress: Int) { progressCallback(newProgress) } } } fun ImageView.setupHelpIcon(url: String, contentDescriptionRes: Int) { val contentDescription = context.getString(contentDescriptionRes) this.contentDescription = contentDescription TooltipCompat.setTooltipText(this, contentDescription) setOnClickListener { url.toUri().openInBrowser(context) } } fun ImageView.updateHelpIconAlpha(isEnabled: Boolean) { alpha = if (isEnabled) 1.0f else 0.5f } fun View.playPressAnimationAndCallBack(postAnimationCallback: () -> Unit) { post { if (background != null) { val centerX = width / 2 val centerY = height / 2 DrawableCompat.setHotspot(background, centerX.toFloat(), centerY.toFloat()) } isPressed = true isPressed = false postAnimationCallback() } } fun RemoteViews.duplicate(): RemoteViews { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { RemoteViews(this) } else { @Suppress("DEPRECATION") clone() } }
epl-1.0
3b8011c8e60d43fd40ff23d1b13fdecb
31.518519
107
0.727506
4.462516
false
false
false
false
damien5314/HoldTheNarwhal
app/src/main/java/com/ddiehl/android/htn/listings/links/LinkViewHolderContextMenuUtil.kt
1
1959
package com.ddiehl.android.htn.listings.links import android.view.ContextMenu import android.view.View import androidx.fragment.app.FragmentActivity import com.ddiehl.android.htn.R import rxreddit.model.Link object LinkViewHolderContextMenuUtil { // FIXME: This is just for convenience before BaseLinkViewHolder is converted to Kotlin @JvmStatic fun showLinkContextMenu(menu: ContextMenu, view: View, link: Link) { (view.context as? FragmentActivity)?.menuInflater?.inflate(R.menu.link_context, menu) // Build title for menu val score = if (link.score == null) { view.context.getString(R.string.hidden_score_placeholder) } else { link.score.toString() } val title = view.context.getString(R.string.menu_action_link).format(link.title, score) menu.setHeaderTitle(title) // Set state of hide/unhide menu.findItem(R.id.action_link_hide).isVisible = !link.hidden menu.findItem(R.id.action_link_unhide).isVisible = link.hidden // Set subreddit for link in the view subreddit menu item val subreddit = view.context.getString(R.string.action_view_subreddit).format(link.subreddit) menu.findItem(R.id.action_link_view_subreddit).title = subreddit // Set username for link in the view user profile menu item val username = view.context.getString(R.string.action_view_user_profile).format(link.author) menu.findItem(R.id.action_link_view_user_profile).title = username // Hide user profile for posts by deleted users if ("[deleted]".equals(link.author, ignoreCase = true)) { menu.findItem(R.id.action_link_view_user_profile).isVisible = false } menu.findItem(R.id.action_link_reply).isVisible = false menu.findItem(R.id.action_link_save).isVisible = !link.isSaved menu.findItem(R.id.action_link_unsave).isVisible = link.isSaved } }
apache-2.0
1d460f64a75f252ddac7db64f7747922
41.586957
101
0.6927
3.949597
false
false
false
false
wleroux/fracturedskies
src/main/kotlin/com/fracturedskies/engine/math/Vector2.kt
1
848
package com.fracturedskies.engine.math import java.lang.Math.sqrt data class Vector2(var x: Float, var y: Float) { val magnitude: Float get() = sqrt((x * x + y * y).toDouble()).toFloat() companion object { val AXIS_X = Vector2(1f, 0f) val AXIS_NEG_X = Vector2(-1f, 0f) val AXIS_Y = Vector2(0f, 1f) val AXIS_NEG_Y = Vector2(0f, -1f) val ZERO = Vector2(0f, 0f) } override fun equals(other: Any?): Boolean { return when (other) { is Vector3 -> Math.abs(x - other.x) <= 0.00001f && Math.abs(y - other.y) <= 0.00001f else -> false } } operator fun plus(o: Vector3) = Vector2(this.x + o.x, this.y + o.y) operator fun minus(o: Vector3) = Vector2(this.x - o.x, this.y - o.y) operator fun times(s: Float) = Vector2(this.x * s, this.y * s) fun normalize() = times(1f / magnitude) }
unlicense
5acbd9451e311da2330b8b99ce58662c
28.275862
70
0.604953
2.780328
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/filterer/CollectionFiltererFactory.kt
1
1236
package com.boardgamegeek.filterer import android.content.Context class CollectionFiltererFactory(context: Context) { private val filterers: MutableList<CollectionFilterer> init { filterers = arrayListOf() filterers.add(CollectionStatusFilterer(context)) filterers.add(CollectionNameFilter(context)) filterers.add(PlayerNumberFilterer(context)) filterers.add(PlayTimeFilterer(context)) filterers.add(SuggestedAgeFilterer(context)) filterers.add(AverageWeightFilterer(context)) filterers.add(YearPublishedFilterer(context)) filterers.add(AverageRatingFilterer(context)) filterers.add(GeekRatingFilterer(context)) filterers.add(GeekRankingFilterer(context)) filterers.add(ExpansionStatusFilterer(context)) filterers.add(PlayCountFilterer(context)) filterers.add(MyRatingFilterer(context)) filterers.add(RecommendedPlayerCountFilterer(context)) filterers.add(FavoriteFilterer(context)) } fun create(type: Int): CollectionFilterer? { return filterers.find { it.type == type } } companion object { const val TYPE_UNKNOWN = -1 const val TYPE_STATUS = 1 } }
gpl-3.0
a2f0cb604a445ae375a4e32849fe5239
34.314286
62
0.710356
4.494545
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/item/inventory/ItemStack.kt
1
1553
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("FunctionName", "NOTHING_TO_INLINE") package org.lanternpowered.api.item.inventory import org.lanternpowered.api.item.ItemType import java.util.function.Supplier import kotlin.contracts.InvocationKind import kotlin.contracts.contract typealias ItemStackSnapshot = org.spongepowered.api.item.inventory.ItemStackSnapshot typealias ItemStackBuilder = org.spongepowered.api.item.inventory.ItemStack.Builder /** * Constructs a new [ItemStack] with the given [ItemType], quantity and * possibility to apply other data using the function. */ inline fun itemStackOf(type: Supplier<out ItemType>, quantity: Int = 1, block: ItemStackBuilder.() -> Unit = {}): ItemStack { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return itemStackOf(type.get(), quantity, block) } /** * Constructs a new [ItemStack] with the given [ItemType], quantity and * possibility to apply other data using the function. */ inline fun itemStackOf(type: ItemType, quantity: Int = 1, block: ItemStackBuilder.() -> Unit = {}): ItemStack { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return ItemStack.builder().itemType(type).quantity(quantity).apply(block).build() }
mit
36f727e23cc49880bebadc91c35c50e2
35.116279
125
0.739214
4.119363
false
false
false
false
jcam3ron/cassandra-migration
src/main/java/com/builtamont/cassandra/migration/internal/resolver/CompositeMigrationResolver.kt
1
5775
/** * File : CompositeMigrationResolver.kt * License : * Original - Copyright (c) 2010 - 2016 Boxfuse GmbH * Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd * * 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.builtamont.cassandra.migration.internal.resolver import com.builtamont.cassandra.migration.api.CassandraMigrationException import com.builtamont.cassandra.migration.api.resolver.MigrationResolver import com.builtamont.cassandra.migration.api.resolver.ResolvedMigration import com.builtamont.cassandra.migration.internal.resolver.cql.CqlMigrationResolver import com.builtamont.cassandra.migration.internal.resolver.java.JavaMigrationResolver import com.builtamont.cassandra.migration.internal.util.Locations import java.util.* /** * Facility for retrieving and sorting the available migrations from the classpath through the various migration * resolvers. * * @param classLoader The ClassLoader for loading migrations on the classpath. * @param locations The locations where migrations are located. * @param encoding The encoding of Cql migrations. * @param customMigrationResolvers Custom Migration Resolvers. */ class CompositeMigrationResolver( classLoader: ClassLoader, locations: Locations, encoding: String, vararg customMigrationResolvers: MigrationResolver ) : MigrationResolver { /** * The migration resolvers to use internally. */ private val migrationResolvers = ArrayList<MigrationResolver>() /** * The available migrations, sorted by version, newest first. An empty list is returned when no migrations can be * found. */ private var availableMigrations: List<ResolvedMigration>? = null /** * CompositeMigrationResolver initialization. */ init { locations.getLocations().forEach { migrationResolvers.add(CqlMigrationResolver(classLoader, it, encoding)) migrationResolvers.add(JavaMigrationResolver(classLoader, it)) } migrationResolvers.addAll(Arrays.asList(*customMigrationResolvers)) } /** * Finds all available migrations using all migration resolvers (CQL, Java, ...). * * @return The available migrations, sorted by version, oldest first. An empty list is returned when no migrations * can be found. * @throws CassandraMigrationException when the available migrations have overlapping versions. */ override fun resolveMigrations(): List<ResolvedMigration> { if (availableMigrations == null) { availableMigrations = doFindAvailableMigrations() } return availableMigrations as List<ResolvedMigration> } /** * Finds all available migrations using all migration resolvers (CQL, Java, ...). * * @return The available migrations, sorted by version, oldest first. An empty list is returned when no migrations * can be found. * @throws CassandraMigrationException when the available migrations have overlapping versions. */ @Throws(CassandraMigrationException::class) private fun doFindAvailableMigrations(): List<ResolvedMigration> { val migrations = ArrayList(collectMigrations(migrationResolvers)) migrations.sortWith(ResolvedMigrationComparator()) checkForIncompatibilities(migrations) return migrations } /** * CompositeMigrationResolver companion object. */ companion object { /** * Collects all the migrations for all migration resolvers. * * @param migrationResolvers The migration resolvers to check. * @return All migrations. */ fun collectMigrations(migrationResolvers: Collection<MigrationResolver>): Collection<ResolvedMigration> { return migrationResolvers.flatMap { it.resolveMigrations() }.distinct() } /** * Checks for incompatible migrations. * * @param migrations The migrations to check. * @throws CassandraMigrationException when two different migration with the same version number are found. */ fun checkForIncompatibilities(migrations: List<ResolvedMigration>) { /** * Returns incompatible migration error message. * * @param current The current migration run. * @param next The next migration to run. * @return Incompatible migration error message. */ fun incompatibleErrorMsg(current: ResolvedMigration, next: ResolvedMigration): String { return "Found more than one migration with version ${current.version}\nOffenders:\n-> ${current.physicalLocation} (${current.type})\n-> ${next.physicalLocation} (${next.type})" } // Check for more than one migration with same version for (i in 0..migrations.size - 1 - 1) { val current = migrations[i] val next = migrations[i + 1] if (current.version!!.compareTo(next.version) == 0) { throw CassandraMigrationException(incompatibleErrorMsg(current, next)) } } } } }
apache-2.0
7ec1ccd423b9ad5e310612372578561c
38.554795
192
0.686407
5.10159
false
false
false
false
debop/debop4k
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/models/Datepart.kt
1
2278
/* * Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.timeperiod.models import debop4k.core.AbstractValueObject import debop4k.core.ToStringHelper import debop4k.core.kodatimes.asDate import debop4k.core.utils.hashOf import debop4k.timeperiod.MillisPerDay import org.joda.time.DateTime /** * Datepart * @author [email protected] */ class Datepart(_value: DateTime) : AbstractValueObject(), Comparable<Datepart> { val value: DateTime init { value = _value.withTimeAtStartOfDay() } val year: Int get() = value.year val month: Int get() = value.monthOfYear val dayOfMonth: Int get() = value.dayOfMonth operator fun plus(timepart: Timepart): DateTime { return value + timepart.totalMillis } @JvmOverloads fun toDateTime(hour: Int = 0, minute: Int = 0, second: Int = 0, millis: Int = 0): DateTime { return this + Timepart(hour, minute, second, millis) } fun toDateTime(timepart: Timepart): DateTime { return value + timepart.totalMillis } fun toDateTime(millis: Long): DateTime { return value.plus(millis % MillisPerDay) } override fun compareTo(other: Datepart): Int { return value.compareTo(other.value) } override fun hashCode(): Int { return hashOf(value) } override fun buildStringHelper(): ToStringHelper { return super.buildStringHelper().add("value", value) } companion object { @JvmStatic @JvmOverloads fun of(value: DateTime = debop4k.core.kodatimes.today()): Datepart = Datepart(value) @JvmStatic @JvmOverloads fun of(year: Int, monthOfYear: Int = 1, dayOfMonth: Int = 1): Datepart { return Datepart(asDate(year, monthOfYear, dayOfMonth)) } } }
apache-2.0
b28796cb927c0445bdce96b71d20ec1d
26.792683
94
0.713784
3.867572
false
false
false
false
FHannes/intellij-community
plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalProjectOptionsProvider.kt
11
3809
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.terminal import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.SystemInfo import java.io.File import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty /** * @author traff */ @State(name = "TerminalProjectOptionsProvider", storages = arrayOf(Storage("terminal.xml"))) class TerminalProjectOptionsProvider(val project: Project) : PersistentStateComponent<TerminalProjectOptionsProvider.State> { private val myState = State() override fun getState(): State? { return myState } override fun loadState(state: State) { myState.myStartingDirectory = state.myStartingDirectory } class State { var myStartingDirectory: String? = null } var startingDirectory: String? by ValueWithDefault(State::myStartingDirectory, myState) { defaultStartingDirectory } val defaultStartingDirectory: String? get() { var directory: String? = null for (customizer in LocalTerminalCustomizer.EP_NAME.extensions) { try { if (directory == null) { directory = customizer.getDefaultFolder(project) } } catch (e: Exception) { LOG.error("Exception during getting default folder", e) } } return directory ?: currentProjectFolder() } private fun currentProjectFolder(): String? { val projectRootManager = ProjectRootManager.getInstance(project) val roots = projectRootManager.contentRoots if (roots.size == 1) { roots[0].canonicalPath } val baseDir = project.baseDir return baseDir?.canonicalPath } val defaultShellPath: String get() { val shell = System.getenv("SHELL") if (shell != null && File(shell).canExecute()) { return shell } if (SystemInfo.isUnix) { if (File("/bin/bash").exists()) { return "/bin/bash" } else { return "/bin/sh" } } else { return "cmd.exe" } } companion object { private val LOG = Logger.getInstance(TerminalProjectOptionsProvider::class.java) fun getInstance(project: Project): TerminalProjectOptionsProvider { return ServiceManager.getService(project, TerminalProjectOptionsProvider::class.java) } } } // TODO: In Kotlin 1.1 it will be possible to pass references to instance properties. Until then we need 'state' argument as a reciever for // to property to apply class ValueWithDefault<S>(val prop: KMutableProperty1<S, String?>, val state: S, val default: () -> String?) { operator fun getValue(thisRef: Any?, property: KProperty<*>): String? { return if (prop.get(state) !== null) prop.get(state) else default() } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String?) { prop.set(state, if (value == default() || value.isNullOrEmpty()) null else value) } }
apache-2.0
4452832fab7729baac4264f6b685c481
28.992126
139
0.700709
4.475911
false
false
false
false
googlesamples/mlkit
android/material-showcase/app/src/main/java/com/google/mlkit/md/objectdetection/ObjectConfirmationController.kt
1
2278
/* * Copyright 2020 Google 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.md.objectdetection import android.os.CountDownTimer import com.google.mlkit.md.camera.GraphicOverlay import com.google.mlkit.md.settings.PreferenceUtils /** * Controls the progress of object confirmation before performing additional operation on the * detected object. */ internal class ObjectConfirmationController /** * @param graphicOverlay Used to refresh camera overlay when the confirmation progress updates. */ (graphicOverlay: GraphicOverlay) { private val countDownTimer: CountDownTimer private var objectId: Int? = null /** Returns the confirmation progress described as a float value in the range of [0, 1]. */ var progress = 0f private set val isConfirmed: Boolean get() = progress.compareTo(1f) == 0 init { val confirmationTimeMs = PreferenceUtils.getConfirmationTimeMs(graphicOverlay.context).toLong() countDownTimer = object : CountDownTimer(confirmationTimeMs, /* countDownInterval= */ 20) { override fun onTick(millisUntilFinished: Long) { progress = (confirmationTimeMs - millisUntilFinished).toFloat() / confirmationTimeMs graphicOverlay.invalidate() } override fun onFinish() { progress = 1f } } } fun confirming(objectId: Int?) { if (objectId == this.objectId) { // Do nothing if it's already in confirming. return } reset() this.objectId = objectId countDownTimer.start() } fun reset() { countDownTimer.cancel() objectId = null progress = 0f } }
apache-2.0
d2ba32079f1021b42a3d3f8349fd8e26
29.783784
103
0.672081
4.836518
false
false
false
false
FHannes/intellij-community
uast/uast-common/src/org/jetbrains/uast/values/UValueBase.kt
3
3988
/* * Copyright 2000-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. */ package org.jetbrains.uast.values abstract class UValueBase : UValue { override operator fun plus(other: UValue): UValue = if (other is UDependentValue) other + this else UUndeterminedValue override operator fun minus(other: UValue): UValue = this + (-other) override operator fun times(other: UValue): UValue = if (other is UDependentValue) other * this else UUndeterminedValue override operator fun div(other: UValue): UValue = (other as? UDependentValue)?.inverseDiv(this) ?: UUndeterminedValue override operator fun mod(other: UValue): UValue = (other as? UDependentValue)?.inverseMod(this) ?: UUndeterminedValue override fun unaryMinus(): UValue = UUndeterminedValue override fun valueEquals(other: UValue): UValue = if (other is UDependentValue || other is UNaNConstant) other.valueEquals(this) else UUndeterminedValue override fun valueNotEquals(other: UValue): UValue = !this.valueEquals(other) override fun identityEquals(other: UValue): UValue = valueEquals(other) override fun identityNotEquals(other: UValue): UValue = !this.identityEquals(other) override fun not(): UValue = UUndeterminedValue override fun greater(other: UValue): UValue = if (other is UDependentValue || other is UNaNConstant) other.less(this) else UUndeterminedValue override fun less(other: UValue): UValue = other.greater(this) override fun greaterOrEquals(other: UValue) = this.greater(other) or this.valueEquals(other) override fun lessOrEquals(other: UValue) = this.less(other) or this.valueEquals(other) override fun inc(): UValue = UUndeterminedValue override fun dec(): UValue = UUndeterminedValue override fun and(other: UValue): UValue = if (other is UDependentValue || other == UBooleanConstant.False) other and this else UUndeterminedValue override fun or(other: UValue): UValue = if (other is UDependentValue || other == UBooleanConstant.True) other or this else UUndeterminedValue override fun bitwiseAnd(other: UValue): UValue = if (other is UDependentValue) other bitwiseAnd this else UUndeterminedValue override fun bitwiseOr(other: UValue): UValue = if (other is UDependentValue) other bitwiseOr this else UUndeterminedValue override fun bitwiseXor(other: UValue): UValue = if (other is UDependentValue) other bitwiseXor this else UUndeterminedValue override fun shl(other: UValue): UValue = (other as? UDependentValue)?.inverseShiftLeft(this) ?: UUndeterminedValue override fun shr(other: UValue): UValue = (other as? UDependentValue)?.inverseShiftRight(this) ?: UUndeterminedValue override fun ushr(other: UValue): UValue = (other as? UDependentValue)?.inverseShiftRightUnsigned(this) ?: UUndeterminedValue override fun merge(other: UValue): UValue = when (other) { this -> this is UVariableValue -> other.merge(this) else -> UPhiValue.create(this, other) } override val dependencies: Set<UDependency> get() = emptySet() override fun toConstant(): UConstant? = this as? UConstant internal open fun coerceConstant(constant: UConstant): UValue = constant override val reachable = true override abstract fun toString(): String }
apache-2.0
c84a94cd29cc1c26f27a9724d3676934
38.89
115
0.712638
4.725118
false
false
false
false
FHannes/intellij-community
uast/uast-common/src/org/jetbrains/uast/evaluation/AbstractEvaluationState.kt
2
2011
/* * Copyright 2000-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. */ package org.jetbrains.uast.evaluation import org.jetbrains.uast.UElement import org.jetbrains.uast.UVariable import org.jetbrains.uast.values.UValue import org.jetbrains.uast.values.UVariableValue abstract class AbstractEvaluationState(override val boundElement: UElement? = null) : UEvaluationState { override fun assign(variable: UVariable, value: UValue, at: UElement): AbstractEvaluationState { val variableValue = UVariableValue.create(variable, value) val prevVariableValue = this[variable] return if (prevVariableValue == variableValue) this else DelegatingEvaluationState( boundElement = at, variableValue = variableValue, baseState = this ) } override fun merge(otherState: UEvaluationState) = if (this == otherState) this else MergingEvaluationState(this, otherState) override fun equals(other: Any?) = other is UEvaluationState && variables == other.variables && variables.all { this[it] == other[it] } override fun hashCode(): Int { var result = 31 result = result * 19 + variables.hashCode() result = result * 19 + variables.map { this[it].hashCode() }.sum() return result } override fun toString() = variables.joinToString(prefix = "[", postfix = "]", separator = ", ") { "${it.psi.name} = ${this[it]}" } }
apache-2.0
f0c74e363d42b09a45f9e1e2e6086baf
38.45098
112
0.685728
4.439294
false
false
false
false
hartwigmedical/hmftools
cider/src/main/java/com/hartwig/hmftools/cider/VJAnchorTemplate.kt
1
2415
package com.hartwig.hmftools.cider import com.hartwig.hmftools.common.codon.Codons import com.hartwig.hmftools.common.genome.region.Strand import com.hartwig.hmftools.common.utils.sv.ChrBaseRegion data class GenomeRegionStrand(val chromosome: String, val posStart: Int, val posEnd: Int, val strand: Strand) : ChrBaseRegion(chromosome, posStart, posEnd) { operator fun compareTo(other: GenomeRegionStrand): Int { val baseRegionCompare = super.compareTo(other) return if (baseRegionCompare == 0) strand.compareTo(other.strand) else baseRegionCompare } override fun toString(): String { return "${chromosome}:${posStart}-${posEnd}(${strand.asChar()})" } } data class VJAnchorTemplate ( val type: VJGeneType, val geneName: String, // IGHV1-45 val allele: String, // 01 val geneLocation: GenomeRegionStrand?, val sequence: String, val anchorSequence: String, val anchorLocation: GenomeRegionStrand? ) { val vj: VJ get() { return type.vj } val anchorAminoAcidSequence: String = Codons.aminoAcidFromBases(anchorSequence) val chromosome: String? get() { return geneLocation?.chromosome() } //val startPosition: Int get() { return geneLocation?.start() ?: -1 } //val endPosition: Int get() { return geneLocation?.end() ?: -1 } val strand: Strand? get() { return geneLocation?.strand } } // store the anchor location and also the type of the gene segment data class VJAnchorGenomeLocation(val vjGeneType: VJGeneType, val genomeLocation: GenomeRegionStrand) { val vj: VJ get() = vjGeneType.vj val chromosome: String get() = genomeLocation.chromosome val start: Int get() = genomeLocation.posStart val end: Int get() = genomeLocation.posEnd val strand: Strand get() = genomeLocation.strand fun baseLength() : Int { return genomeLocation.baseLength() } // get the reference position of the end of the anchor // this is the end of the C codon for V and the start of the W / F codon for J fun anchorBoundaryReferencePosition() : Int { return if (vjGeneType.vj == VJ.V && genomeLocation.strand == Strand.FORWARD || vjGeneType.vj == VJ.J && genomeLocation.strand == Strand.REVERSE) { genomeLocation.posEnd } else { genomeLocation.posStart } } }
gpl-3.0
b908803ebc518017088f086fccb625a6
34
109
0.672878
4.052013
false
false
false
false
FHannes/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/WorkList.kt
12
1848
/* * Copyright 2000-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. */ package org.jetbrains.plugins.groovy.lang.psi.dataFlow import java.util.* internal class WorkList(order: IntArray) { private val mySize: Int = order.size /** * Mapping: index -> instruction number */ private val myOrder: IntArray = order /** * Mapping: instruction number -> index in [myOrder] array */ private val myInstructionToOrder: IntArray = IntArray(mySize) /** * Mapping: index -> whether instruction number needs to be processed * * Indexes match [myOrder] indexes */ private val mySet: BitSet = BitSet() init { order.forEachIndexed { index, instruction -> myInstructionToOrder[instruction] = index } mySet.set(0, mySize) } val isEmpty: Boolean get() = mySet.isEmpty /** * Instruction number to be processed next */ fun next(): Int { /** * Index of instruction in [myOrder] */ val next = mySet.nextSetBit(0) assert(next >= 0 && next < mySize) mySet.clear(next) return myOrder[next] } /** * Marks instruction to be processed */ fun offer(instructionIndex: Int) { /** * Index of instruction in [myOrder] */ val orderIndex = myInstructionToOrder[instructionIndex] mySet.set(orderIndex, true) } }
apache-2.0
1decd995543d377735102188153fa4bf
25.4
75
0.676948
3.982759
false
false
false
false
chemouna/RxBinding
rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/view/RxView.kt
1
11420
package com.jakewharton.rxbinding.view import android.view.DragEvent import android.view.MotionEvent import android.view.View import com.jakewharton.rxbinding.internal.Functions import rx.Observable import rx.functions.Action1 import rx.functions.Func0 import rx.functions.Func1 /** * Create an observable which emits on `view` attach events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.attaches(): Observable<Any> = RxView.attaches(this) /** * Create an observable of attach and detach events on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.attachEvents(): Observable<ViewAttachEvent> = RxView.attachEvents(this) /** * Create an observable which emits on `view` detach events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.detaches(): Observable<Any> = RxView.detaches(this) /** * Create an observable which emits on `view` click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnClickListener] to observe * clicks. Only one observable can be used for a view at a time. */ public inline fun View.clicks(): Observable<Any> = RxView.clicks(this) /** * Create an observable of click events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnClickListener] to observe * clicks. Only one observable can be used for a view at a time. */ public inline fun View.clickEvents(): Observable<ViewClickEvent> = RxView.clickEvents(this) /** * Create an observable of [DragEvent] for drags on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnDragListener] to observe * drags. Only one observable can be used for a view at a time. */ public inline fun View.drags(): Observable<DragEvent> = RxView.drags(this) /** * Create an observable of [DragEvent] for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnDragListener] to observe * drags. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnDragListener]. */ public inline fun View.drags(handled: Func1<in DragEvent, Boolean>): Observable<DragEvent> = RxView.drags(this, handled) /** * Create an observable of drag events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnDragListener] to observe * drags. Only one observable can be used for a view at a time. */ public inline fun View.dragEvents(): Observable<ViewDragEvent> = RxView.dragEvents(this) /** * Create an observable of drag events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnDragListener] to observe * drags. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnDragListener]. */ public inline fun View.dragEvents(handled: Func1<in ViewDragEvent, Boolean>): Observable<ViewDragEvent> = RxView.dragEvents(this, handled) /** * Create an observable of booleans representing the focus of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnFocusChangeListener] to observe * focus change. Only one observable can be used for a view at a time. * * *Note:* A value will be emitted immediately on subscribe. */ public inline fun View.focusChanges(): Observable<Boolean> = RxView.focusChanges(this) /** * Create an observable of focus-change events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnFocusChangeListener] to observe * focus change. Only one observable can be used for a view at a time. * * *Note:* A value will be emitted immediately on subscribe. */ public inline fun View.focusChangeEvents(): Observable<ViewFocusChangeEvent> = RxView.focusChangeEvents(this) /** * Create an observable which emits on `view` long-click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnLongClickListener] to observe * long clicks. Only one observable can be used for a view at a time. */ public inline fun View.longClicks(): Observable<Any> = RxView.longClicks(this) /** * Create an observable which emits on `view` long-click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnLongClickListener] to observe * long clicks. Only one observable can be used for a view at a time. * * @param handled Function invoked each occurrence to determine the return value of the * underlying [View.OnLongClickListener]. */ public inline fun View.longClicks(handled: Func0<Boolean>): Observable<Any> = RxView.longClicks(this, handled) /** * Create an observable of long-clicks events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnLongClickListener] to observe * long clicks. Only one observable can be used for a view at a time. */ public inline fun View.longClickEvents(): Observable<ViewLongClickEvent> = RxView.longClickEvents(this) /** * Create an observable of long-click events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnLongClickListener] to observe * long clicks. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnLongClickListener]. */ public inline fun View.longClickEvents(handled: Func1<in ViewLongClickEvent, Boolean>): Observable<ViewLongClickEvent> = RxView.longClickEvents(this, handled) /** * Create an observable of touch events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnTouchListener] to observe * touches. Only one observable can be used for a view at a time. */ public inline fun View.touches(): Observable<MotionEvent> = RxView.touches(this) /** * Create an observable of touch events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnTouchListener] to observe * touches. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnTouchListener]. */ public inline fun View.touches(handled: Func1<in MotionEvent, Boolean>): Observable<MotionEvent> = RxView.touches(this, handled) /** * Create an observable of touch events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnTouchListener] to observe * touches. Only one observable can be used for a view at a time. */ public inline fun View.touchEvents(): Observable<ViewTouchEvent> = RxView.touchEvents(this) /** * Create an observable of touch events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnTouchListener] to observe * touches. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnTouchListener]. */ public inline fun View.touchEvents(handled: Func1<in ViewTouchEvent, Boolean>): Observable<ViewTouchEvent> = RxView.touchEvents(this, handled) /** * An action which sets the activated property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.activated(): Action1<in Boolean> = RxView.activated(this) /** * An action which sets the clickable property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.clickable(): Action1<in Boolean> = RxView.clickable(this) /** * An action which sets the enabled property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.enabled(): Action1<in Boolean> = RxView.enabled(this) /** * An action which sets the pressed property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.pressed(): Action1<in Boolean> = RxView.pressed(this) /** * An action which sets the selected property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.selected(): Action1<in Boolean> = RxView.selected(this) /** * An action which sets the visibility property of `view`. `false` values use * `View.GONE`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.visibility(): Action1<in Boolean> = RxView.visibility(this) /** * An action which sets the visibility property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * @param visibilityWhenFalse Visibility to set on a `false` value (`View.INVISIBLE` * or `View.GONE`). */ public inline fun View.visibility(visibilityWhenFalse: Int): Action1<in Boolean> = RxView.visibility(this, visibilityWhenFalse)
apache-2.0
9f59159b53ef77ef528b3ae646ff0f3d
37.451178
158
0.739667
4.200074
false
false
false
false
schaal/ocreader
app/src/main/java/email/schaal/ocreader/view/ArticleWebView.kt
1
7113
package email.schaal.ocreader.view import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.util.Log import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.core.content.res.use import androidx.preference.PreferenceManager import email.schaal.ocreader.Preferences import email.schaal.ocreader.R import email.schaal.ocreader.database.model.Item import email.schaal.ocreader.util.FaviconLoader import email.schaal.ocreader.util.FaviconLoader.FeedColorsListener import email.schaal.ocreader.util.FeedColors import email.schaal.ocreader.util.asCssString import email.schaal.ocreader.util.getByLine import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.jsoup.safety.Cleaner import org.jsoup.safety.Safelist import java.util.* import java.util.regex.Pattern /** * WebView to display a Item */ @SuppressLint("SetJavaScriptEnabled") class ArticleWebView(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0): NestedScrollWebView(context, attrs, defStyleAttr) { @ColorInt private var defaultLinkColor = 0 @ColorInt private var fontColor = 0 @ColorInt private var backColor = 0 private var item: Item? = null constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context) : this(context, null) private val feedColorsListener: FeedColorsListener = object : FeedColorsListener { override fun onGenerated(feedColors: FeedColors) { evaluateJavascript( resources.getString( R.string.style_change_js, feedColors.getColor(FeedColors.Type.TEXT, defaultLinkColor).asCssString() ), null ) } override fun onStart() {} } init { context.obtainStyledAttributes(attrs, R.styleable.ArticleWebView).use { typedArray -> defaultLinkColor = typedArray.getColor(R.styleable.ArticleWebView_linkColor, 0) fontColor = typedArray.getColor(R.styleable.ArticleWebView_fontColor, 0) backColor = typedArray.getColor(R.styleable.ArticleWebView_backgroundColor, 0) } setBackgroundColor(backColor) settings.apply { javaScriptEnabled = true builtInZoomControls = true displayZoomControls = false offscreenPreRaster = true } } fun setItem(item: Item?) { this.item = item loadDataWithBaseURL("file:///android_asset/", html, "text/html", "UTF-8", null) postVisualStateCallback(1, object: VisualStateCallback() { override fun onComplete(requestId: Long) { FaviconLoader.Builder() .build() .load([email protected], item?.feed, feedColorsListener) } }) } private val html: String get() { val context = context val font = Preferences.ARTICLE_FONT.getString(PreferenceManager.getDefaultSharedPreferences(context)) val document = cleaner.clean(Jsoup.parse(item?.body)).apply { outputSettings().prettyPrint(false) prepareDocument() } val firstImage = document.extractFirstImg() return context.getString( R.string.article_html_template, defaultLinkColor.asCssString(), fontColor.asCssString(), backColor.asCssString(), ContextCompat.getColor(context, R.color.selected_background).asCssString(), item?.url ?: "", item?.title, getByLine(context, "<p class=\"byline\">%s</p>", item?.author, item?.feed), document.body().html(), firstImage ?: "", if ("system" != font) context.getString(R.string.crimson_font_css) else "" ) } private fun Document.extractFirstImg(): String? { try { var child: Element? = body().child(0) // if document starts with <br>, remove it if (child?.tagName() == "br") { val brChild = child child = child.nextElementSibling() brChild.remove() } while (child != null && child.tagName() != "img") { child = child.children().first() } return child?.run { remove() addClass("headerimg") toString() } } catch (e: IndexOutOfBoundsException) { Log.e(TAG, "Body has no children", e) } return null } /** * Enum to convert some common iframe urls to simpler formats */ private enum class IframePattern(val pattern: Pattern, val baseUrl: String, val thumbUrl: String?) { YOUTUBE(Pattern.compile("(https?://)(?:www\\.)?youtube\\.com/embed/([a-zA-Z0-9-_]+)(?:\\?.*)?"), "youtu.be/", "%simg.youtube.com/vi/%s/sddefault.jpg"), VIMEO(Pattern.compile("(https?://)(?:www\\.)?player\\.vimeo\\.com/video/([a-zA-Z0-9]+)"), "vimeo.com/", null); } private fun Document.prepareDocument(): Document { for (iframe in getElementsByTag("iframe")) { if (iframe.hasAttr("src")) { var href = iframe.attr("src") var html = String.format(Locale.US, videoLink, href, href) // Check if url matches any known patterns for (iframePattern in IframePattern.values()) { val matcher = iframePattern.pattern.matcher(href) if (matcher.matches()) { val videoId = matcher.group(2) val urlPrefix = matcher.group(1) ?: "https://" href = urlPrefix + iframePattern.baseUrl + videoId // use thumbnail if available if (iframePattern.thumbUrl != null) { val thumbUrl = String.format(iframePattern.thumbUrl, urlPrefix, videoId) html = String.format(Locale.US, videoThumbLink, href, thumbUrl) } break } } iframe.replaceWith(Jsoup.parse(html).body().child(0)) } else { iframe.remove() } } return this } companion object { private val TAG = ArticleWebView::class.java.name // iframes are replaced in prepareDocument() private val cleaner = Cleaner(Safelist.relaxed() .addTags("video", "iframe") .addAttributes("iframe", "src") .preserveRelativeLinks(true)) private const val videoThumbLink = """<div style="position:relative"><a href="%s"><img src="%s" class="videothumb"></img><span class="play">▶</span></a></div>""" private const val videoLink = """<a href="%s">%s</a>""" } }
gpl-3.0
f47a465bb63a5949707218c6dccc9974
37.863388
169
0.587681
4.647712
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/backup/impl/BackupV4.kt
1
13614
package cc.aoeiuv020.panovel.backup.impl import android.net.Uri import cc.aoeiuv020.anull.notNull import cc.aoeiuv020.gson.toBean import cc.aoeiuv020.gson.toJson import cc.aoeiuv020.panovel.App import cc.aoeiuv020.panovel.backup.BackupOption import cc.aoeiuv020.panovel.backup.BackupOption.* import cc.aoeiuv020.panovel.data.DataManager import cc.aoeiuv020.panovel.data.entity.NovelMinimal import cc.aoeiuv020.panovel.data.entity.NovelWithProgressAndPinnedTime import cc.aoeiuv020.panovel.settings.* import cc.aoeiuv020.panovel.share.Share import cc.aoeiuv020.panovel.util.Pref import cc.aoeiuv020.panovel.util.notNullOrReport import com.google.gson.JsonElement import org.jetbrains.anko.debug import java.io.File import java.util.* class BackupV4 : DefaultBackup() { override fun import(file: File, option: BackupOption): Int { debug { "import $option from $file" } return when (option) { Bookshelf -> importBookshelf(file) BookList -> importBookList(file) Progress -> importProgress(file) Settings -> importSettings(file) } } private fun importProgress(file: File): Int { return file.useLines { s -> s.map { line -> val a = line.split(',') NovelWithProgressAndPinnedTime( a[0], a[1], a[2], a[3], a[4].toInt(), a[5].toInt(), Date(a[6].toLong()) ) }.let { DataManager.importNovelWithProgress(it) } } } private fun importSettings(folder: File): Int { val list = folder.listFiles() return list.notNullOrReport().sumBy { file -> when (file.name) { "Ad" -> importPref(AdSettings, file) "General" -> importPref(GeneralSettings, file) "List" -> importPref(ListSettings, file) "Other" -> importPref(OtherSettings, file) "Reader" -> importPref(ReaderSettings, file) "Download" -> importPref(DownloadSettings, file) "Interface" -> importPref(InterfaceSettings, file) "Location" -> importPref(LocationSettings, file) "Server" -> importPref(ServerSettings, file) "Reader_BatteryMargins" -> importPref(ReaderSettings.batteryMargins, file) "Reader_BookNameMargins" -> importPref(ReaderSettings.bookNameMargins, file) "Reader_ChapterNameMargins" -> importPref(ReaderSettings.chapterNameMargins, file) "Reader_ContentMargins" -> importPref(ReaderSettings.contentMargins, file) "Reader_PaginationMargins" -> importPref(ReaderSettings.paginationMargins, file) "Reader_TimeMargins" -> importPref(ReaderSettings.timeMargins, file) "backgroundImage" -> 1.also { ReaderSettings.backgroundImage = Uri.fromFile(file) } "lastBackgroundImage" -> 1.also { ReaderSettings.lastBackgroundImage = Uri.fromFile(file) } "font" -> 1.also { ReaderSettings.font = Uri.fromFile(file) } else -> 0 } } } private fun importPref(pref: Pref, file: File): Int { val editor = pref.sharedPreferences.edit() var count = 0 file.readText().toBean<Map<String, JsonElement>>().forEach { (key, value) -> when (key) { // 枚举,保存字符串, "animationMode" -> editor.putString(key, value.asString) "shareExpiration" -> editor.putString(key, value.asString) "onCheckUpdateClick" -> editor.putString(key, value.asString) "onDotClick" -> editor.putString(key, value.asString) "onDotLongClick" -> editor.putString(key, value.asString) "onItemClick" -> editor.putString(key, value.asString) "onItemLongClick" -> editor.putString(key, value.asString) "onLastChapterClick" -> editor.putString(key, value.asString) "onNameClick" -> editor.putString(key, value.asString) "onNameLongClick" -> editor.putString(key, value.asString) "bookshelfOrderBy" -> editor.putString(key, value.asString) "adEnabled" -> editor.putBoolean(key, value.asBoolean) "keepScreenOn" -> editor.putBoolean(key, value.asBoolean) "fullScreen" -> editor.putBoolean(key, value.asBoolean) "backPressOutOfFullScreen" -> editor.putBoolean(key, value.asBoolean) "fullScreenClickNextPage" -> editor.putBoolean(key, value.asBoolean) "fitWidth" -> editor.putBoolean(key, value.asBoolean) "fitHeight" -> editor.putBoolean(key, value.asBoolean) "gridView" -> editor.putBoolean(key, value.asBoolean) "largeView" -> editor.putBoolean(key, value.asBoolean) "pinnedBackgroundColor" -> editor.putInt(key, value.asInt) "refreshOnSearch" -> editor.putBoolean(key, value.asBoolean) "reportCrash" -> editor.putBoolean(key, value.asBoolean) "qidianshuju" -> editor.putBoolean(key, value.asBoolean) "sp7" -> editor.putBoolean(key, value.asBoolean) "qidiantu" -> editor.putBoolean(key, value.asBoolean) "volumeKeyScroll" -> editor.putBoolean(key, value.asBoolean) "tabGravityCenter" -> editor.putBoolean(key, value.asBoolean) "animationSpeed" -> editor.putFloat(key, value.asFloat) "centerPercent" -> editor.putFloat(key, value.asFloat) "dotSize" -> editor.putFloat(key, value.asFloat) "autoSaveReadStatus" -> editor.putInt(key, value.asInt) "brightness" -> editor.putInt(key, value.asInt) "autoRefreshInterval" -> editor.putInt(key, value.asInt) "backgroundColor" -> editor.putInt(key, value.asInt) "lastBackgroundColor" -> editor.putInt(key, value.asInt) "chapterColorCached" -> editor.putInt(key, value.asInt) "chapterColorDefault" -> editor.putInt(key, value.asInt) "chapterColorReadAt" -> editor.putInt(key, value.asInt) "dotColor" -> editor.putInt(key, value.asInt) "searchThreadsLimit" -> editor.putInt(key, value.asInt) // 下载相关设置以前是在GeneralSettings里, // TODO: 可以干脆都改成这样, "downloadThreadsLimit" -> DownloadSettings.downloadThreadsLimit = value.asInt "downloadCount" -> DownloadSettings.downloadCount = value.asInt "autoDownloadCount" -> DownloadSettings.autoDownloadCount = value.asInt "fullScreenDelay" -> editor.putInt(key, value.asInt) "historyCount" -> editor.putInt(key, value.asInt) "lineSpacing" -> editor.putInt(key, value.asInt) "messageSize" -> editor.putInt(key, value.asInt) "paragraphSpacing" -> editor.putInt(key, value.asInt) "textColor" -> editor.putInt(key, value.asInt) "lastTextColor" -> editor.putInt(key, value.asInt) "textSize" -> editor.putInt(key, value.asInt) "dateFormat" -> editor.putString(key, value.asString) "segmentIndentation" -> editor.putString(key, value.asString) "enabled" -> editor.putBoolean(key, value.asBoolean) "serverAddress" -> editor.putString(key, value.asString) "notifyNovelUpdate" -> editor.putBoolean(key, value.asBoolean) "askUpdate" -> editor.putBoolean(key, value.asBoolean) "singleNotification" -> editor.putBoolean(key, value.asBoolean) "notifyPinnedOnly" -> editor.putBoolean(key, value.asBoolean) "dotNotifyUpdate" -> editor.putBoolean(key, value.asBoolean) "subscriptToast" -> editor.putBoolean(key, value.asBoolean) "bottom" -> editor.putInt(key, value.asInt) "left" -> editor.putInt(key, value.asInt) "right" -> editor.putInt(key, value.asInt) "top" -> editor.putInt(key, value.asInt) else -> --count } ++count } editor.apply() return count } private fun importBookList(folder: File): Int = folder.listFiles().notNullOrReport().sumBy { file -> val bookListBean = Share.importBookList(file.readText()) DataManager.importBookList( bookListBean.name, bookListBean.list, bookListBean.uuid ) bookListBean.list.size } private fun importBookshelf(file: File): Int { val list = file.readText().toBean<List<NovelMinimal>>() DataManager.importBookshelf(list) return list.size } override fun export(file: File, option: BackupOption): Int { debug { "export $option to $file" } return when (option) { Bookshelf -> exportBookshelf(file) BookList -> exportBookList(file) Progress -> exportProgress(file) Settings -> exportSettings(file) } } // 无头csv格式,其实就是逗号分隔, private fun exportProgress(file: File): Int { val list = DataManager.exportNovelProgress().map { NovelWithProgressAndPinnedTime(it) } var count = 0 file.outputStream().bufferedWriter().use { output -> list.forEach { n -> if (n.readAtChapterIndex > 0 || n.readAtTextIndex > 0) { output.appendln( listOf( n.site, n.author, n.name, n.detail, n.readAtChapterIndex, n.readAtTextIndex, n.pinnedTime.time ).joinToString(",") ) count++ } } } return count } // 书架只导出一个文件, private fun exportBookshelf(file: File): Int { val list = DataManager.listBookshelf().map { NovelMinimal(it.novel) } file.writeText(list.toJson()) return list.size } // 书单分多个文件导出,一个书单一个文件, private fun exportBookList(folder: File): Int { folder.mkdirs() return DataManager.allBookList().sumBy { bookList -> // 书单名允许重复,所以拼接上id, val fileName = "${bookList.id}|${bookList.name}" // 只取小说必须的几个参数,相关数据类不能被混淆, // 不包括本地小说, val novelList = DataManager.getNovelMinimalFromBookList(bookList.nId) folder.resolve(fileName).writeText(Share.exportBookList(bookList, novelList)) novelList.size } } // 设置分多个文件导出, private fun exportSettings(folder: File): Int { folder.mkdirs() @Suppress("RemoveExplicitTypeArguments") var count = listOf<Pref>( AdSettings, GeneralSettings, ListSettings, OtherSettings, ReaderSettings, DownloadSettings, InterfaceSettings, LocationSettings, ServerSettings, ReaderSettings.batteryMargins, ReaderSettings.bookNameMargins, ReaderSettings.chapterNameMargins, ReaderSettings.contentMargins, ReaderSettings.paginationMargins, ReaderSettings.timeMargins ).sumBy { pref -> // 直接从sp读map, 不受几个Settings混淆影响, pref.sharedPreferences.all.also { folder.resolve(pref.name).writeText(it.toJson()) }.size } // 导出背景图片, val backgroundImage = ReaderSettings.backgroundImage if (backgroundImage != null) { folder.resolve("backgroundImage").outputStream().use { output -> App.ctx.contentResolver.openInputStream(backgroundImage).notNull().use { input -> input.copyTo(output) } output.flush() } count++ } // 导出前一次设置的背景图片, val lastBackgroundImage = ReaderSettings.lastBackgroundImage if (lastBackgroundImage != null) { folder.resolve("lastBackgroundImage").outputStream().use { output -> App.ctx.contentResolver.openInputStream(lastBackgroundImage).notNull() .use { input -> input.copyTo(output) } output.flush() } count++ } // 导出字体, val font = ReaderSettings.font if (font != null) { folder.resolve("font").outputStream().use { output -> App.ctx.contentResolver.openInputStream(font).notNull().use { input -> input.copyTo(output) } output.flush() } count++ } return count } }
gpl-3.0
12743b2268c134ffcc2581885dfa0efa
43.717172
99
0.569202
4.641734
false
false
false
false
sandjelkovic/dispatchd
content-service/src/main/kotlin/com/sandjelkovic/dispatchd/content/data/entity/Show.kt
1
1123
package com.sandjelkovic.dispatchd.content.data.entity import java.time.ZonedDateTime import javax.persistence.* /** * @author sandjelkovic * @date 25.1.18. */ @Entity data class Show( @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long? = null, var title: String = "", @Lob var description: String = "", var year: Int? = null, var status: String = "", var lastLocalUpdate: ZonedDateTime = ZonedDateTime.now().minusYears(500), @Column(unique = true) var imdbId: String? = null, @Column(unique = true) var tmdbId: String? = null, @Column(unique = true) var traktId: String? = null, @Column(unique = true) var traktSlug: String? = null, @Column(unique = true) var tvdbId: String? = null, @OneToMany(mappedBy = "show") var episodes: List<Episode> = mutableListOf(), // JPA/Hibernate Specifics @OneToMany(mappedBy = "show") var seasons: List<Season> = mutableListOf(), // JPA/Hibernate Specifics @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "imagesId") var imagesGroup: ImagesGroup? = null )
apache-2.0
a3fbf3c687c54e834c378a5552725875
25.738095
77
0.652716
3.730897
false
false
false
false
arturbosch/detekt
detekt-psi-utils/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/KtLambdaExpression.kt
1
1513
package io.gitlab.arturbosch.detekt.rules import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall fun KtLambdaExpression.firstParameter(bindingContext: BindingContext) = bindingContext[BindingContext.FUNCTION, functionLiteral]?.valueParameters?.singleOrNull() fun KtLambdaExpression.implicitParameter(bindingContext: BindingContext): ValueParameterDescriptor? = if (valueParameters.isNotEmpty()) { null } else { firstParameter(bindingContext) } fun KtLambdaExpression.hasImplicitParameterReference( implicitParameter: ValueParameterDescriptor, bindingContext: BindingContext ): Boolean { return anyDescendantOfType<KtNameReferenceExpression> { it.isImplicitParameterReference(this, implicitParameter, bindingContext) } } private fun KtNameReferenceExpression.isImplicitParameterReference( lambda: KtLambdaExpression, implicitParameter: ValueParameterDescriptor, bindingContext: BindingContext ): Boolean { return text == "it" && getStrictParentOfType<KtLambdaExpression>() == lambda && getResolvedCall(bindingContext)?.resultingDescriptor == implicitParameter }
apache-2.0
1b4838f97fbc1c67792a20cad0ed0f2e
38.815789
101
0.808989
5.752852
false
false
false
false
arturbosch/detekt
detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/EqualsOnSignatureLine.kt
1
1819
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import org.jetbrains.kotlin.com.intellij.psi.PsiComment import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.siblings /** * Requires that the equals sign, when used for an expression style function, is on the same line as the * rest of the function signature. * * <noncompliant> * fun stuff(): Int * = 5 * * fun <V> foo(): Int where V : Int * = 5 * </noncompliant> * * <compliant> * fun stuff() = 5 * * fun stuff() = * foo.bar() * * fun <V> foo(): Int where V : Int = 5 * </compliant> */ class EqualsOnSignatureLine(config: Config = Config.empty) : Rule(config) { override val issue = Issue(javaClass.simpleName, Severity.Style, MESSAGE, Debt.FIVE_MINS) override fun visitNamedFunction(function: KtNamedFunction) { val equalsToken = function.equalsToken ?: return val hasLineBreakBeforeEqualsToken = equalsToken .siblings(forward = false, withItself = false) .takeWhile { it is PsiWhiteSpace || it is PsiComment } .any { it is PsiWhiteSpace && it.textContains('\n') } if (hasLineBreakBeforeEqualsToken) { report(CodeSmell(issue, Entity.from(equalsToken), MESSAGE)) } } private companion object { const val MESSAGE = "Equals signs for expression style functions should be on the same line as the signature" } }
apache-2.0
7407d29f3eb4b59cc028d533d95914fb
32.685185
117
0.706432
3.954348
false
true
false
false
Light-Team/ModPE-IDE-Source
editorkit/src/main/kotlin/com/brackeys/ui/editorkit/adapter/SuggestionAdapter.kt
1
3040
/* * Copyright 2021 Brackeys IDE contributors. * * 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.brackeys.ui.editorkit.adapter import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Filter import com.brackeys.ui.editorkit.model.ColorScheme import com.brackeys.ui.language.base.model.Suggestion import com.brackeys.ui.language.base.provider.SuggestionProvider abstract class SuggestionAdapter( context: Context, resourceId: Int ) : ArrayAdapter<Suggestion>(context, resourceId) { var colorScheme: ColorScheme? = null private var suggestionProvider: SuggestionProvider? = null private var queryText = "" abstract fun createViewHolder(parent: ViewGroup): SuggestionViewHolder override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val viewHolder = createViewHolder(parent) viewHolder.bind(getItem(position), queryText) return viewHolder.itemView } override fun getFilter(): Filter { return object : Filter() { private val suggestions: MutableList<Suggestion> = mutableListOf() override fun performFiltering(constraint: CharSequence?): FilterResults { val filterResults = FilterResults() suggestions.clear() suggestionProvider?.let { val query = constraint.toString() for (suggestion in it.getAll()) { val word = suggestion.text if (word.startsWith(query, ignoreCase = true) && !word.equals(query, ignoreCase = true)) { queryText = query suggestions.add(suggestion) } } } filterResults.values = suggestions filterResults.count = suggestions.size return filterResults } override fun publishResults(constraint: CharSequence?, results: FilterResults) { clear() addAll(suggestions) notifyDataSetChanged() } } } fun setSuggestionProvider(suggestionProvider: SuggestionProvider) { this.suggestionProvider = suggestionProvider } abstract class SuggestionViewHolder(val itemView: View) { abstract fun bind(suggestion: Suggestion?, query: String) } }
apache-2.0
e385f16435e01d80105b68749bb64b10
34.360465
92
0.646382
5.352113
false
false
false
false
cout970/Magneticraft
src/main/kotlin/com/cout970/magneticraft/registry/Recipes.kt
2
38110
package com.cout970.magneticraft.registry import com.cout970.magneticraft.api.MagneticraftApi import com.cout970.magneticraft.api.internal.registries.generators.thermopile.ThermopileRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.crushingtable.CrushingTableRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.gasificationunit.GasificationUnitRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.grinder.GrinderRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.hydraulicpress.HydraulicPressRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.oilheater.OilHeaterRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.refinery.RefineryRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.sieve.SieveRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.sluicebox.SluiceBoxRecipeManager import com.cout970.magneticraft.api.registries.machines.hydraulicpress.HydraulicPressMode import com.cout970.magneticraft.api.registries.machines.hydraulicpress.HydraulicPressMode.* import com.cout970.magneticraft.features.items.CraftingItems import com.cout970.magneticraft.features.items.EnumMetal import com.cout970.magneticraft.features.items.EnumMetal.* import com.cout970.magneticraft.features.items.MetallicItems import com.cout970.magneticraft.misc.* import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.inventory.stack import com.cout970.magneticraft.misc.inventory.toBlockState import com.cout970.magneticraft.misc.inventory.withSize import com.cout970.magneticraft.systems.integration.ItemHolder import com.cout970.magneticraft.systems.integration.crafttweaker.ifNonEmpty import net.minecraft.block.Block import net.minecraft.block.BlockSnow import net.minecraft.block.state.IBlockState import net.minecraft.init.Blocks import net.minecraft.init.Blocks.COBBLESTONE import net.minecraft.init.Items import net.minecraft.init.Items.GOLD_INGOT import net.minecraft.init.Items.IRON_INGOT import net.minecraft.item.ItemStack import net.minecraftforge.fluids.FluidRegistry import net.minecraftforge.fluids.FluidStack import net.minecraftforge.fml.common.registry.GameRegistry import com.cout970.magneticraft.features.decoration.Blocks as Decoration import com.cout970.magneticraft.features.decoration.Blocks as DecorationBlocks import com.cout970.magneticraft.features.ores.Blocks as OreBlocks import com.cout970.magneticraft.features.ores.Blocks as Ores import com.cout970.magneticraft.features.ores.Blocks.OreType as BlockOreType /** * Created by cout970 on 11/06/2016. * Modified by Yurgen * * Called by CommonProxy to register all the recipes in the mod */ fun registerRecipes() { //@formatter:off // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // GRINDER RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EnumMetal.values().forEach { metal -> metal.getOres().firstOrNull()?.let { addGrinderRecipe(it, metal.getRockyChunk(), Blocks.GRAVEL.stack(), 0.15f, 50f) } if (metal.subComponents.isEmpty()) { addGrinderRecipe(metal.getIngot(), metal.getDust(), ItemStack.EMPTY, 0.0f, 50f) } } ItemHolder.tinOre?.ifNonEmpty { addGrinderRecipe(it, TIN.getRockyChunk(), Blocks.GRAVEL.stack(), 0.15f, 50f) } ItemHolder.osmiumOre?.ifNonEmpty { addGrinderRecipe(it, OSMIUM.getRockyChunk(), Blocks.GRAVEL.stack(), 0.15f, 50f) } ItemHolder.dimensionalShard?.ifNonEmpty { shard -> ItemHolder.dimensionalShardOre0?.ifNonEmpty { ore -> addGrinderRecipe(ore, shard.withSize(4), shard.withSize(1), 0.5f, 50f) } ItemHolder.dimensionalShardOre1?.ifNonEmpty { ore -> addGrinderRecipe(ore, shard.withSize(4), shard.withSize(1), 0.5f, 50f) } ItemHolder.dimensionalShardOre2?.ifNonEmpty { ore -> addGrinderRecipe(ore, shard.withSize(4), shard.withSize(1), 0.5f, 50f) } } addGrinderRecipe(Blocks.REDSTONE_ORE.stack(), Items.REDSTONE.stack(4), Blocks.GRAVEL.stack(), 0.15f, 50f) addGrinderRecipe(Blocks.LAPIS_ORE.stack(), Items.DYE.stack(6, 4), Blocks.GRAVEL.stack(), 0.15f, 50f) addGrinderRecipe(Blocks.QUARTZ_ORE.stack(), Items.QUARTZ.stack(3), Items.QUARTZ.stack(1), 0.5f, 60f) addGrinderRecipe(Blocks.EMERALD_ORE.stack(), Items.EMERALD.stack(2), Blocks.GRAVEL.stack(), 0.15f, 50f) addGrinderRecipe(Blocks.DIAMOND_ORE.stack(), Items.DIAMOND.stack(1), Items.DIAMOND.stack(1), 0.75f, 50f) addGrinderRecipe(Blocks.COAL_ORE.stack(), Items.COAL.stack(1), Items.COAL.stack(1), 0.5f, 50f) addGrinderRecipe(Blocks.GLOWSTONE.stack(), Items.GLOWSTONE_DUST.stack(4), ItemStack.EMPTY, 0.0f, 40f) addGrinderRecipe(Blocks.SANDSTONE.stack(), Blocks.SAND.stack(4), ItemStack.EMPTY, 0.0f, 40f) addGrinderRecipe(Blocks.RED_SANDSTONE.stack(), Blocks.SAND.stack(4, 1), ItemStack.EMPTY, 0.0f, 40f) addGrinderRecipe(Items.BLAZE_ROD.stack(), Items.BLAZE_POWDER.stack(4), CraftingItems.Type.SULFUR.stack(1), 0.5f, 50f) addGrinderRecipe(Blocks.WOOL.stack(), Items.STRING.stack(4), ItemStack.EMPTY, 0.0f, 40f) addGrinderRecipe(Items.BONE.stack(), Items.DYE.stack(5, 15), Items.DYE.stack(3, 15), 0.5f, 40f) addGrinderRecipe(Items.REEDS.stack(), Items.SUGAR.stack(1), Items.SUGAR.stack(2), 0.5f, 40f) addGrinderRecipe(Blocks.COBBLESTONE.stack(), Blocks.GRAVEL.stack(1), Blocks.SAND.stack(1), 0.5f, 60f) addGrinderRecipe(Blocks.QUARTZ_BLOCK.stack(), Items.QUARTZ.stack(4), ItemStack.EMPTY, 0.0f, 50f) addGrinderRecipe(DecorationBlocks.limestone.stack(meta = 0), DecorationBlocks.limestone.stack(meta = 2), ItemStack.EMPTY, 0.0f, 20f) addGrinderRecipe(DecorationBlocks.burnLimestone.stack(meta = 0), DecorationBlocks.burnLimestone.stack(meta = 2), ItemStack.EMPTY, 0.0f, 20f) addGrinderRecipe(BlockOreType.PYRITE.stack(1), CraftingItems.Type.SULFUR.stack(4), EnumMetal.IRON.getDust(), 0.01f, 40f) ItemHolder.sawdust?.ifNonEmpty { sawdust -> addGrinderRecipe(Blocks.LOG.stack(), sawdust.withSize(8), sawdust.withSize(4), 0.5f, 100f) addGrinderRecipe(Blocks.PLANKS.stack(), sawdust.withSize(2), sawdust.withSize(1), 0.5f, 80f) } ItemHolder.pulverizedCoal?.ifNonEmpty { pulverizedCoal -> addGrinderRecipe(Blocks.COAL_ORE.stack(), pulverizedCoal.withSize(1), pulverizedCoal.withSize(1), 0.25f, 50f) addGrinderRecipe(Blocks.COAL_BLOCK.stack(), pulverizedCoal.withSize(9), pulverizedCoal.withSize(1), 0.15f, 120f) addGrinderRecipe(Items.COAL.stack(), pulverizedCoal.withSize(1), pulverizedCoal.withSize(1), 0.05f, 40f) } ItemHolder.pulverizedObsidian?.ifNonEmpty { pulverizedObsidian -> addGrinderRecipe(Blocks.OBSIDIAN.stack(), pulverizedObsidian.withSize(4), pulverizedObsidian.withSize(1), 0.25f, 80f) } ItemHolder.pulverizedCharcoal?.ifNonEmpty { pulverizedCharcoal -> addGrinderRecipe(Items.COAL.stack(meta = 1), pulverizedCharcoal.withSize(1), pulverizedCharcoal.withSize(1), 0.15f, 40f) } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // SIEVE RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EnumMetal.values().filter { it.isOre }.forEach { metal -> val subComponents = if (metal.isComposite) { metal.subComponents.map { it.invoke() }.map { it.getChunk() to 1f } } else { EnumMetal.subProducts[metal]?.map { it.getDust() to 0.15f } ?: emptyList() } when (subComponents.size) { 0 -> addSieveRecipe(metal.getRockyChunk(), metal.getChunk(), 1f, 50f) 1 -> addSieveRecipe(metal.getRockyChunk(), metal.getChunk(), 1f, subComponents[0].first, subComponents[0].second, 50f) 2 -> addSieveRecipe(metal.getRockyChunk(), metal.getChunk(), 1f, subComponents[0].first, subComponents[0].second, subComponents[1].first, subComponents[1].second, 50f) } } addSieveRecipe(Blocks.GRAVEL.stack(), Items.FLINT.stack(), 1f, Items.FLINT.stack(), 0.15f, Items.FLINT.stack(), 0.05f, 50f) addSieveRecipe(Blocks.SAND.stack(), Items.GOLD_NUGGET.stack(), 0.04f, Items.GOLD_NUGGET.stack(), 0.02f, Items.QUARTZ.stack(), 0.01f, 80f) addSieveRecipe(Blocks.SOUL_SAND.stack(), Items.QUARTZ.stack(), 0.15f, Items.QUARTZ.stack(), 0.1f, Items.QUARTZ.stack(), 0.05f, 80f) // addSieveRecipe(Blocks..stack(), Items.QUARTZ.stack(), 0.15f, Items.QUARTZ.stack(), 0.1f, Items.QUARTZ.stack(), 0.05f, 80f) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // CRUSHING TABLE RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // skulls addCrushingTableRecipe(Items.SKULL.stack(meta = 4), Items.GUNPOWDER.stack(8), true) // creeper addCrushingTableRecipe(Items.SKULL.stack(meta = 0), Items.DYE.stack(8, 15), true) // skeleton addCrushingTableRecipe(Items.SKULL.stack(meta = 2), Items.ROTTEN_FLESH.stack(4), true) // zombie // ores EnumMetal.values().forEach { metal -> metal.getOres().firstOrNull()?.let { addCrushingTableRecipe(it, metal.getRockyChunk()) } } ItemHolder.tinOre?.ifNonEmpty { addCrushingTableRecipe(it, TIN.getRockyChunk()) } ItemHolder.osmiumOre?.ifNonEmpty { addCrushingTableRecipe(it, OSMIUM.getRockyChunk()) } addCrushingTableRecipe(BlockOreType.PYRITE.stack(), CraftingItems.Type.SULFUR.stack(2)) // limestone addCrushingTableRecipe(Decoration.limestone.stack(), Decoration.limestone.stack(1, 2)) addCrushingTableRecipe(Decoration.burnLimestone.stack(), Decoration.burnLimestone.stack(1, 2)) // double plates addCrushingTableRecipe(Blocks.IRON_BLOCK.stack(), EnumMetal.IRON.getLightPlate().withSize(5), true) addCrushingTableRecipe(Blocks.GOLD_BLOCK.stack(), EnumMetal.GOLD.getLightPlate().withSize(5), true) addCrushingTableRecipe(OreBlocks.storageBlocks.stack(1, BlockOreType.COPPER.ordinal), EnumMetal.COPPER.getLightPlate().withSize(5)) addCrushingTableRecipe(OreBlocks.storageBlocks.stack(1, BlockOreType.LEAD.ordinal), EnumMetal.LEAD.getLightPlate().withSize(5)) addCrushingTableRecipe(OreBlocks.storageBlocks.stack(1, BlockOreType.TUNGSTEN.ordinal), EnumMetal.TUNGSTEN.getLightPlate().withSize(5)) addCrushingTableRecipe(EnumMetal.STEEL.getIngot(), EnumMetal.STEEL.getLightPlate()) // rods addCrushingTableRecipe(Items.BLAZE_ROD.stack(), Items.BLAZE_POWDER.stack(5)) addCrushingTableRecipe(Items.BONE.stack(), Items.DYE.stack(4, 15)) // blocks addCrushingTableRecipe(Blocks.STONE.stack(), Blocks.COBBLESTONE.stack()) addCrushingTableRecipe(Blocks.STONE.stack(1, 6), Blocks.STONE.stack(1, 5)) addCrushingTableRecipe(Blocks.STONE.stack(1, 4), Blocks.STONE.stack(1, 3)) addCrushingTableRecipe(Blocks.STONE.stack(1, 2), Blocks.STONE.stack(1, 1)) addCrushingTableRecipe(Blocks.STONEBRICK.stack(), Blocks.STONEBRICK.stack(1, 2)) addCrushingTableRecipe(Blocks.STONEBRICK.stack(1, 1), Blocks.MOSSY_COBBLESTONE.stack()) addCrushingTableRecipe(Blocks.PRISMARINE.stack(1, 1), Blocks.PRISMARINE.stack()) addCrushingTableRecipe(Blocks.END_BRICKS.stack(1), Blocks.END_STONE.stack(1)) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // SMELTING RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ addSmeltingRecipe(Decoration.burnLimestone.stack(1, 0), Decoration.limestone.stack(1, 0)) addSmeltingRecipe(Decoration.burnLimestone.stack(1, 2), Decoration.limestone.stack(1, 2)) //ores addSmeltingRecipe(MetallicItems.ingots.stack(1, 2), Ores.ores.stack(1, 0)) addSmeltingRecipe(MetallicItems.ingots.stack(1, 3), Ores.ores.stack(1, 1)) addSmeltingRecipe(MetallicItems.ingots.stack(1, 4), Ores.ores.stack(1, 2)) addSmeltingRecipe(MetallicItems.ingots.stack(1, 5), Ores.ores.stack(1, 3)) EnumMetal.values().forEach { if (it.isComposite) { addSmeltingRecipe(it.subComponents[0]().getIngot().withSize(2), it.getRockyChunk()) } else { addSmeltingRecipe(it.getIngot(), it.getDust()) if (it.isOre) { addSmeltingRecipe(it.getIngot(), it.getRockyChunk()) addSmeltingRecipe(it.getIngot().withSize(2), it.getChunk()) } } } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // SLUICE BOX RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EnumMetal.values() .filter { it.isOre } .forEach { metal -> val subComponents = if (metal.isComposite) { metal.subComponents.map { it.invoke() }.map { it.getChunk() to 1f } } else { EnumMetal.subProducts[metal]?.map { it.getDust() to 0.15f } ?: emptyList() } addSluiceBoxRecipe(metal.getRockyChunk(), metal.getChunk(), subComponents + listOf(COBBLESTONE.stack() to 0.15f)) } addSluiceBoxRecipe(Blocks.GRAVEL.stack(), Items.FLINT.stack(), listOf(Items.FLINT.stack() to 0.15f)) addSluiceBoxRecipe(Blocks.SAND.stack(), ItemStack.EMPTY, listOf( Items.GOLD_NUGGET.stack() to 0.01f, Items.GOLD_NUGGET.stack() to 0.005f, Items.GOLD_NUGGET.stack() to 0.0025f, Items.GOLD_NUGGET.stack() to 0.00125f, Items.GOLD_NUGGET.stack() to 0.000625f, Items.GOLD_NUGGET.stack() to 0.0003125f, Items.GOLD_NUGGET.stack() to 0.00015625f, Items.GOLD_NUGGET.stack() to 0.000078125f, Items.GOLD_NUGGET.stack() to 0.0000390625f )) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // THERMOPILE RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ addThermopileRecipe(Blocks.SNOW, WATER_FREEZING_POINT, 40.0) addThermopileRecipe(Blocks.ICE, WATER_FREEZING_POINT, 60.0) addThermopileRecipe(Blocks.PACKED_ICE, WATER_FREEZING_POINT, 80.0) addThermopileRecipe(Blocks.TORCH, FIRE_TEMP, 4.0) addThermopileRecipe(Blocks.LIT_PUMPKIN, FIRE_TEMP, 3.5) addThermopileRecipe(Blocks.FIRE, FIRE_TEMP, 4.5) addThermopileRecipe(Blocks.MAGMA, MAGMA_TEMP, 1.4) Blocks.SNOW_LAYER.blockState.validStates.forEach { state -> addThermopileRecipe(state, WATER_FREEZING_POINT, state[BlockSnow.LAYERS]!!.toDouble() / 15.0 * 40.0) } ItemHolder.uraniumBlock?.ifNonEmpty { it.toBlockState()?.let { state -> addThermopileRecipe(state, FIRE_TEMP, 1.5) } } FluidRegistry.getRegisteredFluids().values .filter { it.canBePlacedInWorld() } .forEach { fluid -> val temp = fluid.temperature.toDouble() addThermopileRecipe(fluid.block, temp, balancedConductivity(temp)) } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // HYDRAULIC PRESS RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //@formatter:on // Heavy recipes addHydraulicPressRecipe(IRON_INGOT.stack(4), IRON.getHeavyPlate(), HEAVY, 120f) addHydraulicPressRecipe(GOLD_INGOT.stack(4), GOLD.getHeavyPlate(), HEAVY, 50f) addHydraulicPressRecipe(EnumMetal.COPPER.getIngot().withSize(4), EnumMetal.COPPER.getHeavyPlate(), HEAVY, 100f) addHydraulicPressRecipe(EnumMetal.LEAD.getIngot().withSize(4), EnumMetal.LEAD.getHeavyPlate(), HEAVY, 50f) addHydraulicPressRecipe(EnumMetal.TUNGSTEN.getIngot().withSize(4), EnumMetal.TUNGSTEN.getHeavyPlate(), HEAVY, 250f) addHydraulicPressRecipe(EnumMetal.STEEL.getIngot().withSize(4), EnumMetal.STEEL.getHeavyPlate(), HEAVY, 140f) // Medium recipes addHydraulicPressRecipe(IRON_INGOT.stack(1), IRON.getLightPlate(), MEDIUM, 120f) addHydraulicPressRecipe(GOLD_INGOT.stack(1), GOLD.getLightPlate(), MEDIUM, 50f) addHydraulicPressRecipe(EnumMetal.COPPER.getIngot().withSize(1), EnumMetal.COPPER.getLightPlate(), MEDIUM, 100f) addHydraulicPressRecipe(EnumMetal.LEAD.getIngot().withSize(1), EnumMetal.LEAD.getLightPlate(), MEDIUM, 50f) addHydraulicPressRecipe(EnumMetal.TUNGSTEN.getIngot().withSize(1), EnumMetal.TUNGSTEN.getLightPlate(), MEDIUM, 250f) addHydraulicPressRecipe(EnumMetal.STEEL.getIngot().withSize(1), EnumMetal.STEEL.getLightPlate(), MEDIUM, 140f) // Light recipes listOf( IRON_INGOT.stack() to ItemHolder.ironPlate, GOLD_INGOT.stack() to ItemHolder.goldPlate, EnumMetal.COPPER.getIngot() to ItemHolder.copperPlate, EnumMetal.TIN.getIngot() to ItemHolder.tinPlate, EnumMetal.SILVER.getIngot() to ItemHolder.silverPlate, EnumMetal.LEAD.getIngot() to ItemHolder.leadPlate, EnumMetal.ALUMINIUM.getIngot() to ItemHolder.aluminiumPlate, EnumMetal.NICKEL.getIngot() to ItemHolder.nickelPlate, ItemHolder.platinumIngot to ItemHolder.platinumPlate, ItemHolder.iridiumIngot to ItemHolder.iridiumPlate, EnumMetal.MITHRIL.getIngot() to ItemHolder.mithilPlate, EnumMetal.STEEL.getIngot() to ItemHolder.steelPlate, ItemHolder.electrumIngot to ItemHolder.electrumPlate, ItemHolder.invarIngot to ItemHolder.invarPlate, ItemHolder.constantanIngot to ItemHolder.constantanPlate, ItemHolder.signalumIngot to ItemHolder.signalumPlate, ItemHolder.lumiumIngot to ItemHolder.lumiumPlate, ItemHolder.enderiumIngot to ItemHolder.enderiumPlate ).forEach { (a, b) -> a?.ifNonEmpty { b?.ifNonEmpty { addHydraulicPressRecipe(a, b, LIGHT, 80f) } } } // utility addHydraulicPressRecipe(Blocks.STONE.stack(), Blocks.COBBLESTONE.stack(), LIGHT, 55f) addHydraulicPressRecipe(Blocks.STONE.stack(meta = 6), Blocks.STONE.stack(meta = 5), LIGHT, 55f) addHydraulicPressRecipe(Blocks.STONE.stack(meta = 4), Blocks.STONE.stack(meta = 3), LIGHT, 55f) addHydraulicPressRecipe(Blocks.STONE.stack(meta = 2), Blocks.STONE.stack(meta = 1), LIGHT, 55f) addHydraulicPressRecipe(Blocks.STONEBRICK.stack(meta = 1), Blocks.MOSSY_COBBLESTONE.stack(), LIGHT, 55f) addHydraulicPressRecipe(Blocks.STONEBRICK.stack(), Blocks.STONEBRICK.stack(meta = 2), LIGHT, 55f) addHydraulicPressRecipe(Blocks.END_BRICKS.stack(), Blocks.END_STONE.stack(), LIGHT, 100f) addHydraulicPressRecipe(Blocks.RED_SANDSTONE.stack(meta = 2), Blocks.RED_SANDSTONE.stack(), LIGHT, 40f) addHydraulicPressRecipe(Blocks.SANDSTONE.stack(meta = 2), Blocks.SANDSTONE.stack(), LIGHT, 40f) addHydraulicPressRecipe(Blocks.PRISMARINE.stack(meta = 1), Blocks.PRISMARINE.stack(), LIGHT, 50f) addHydraulicPressRecipe(Blocks.ICE.stack(), Blocks.PACKED_ICE.stack(), LIGHT, 200f) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // OIL HEATER RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ addOilHeaterRecipe(FluidRegistry.getFluidStack("water", 1), FluidRegistry.getFluidStack("steam", 10), 1f, WATER_BOILING_POINT) addOilHeaterRecipe(FluidRegistry.getFluidStack("oil", 10), FluidRegistry.getFluidStack("hot_crude", 100), 2f, 350.fromCelsiusToKelvin()) addOilHeaterRecipe(FluidRegistry.getFluidStack("crude_oil", 10), FluidRegistry.getFluidStack("hot_crude", 100), 2f, 350.fromCelsiusToKelvin()) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // REFINERY RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ addRefineryRecipe(FluidRegistry.getFluidStack("steam", 10), FluidRegistry.getFluidStack("water", 1), null, null, 2f) addRefineryRecipe(FluidRegistry.getFluidStack("hot_crude", 100), FluidRegistry.getFluidStack("heavy_oil", 4), FluidRegistry.getFluidStack("light_oil", 3), FluidRegistry.getFluidStack("lpg", 3), 1f) addRefineryRecipe(FluidRegistry.getFluidStack("heavy_oil", 10), FluidRegistry.getFluidStack("oil_residue", 4), FluidRegistry.getFluidStack("fuel", 5), FluidRegistry.getFluidStack("lubricant", 1), 1f) addRefineryRecipe(FluidRegistry.getFluidStack("light_oil", 10), FluidRegistry.getFluidStack("diesel", 5), FluidRegistry.getFluidStack("kerosene", 2), FluidRegistry.getFluidStack("gasoline", 3), 1f) addRefineryRecipe(FluidRegistry.getFluidStack("lpg", 10), FluidRegistry.getFluidStack("plastic", 5), FluidRegistry.getFluidStack("naphtha", 2), FluidRegistry.getFluidStack("natural_gas", 3), 1f) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // GASIFIER RECIPES // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ addGasifierRecipe(Blocks.PLANKS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.LOG.stack(), Items.COAL.stack(meta = 1), fluidOf("wood_gas", 150), 30f, 300f) addGasifierRecipe(Blocks.LOG2.stack(), Items.COAL.stack(meta = 1), fluidOf("wood_gas", 150), 30f, 300f) addGasifierRecipe(Blocks.OAK_STAIRS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.ACACIA_STAIRS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.BIRCH_STAIRS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.JUNGLE_STAIRS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.SPRUCE_STAIRS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.DARK_OAK_STAIRS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Items.OAK_DOOR.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 20f, 250f) addGasifierRecipe(Items.ACACIA_DOOR.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 20f, 250f) addGasifierRecipe(Items.BIRCH_DOOR.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 20f, 250f) addGasifierRecipe(Items.JUNGLE_DOOR.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 20f, 250f) addGasifierRecipe(Items.SPRUCE_DOOR.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 20f, 250f) addGasifierRecipe(Items.DARK_OAK_DOOR.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 20f, 250f) addGasifierRecipe(Blocks.OAK_FENCE.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.ACACIA_FENCE.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.BIRCH_FENCE.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.JUNGLE_FENCE.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.SPRUCE_FENCE.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.DARK_OAK_FENCE.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 250f) addGasifierRecipe(Blocks.WOODEN_SLAB.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 15f, 200f) addGasifierRecipe(Blocks.WOODEN_PRESSURE_PLATE.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 15f, 200f) addGasifierRecipe(Blocks.TRAPDOOR.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 15f, 200f) addGasifierRecipe(Blocks.HAY_BLOCK.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 100), 15f, 250f) addGasifierRecipe(Blocks.SAPLING.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 180f) addGasifierRecipe(Blocks.LEAVES.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 180f) addGasifierRecipe(Blocks.LEAVES2.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 180f) addGasifierRecipe(Blocks.VINE.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 180f) addGasifierRecipe(Blocks.WATERLILY.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 180f) addGasifierRecipe(Blocks.RED_FLOWER.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 10f, 150f) addGasifierRecipe(Blocks.YELLOW_FLOWER.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 10f, 150f) addGasifierRecipe(Blocks.BROWN_MUSHROOM.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 10f, 150f) addGasifierRecipe(Blocks.RED_MUSHROOM.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 10f, 150f) addGasifierRecipe(Blocks.CACTUS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 10f, 180f) addGasifierRecipe(Blocks.DOUBLE_PLANT.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 10f, 150f) addGasifierRecipe(Blocks.CHEST.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 30f, 200f) addGasifierRecipe(Items.BOWL.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 15f, 150f) addGasifierRecipe(Items.SIGN.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 10f, 150f) addGasifierRecipe(Items.STICK.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 10), 10f, 150f) addGasifierRecipe(Items.WHEAT_SEEDS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 150f) addGasifierRecipe(Items.BEETROOT_SEEDS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 150f) addGasifierRecipe(Items.MELON_SEEDS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 150f) addGasifierRecipe(Items.PUMPKIN_SEEDS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 150f) addGasifierRecipe(Items.WHEAT.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 20f, 200f) addGasifierRecipe(Items.REEDS.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 30), 10f, 200f) addGasifierRecipe(Items.NETHER_WART.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 10f, 200f) addGasifierRecipe(Items.CARROT.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 10f, 200f) addGasifierRecipe(Items.POTATO.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 10f, 200f) addGasifierRecipe(Items.BEETROOT.stack(), ItemStack.EMPTY, fluidOf("wood_gas", 50), 10f, 200f) ItemHolder.coalCoke?.ifNonEmpty { addGasifierRecipe(Items.COAL.stack(), it, fluidOf("wood_gas", 15), 30f, 300f) } ItemHolder.sawdust?.ifNonEmpty { addGasifierRecipe(it, ItemStack.EMPTY, fluidOf("wood_gas", 10), 30f, 10f) } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // FLUID FUELS // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // For balance: 1 coal = 16_000 J // 1 oil bucket -> 18.75 coal items // unrefined addFluidFuel("oil", 10_000, 30.0) // 300_000 J/B = 18.75 coal items addFluidFuel("crude_oil", 10_000, 30.0) // 300_000 J/B = 18.75 coal items // 1 oil bucket -> 225 coal items // refined 1 time addFluidFuel("heavy_oil", 25_000, 60.0) // 1_500_000 J/B = 93.75 coal items addFluidFuel("light_oil", 25_000, 80.0) // 2_000_000 J/B = 125 coal items addFluidFuel("natural_gas", 2_500, 40.0) // 100_000 J/B = 6.25 coal items // 1 oil bucket -> 318.75 coal items // refined 2 times addFluidFuel("fuel", 25_000, 60.0) // 1_500_000 J/B = 93.75 coal items addFluidFuel("diesel", 10_000, 80.0) // 800_000 J/B = 62.5 coal items addFluidFuel("kerosene", 5_000, 120.0) // 600_000 J/B = 37.5 coal items addFluidFuel("gasoline", 12_000, 100.0) // 1_200_000 J/B = 62.5 coal items addFluidFuel("naphtha", 25_000, 40.0) // 1_000_000 J/B = 62.5 coal items // other fuels addFluidFuel("wood_gas", 2_500, 20.0) // 50_000 J/B = 3.125 coal items // IE addFluidFuel("creosote", 1_000, 20.0) // 20_000 J/B = 1.25 coal items addFluidFuel("ethanol", 2_000, 20.0) // 40_000 J/B = 2.5 coal items addFluidFuel("plantoil", 2_000, 20.0) // 40_000 J/B = 2.5 coal items addFluidFuel("biodiesel", 10_000, 50.0) // 500_000 J/B = 31.25 coal items // TE addFluidFuel("coal", 10_000, 40.0) // 400_000 J/B = 62.5 coal items addFluidFuel("tree_oil", 12_500, 80.0) // 1_000_000 J/B = 62.5 coal items addFluidFuel("refined_fuel", 25_000, 80.0) // 2_000_000 J/B = 125 coal items addFluidFuel("refined_oil", 25_000, 40.0) // 1_000_000 J/B = 62.5 coal items // IF addFluidFuel("biofuel", 10_000, 50.0) // 500_000 J/B = 31.25 coal items // Forestry addFluidFuel("bioethanol", 10_000, 50.0) // 500_000 J/B = 31.25 coal items } private fun fluidOf(name: String, amount: Int) = FluidRegistry.getFluidStack(name, amount) private fun addSmeltingRecipe(result: ItemStack, input: ItemStack) { if (input.isEmpty) throw IllegalStateException("Trying to register furnace recipe with empty input stack: $input") if (result.isEmpty) throw IllegalStateException("Trying to register furnace recipe with empty result empty stack: $result") GameRegistry.addSmelting(input, result, 0.1f) // i don't care about xp } private fun addCrushingTableRecipe(input: ItemStack, output: ItemStack, strict: Boolean = false) { CrushingTableRecipeManager.registerRecipe(CrushingTableRecipeManager.createRecipe(input, output, !strict)) } private fun addSluiceBoxRecipe(input: ItemStack, output: ItemStack, otherOutput: List<Pair<ItemStack, Float>> = emptyList()) { SluiceBoxRecipeManager.registerRecipe(SluiceBoxRecipeManager.createRecipe(input, (listOf(output to 1f) + otherOutput).toMutableList(), true)) } private fun addThermopileRecipe(input: IBlockState, temperature: Double, conductivity: Double) { ThermopileRecipeManager.registerRecipe( ThermopileRecipeManager.createRecipe(input, temperature.toFloat(), conductivity.toFloat()) ) } private fun addThermopileRecipe(input: Block, temperature: Double, conductivity: Double) { input.blockState.validStates.forEach { state -> ThermopileRecipeManager.registerRecipe( ThermopileRecipeManager.createRecipe(state, temperature.toFloat(), conductivity.toFloat()) ) } } private fun balancedConductivity(temp: Double): Double { if (temp < STANDARD_AMBIENT_TEMPERATURE) { return 2000.0 / ensureNonZero(STANDARD_AMBIENT_TEMPERATURE - temp) } return 1000.0 / ensureNonZero(temp - STANDARD_AMBIENT_TEMPERATURE) } private fun addSieveRecipe(input: ItemStack, output0: ItemStack, prob0: Float, output1: ItemStack, prob1: Float, output2: ItemStack, prob2: Float, duration: Float) { SieveRecipeManager.registerRecipe( SieveRecipeManager.createRecipe(input, output0, prob0, output1, prob1, output2, prob2, duration, true)) } private fun addSieveRecipe(input: ItemStack, output0: ItemStack, prob0: Float, output1: ItemStack, prob1: Float, duration: Float) { SieveRecipeManager.registerRecipe( SieveRecipeManager.createRecipe(input, output0, prob0, output1, prob1, output1, 0f, duration, true)) } private fun addSieveRecipe(input: ItemStack, output0: ItemStack, prob0: Float, duration: Float) { SieveRecipeManager.registerRecipe( SieveRecipeManager.createRecipe(input, output0, prob0, output0, 0f, output0, 0f, duration, true)) } private fun addGrinderRecipe(input: ItemStack, output0: ItemStack, output1: ItemStack, prob: Float, ticks: Float) { GrinderRecipeManager.registerRecipe(GrinderRecipeManager.createRecipe(input, output0, output1, prob, ticks, true)) } private fun addHydraulicPressRecipe(input: ItemStack, output: ItemStack, mode: HydraulicPressMode, ticks: Float) { HydraulicPressRecipeManager.registerRecipe(HydraulicPressRecipeManager.createRecipe(input, output, ticks, mode, true)) } private fun addOilHeaterRecipe(input: FluidStack?, output: FluidStack?, ticks: Float, minTemp: Double) { if (input == null || output == null) { warn("(Ignoring) Trying to register a OilHeaterRecipe with null params: input=$input, output=$output, duration=$ticks, minTemp=$minTemp") return } OilHeaterRecipeManager.registerRecipe(OilHeaterRecipeManager.createRecipe(input, output, ticks, minTemp.toFloat())) } private fun addRefineryRecipe(input: FluidStack?, output0: FluidStack?, output1: FluidStack?, output2: FluidStack?, ticks: Float) { if (input == null || (output0 == null && output1 == null && output2 == null)) { warn("Error trying to register a RefineryRecipe with params: input=$input, output0=$output0, " + "output1=$output1, output2=$output2, duration=$ticks") return } RefineryRecipeManager.registerRecipe(RefineryRecipeManager.createRecipe(input, output0, output1, output2, ticks)) } private fun addGasifierRecipe(input: ItemStack, output0: ItemStack, output1: FluidStack?, ticks: Float, minTemp: Float) { if (input.isEmpty) return GasificationUnitRecipeManager.registerRecipe( GasificationUnitRecipeManager.createRecipe(input, output0, output1, ticks, minTemp.fromCelsiusToKelvin().toFloat(), true) ) } private fun addFluidFuel(name: String, ticks: Int, value: Double) { val fluid = fluidOf(name, 1) if (fluid == null) { warn("(Ignoring) Unable to add a fuel for '$name': fluid not found") return } val manager = MagneticraftApi.getFluidFuelManager() manager.registerFuel(manager.createFuel(fluid, ticks, value)) } /* OLD RECIPES // // //ICEBOX RECIPES // addIceboxRecipeWater(ItemStack(Items.SNOWBALL), 125, false) // addIceboxRecipeWater(ItemStack(Blocks.SNOW), 500, false) // addIceboxRecipeWater(ItemStack(Blocks.ICE), 900, true) // addIceboxRecipeWater(ItemStack(Blocks.PACKED_ICE), 1000, false) // // //KILN RECIPES // addKilnRecipe(ItemStack(COAL_BLOCK), BlockCoke.defaultState, 50, COKE_REACTION_TEMP, CARBON_SUBLIMATION_POINT) // addKilnRecipe(ItemStack(Blocks.LOG, 1, 0), BlockCharcoalSlab.defaultState, 25, COKE_REACTION_TEMP, CARBON_SUBLIMATION_POINT) // addKilnRecipe(ItemStack(Blocks.SAND), Blocks.GLASS.defaultState, 25, GLASS_MAKING_TEMP, QUARTZ_MELTING_POINT) // addKilnRecipe(ItemStack(Blocks.CLAY), Blocks.HARDENED_CLAY.defaultState, 25, DEFAULT_SMELTING_TEMPERATURE, QUARTZ_MELTING_POINT) // addKilnRecipe(ItemStack(BlockFluxedGravel), BlockGlazedBrick.defaultState, 25, FURNACE_BRICK_TEMP, QUARTZ_MELTING_POINT) // addKilnRecipe(ItemStack(Blocks.SPONGE, 1, 1), ItemStack(Blocks.SPONGE, 1, 0), 25, WATER_BOILING_POINT, COKE_REACTION_TEMP) // // //KILN SHELF RECIPES // addKilnRecipe(ItemStack(COAL, 1, 0), ItemStack(ItemCoke), 50, COKE_REACTION_TEMP, CARBON_SUBLIMATION_POINT) // addKilnRecipe(ItemStack(CLAY_BALL), ItemStack(BRICK), 25, DEFAULT_SMELTING_TEMPERATURE, QUARTZ_MELTING_POINT) // addKilnRecipe(ItemStack(CHORUS_FRUIT), ItemStack(CHORUS_FRUIT_POPPED, 1, 0), 25, DEFAULT_SMELTING_TEMPERATURE, QUARTZ_MELTING_POINT) */ //private fun addKilnRecipe(input: ItemStack, output: ItemStack, duration: Int, minTemp: Double, maxTemp: Double) { // KilnRecipeManager.registerRecipe(KilnRecipeManager.createRecipe(input, output, duration, minTemp, maxTemp, true)) //} // //private fun addKilnRecipe(input: ItemStack, output: IBlockState, duration: Int, minTemp: Double, maxTemp: Double) { // KilnRecipeManager.registerRecipe(KilnRecipeManager.createRecipe(input, output, duration, minTemp, maxTemp, true)) //} // //private fun addIceboxRecipe(input: ItemStack, output: FluidStack, heat: Long, specificHeat: Double, minTemp: Double, // maxTemp: Double, reverse: Boolean) { // IceboxRecipeManager.registerRecipe( // IceboxRecipeManager.createRecipe(input, output, heat, specificHeat, minTemp, maxTemp, reverse)) //} // //private fun addIceboxRecipeWater(input: ItemStack, output: Int, reverse: Boolean) { // IceboxRecipeManager.registerRecipe(IceboxRecipeManager.createRecipe(input, FluidStack(FluidRegistry.WATER, output), // (WATER_HEAT_OF_FUSION * output / 1000).toLong(), WATER_HEAT_CAPACITY, WATER_MELTING_POINT, // WATER_BOILING_POINT, reverse)) //} //
gpl-2.0
a7e1525f535ac29b3552b61e234cde34
59.300633
146
0.647389
3.572701
false
false
false
false
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/SearchIndexMappingExtensions.kt
1
2507
package net.nemerosa.ontrack.model.structure import kotlin.reflect.KProperty1 @SearchIndexMappingMarker fun <T : SearchItem> indexMappings(code: SearchIndexMappingBuilder<T>.() -> Unit): SearchIndexMapping { val builder = SearchIndexMappingBuilder<T>() builder.code() return builder.createMapping() } @SearchIndexMappingMarker class SearchIndexMappingBuilder<T : SearchItem> { private val fields = mutableListOf<SearchIndexMappingFieldBuilder<T>>() operator fun KProperty1<T, Any>.unaryPlus(): SearchIndexMappingFieldBuilder<T> { val builder = SearchIndexMappingFieldBuilder(this) fields.add(builder) return builder } fun type(typeName: String, typeInit: SearchIndexMappingFieldTypeBuilder.() -> Unit = {}) = SearchIndexMappingFieldTypeBuilder(typeName).apply { typeInit() } fun id(typeInit: SearchIndexMappingFieldTypeBuilder.() -> Unit = {}) = type("long", typeInit) fun keyword(typeInit: SearchIndexMappingFieldTypeBuilder.() -> Unit = {}) = type("keyword", typeInit) fun nested(typeInit: SearchIndexMappingFieldTypeBuilder.() -> Unit = {}) = type("nested", typeInit) fun `object`(typeInit: SearchIndexMappingFieldTypeBuilder.() -> Unit = {}) = type("object", typeInit) fun timestamp(typeInit: SearchIndexMappingFieldTypeBuilder.() -> Unit = {}) = type("date", typeInit) fun text(typeInit: SearchIndexMappingFieldTypeBuilder.() -> Unit = {}) = type("text", typeInit) fun createMapping() = SearchIndexMapping( fields = fields.map { it.createField() } ) } @SearchIndexMappingMarker class SearchIndexMappingFieldBuilder<T : SearchItem>( private val property: KProperty1<T, Any> ) { private val types = mutableListOf<SearchIndexMappingFieldType>() infix fun to(typeBuilder: SearchIndexMappingFieldTypeBuilder): SearchIndexMappingFieldBuilder<T> { types.add(typeBuilder.createType()) return this } fun createField() = SearchIndexMappingField( name = property.name, types = types.toList() ) } @SearchIndexMappingMarker class SearchIndexMappingFieldTypeBuilder(private val typeName: String) { var index: Boolean? = null var scoreBoost: Double? = null fun createType(): SearchIndexMappingFieldType { return SearchIndexMappingFieldType( type = typeName, index = index, scoreBoost = scoreBoost ) } } @DslMarker annotation class SearchIndexMappingMarker
mit
62bbd60651902fd231ae0fc6a7359cd4
33.819444
160
0.704029
4.413732
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/ContextBar.kt
1
4350
package ch.bailu.aat_gtk.view import ch.bailu.aat_gtk.config.Layout import ch.bailu.aat_gtk.config.Strings import ch.bailu.aat_gtk.lib.extensions.appendText import ch.bailu.aat_gtk.lib.extensions.margin import ch.bailu.aat_gtk.lib.extensions.setLabel import ch.bailu.aat_gtk.lib.icons.IconMap import ch.bailu.aat_lib.dispatcher.OnContentUpdatedInterface import ch.bailu.aat_lib.gpx.GpxInformation import ch.bailu.aat_lib.gpx.InfoID import ch.bailu.aat_lib.gpx.StateID import ch.bailu.aat_lib.logger.AppLog import ch.bailu.aat_lib.preferences.StorageInterface import ch.bailu.aat_lib.resources.ToDo import ch.bailu.aat_lib.util.IndexedMap import ch.bailu.gtk.GTK import ch.bailu.gtk.gtk.* class ContextBar(contextCallback: UiController, private val storage: StorageInterface) : OnContentUpdatedInterface { val revealer = Revealer() private val combo = ComboBoxText() private val cache = IndexedMap<Int, GpxInformation>() private var trackerState = StateID.NOSERVICE private var selectInfoID = InfoID.TRACKER private val row1 = Box(Orientation.HORIZONTAL, 0).apply { append(createImageButton("zoom-fit-best-symbolic") { contextCallback.showInMap(selectedGpx()) } ) append(combo) margin(3) addCssClass(Strings.linked) } private val row2 = Box(Orientation.HORIZONTAL, 0).apply { addCssClass(Strings.linked) margin(3) } private val buttons = ArrayList<ToggleButton>().apply { add(createButton(ToDo.translate("Map")) { contextCallback.showMap() updateToggle() }) add(createButton(ToDo.translate("List")) { contextCallback.showInList() updateToggle() }) add(createButton(ToDo.translate("Detail")) { contextCallback.showDetail() updateToggle() }) add(createButton(ToDo.translate("Cockpit")) { contextCallback.showCockpit() updateToggle() }) forEach { row2.append(it) } } init { val layout = Box(Orientation.VERTICAL,0).apply { append(row1) append(row2) } revealer.child = layout revealer.revealChild = GTK.FALSE storage.register { _, key -> if (key == MainStackView.KEY) { updateToggle() } } updateToggle() } private fun updateCombo(index: Int = 0) { combo.removeAll() cache.forEach { _, value -> combo.appendText(value.file.name) } combo.active = index } private fun createButton(label: String, onClicked: Button.OnClicked) : ToggleButton { return ToggleButton().apply { setLabel(label) onClicked(onClicked) } } private fun createImageButton(resource: String, onClicked: Button.OnClicked) : Button { return Button().apply { onClicked(onClicked) child = IconMap.getImage(resource, Layout.iconSize) } } private fun selectedGpx(): GpxInformation { val info = cache.getValueAt(combo.active) if (info is GpxInformation) { return info } return GpxInformation.NULL } override fun onContentUpdated(iid: Int, info: GpxInformation) { val isInCache = cache.indexOfKey(iid) > -1 if (isInCache && iid == InfoID.TRACKER) { if (info.state != trackerState) { trackerState = info.state updateCacheAndCombo(iid, info, isInCache) } } else { updateCacheAndCombo(iid, info, isInCache) } } private fun updateCacheAndCombo(iid: Int, info: GpxInformation, isInCache: Boolean) { if (info.isLoaded && info.gpxList.pointList.size() > 0) { cache.put(iid, info) selectInfoID = iid updateCombo(cache.indexOfKey(selectInfoID)) } else if (isInCache) { cache.remove(iid) updateCombo(cache.indexOfKey(selectInfoID)) } } private fun updateToggle() { val index = storage.readInteger(MainStackView.KEY) AppLog.d(this, "update toggle $index") buttons.forEachIndexed { i, it -> it.active = GTK.IS(index == i) } } }
gpl-3.0
289db882c8453499acb5da838dadeb87
29.208333
116
0.616552
4.170662
false
false
false
false
johnguant/RedditThing
app/src/main/java/com/johnguant/redditthing/auth/RedditAuthActivity.kt
1
5758
package com.johnguant.redditthing.auth import android.accounts.Account import android.accounts.AccountAuthenticatorResponse import android.accounts.AccountManager import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import android.webkit.WebView import android.webkit.WebViewClient import com.johnguant.redditthing.R import com.johnguant.redditthing.redditapi.* import com.johnguant.redditthing.redditapi.model.OAuthToken import kotlinx.android.synthetic.main.activity_reddit_auth.* import okhttp3.OkHttpClient import org.jetbrains.anko.coroutines.experimental.bg import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.IOException class RedditAuthActivity : AppCompatActivity() { private var mAccountManager: AccountManager? = null private var mResultBundle: Bundle? = null private var mAccountAuthenticatorResponse: AccountAuthenticatorResponse? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_reddit_auth) setSupportActionBar(toolbar) mAccountAuthenticatorResponse = intent.getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE) if (mAccountAuthenticatorResponse != null) { mAccountAuthenticatorResponse!!.onRequestContinued() } mAccountManager = AccountManager.get(baseContext) login_webview.webViewClient = object : WebViewClient() { internal var authComplete = false internal var result = Intent() override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) if (url.contains("code=") && !authComplete) { authComplete = true bg { val time = System.currentTimeMillis() Log.d("redditThing", "response") val uri = Uri.parse(url) val authCode = uri.getQueryParameter("code") val oAuthToken = getAccessTokenFromCode(authCode) val username = getUsername(oAuthToken) val account = Account(username, getString(R.string.account_type)) mAccountManager!!.addAccountExplicitly(account, "", null) mAccountManager!!.setAuthToken(account, "accessToken", oAuthToken!!.accessToken) mAccountManager!!.setUserData(account, "refreshToken", oAuthToken.refresh_token) mAccountManager!!.setUserData(account, "expiryTime", (time + oAuthToken.expiresIn * 1000).toString()) val intent = Intent() intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username) intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, getString(R.string.account_type)) intent.putExtra(AccountManager.KEY_AUTHTOKEN, oAuthToken.accessToken) mResultBundle = result.extras finish() } } } } login_webview.loadUrl("https://www.reddit.com/api/v1/authorize.compact?client_id=3_XCTkayxEPJuA&response_type=code&state=testing&redirect_uri=com.johnguant.redditthing://oauth2redirect&duration=permanent&scope=read%20privatemessages%20report%20identity%20livemanage%20account%20edit%20history%20flair%20creddits%20subscribe%20vote%20mysubreddits%20submit%20save%20modcontributors%20modmail%20modconfig%20modlog%20modposts%20modflair%20modothers%20modtraffic%20modwiki%20modself") } fun getUsername(oAuthToken: OAuthToken?): String? { val baseUrl = "https://oauth.reddit.com/" val httpClient = OkHttpClient.Builder() .addInterceptor(HeaderInterceptor()) .addInterceptor(AuthInterceptor(oAuthToken!!.accessToken!!)) val builder = Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) builder.client(httpClient.build()) val retrofit = builder.build() val service = retrofit.create(RedditApiService::class.java) val call = service.me val account: com.johnguant.redditthing.redditapi.model.Account try { account = call.execute().body()!! } catch (e: IOException) { return null } return account.name } fun getAccessTokenFromCode(code: String): OAuthToken? { val service = ServiceGenerator.createService(AuthService::class.java, applicationContext) val call = service.accessToken("authorization_code", code, "com.johnguant.redditthing://oauth2redirect") val token: OAuthToken try { token = call.execute().body()!! } catch (e: IOException) { return null } return token } override fun finish() { if (mAccountAuthenticatorResponse != null) { if (mResultBundle != null) { mAccountAuthenticatorResponse!!.onResult(mResultBundle) } else { mAccountAuthenticatorResponse!!.onError(AccountManager.ERROR_CODE_CANCELED, "canceled") } mAccountAuthenticatorResponse = null } super.finish() } companion object { val ARG_ACCOUNT_TYPE = "com.johnguant.redditthing" val ARG_AUTH_TYPE = "AUTH_TYPE" val ARG_IS_ADDING_NEW_ACCOUNT = "IS_ADDING_ACCOUNT" } }
mit
e961b7f1b81b7d04fd9aab7dd8ab22d0
42.293233
487
0.652831
4.859072
false
false
false
false
ohmae/mmupnp
sample/src/main/java/net/mm2d/upnp/sample/MainWindow.kt
1
11234
/* * Copyright (c) 2016 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.sample import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import net.mm2d.upnp.Adapter.discoveryListener import net.mm2d.upnp.Adapter.eventListener import net.mm2d.upnp.Adapter.iconFilter import net.mm2d.upnp.ControlPoint import net.mm2d.upnp.ControlPointFactory import net.mm2d.upnp.Protocol import net.mm2d.upnp.log.DefaultSender import net.mm2d.upnp.log.Logger import java.awt.BorderLayout import java.awt.Color import java.awt.Component import java.awt.FlowLayout import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.io.File import java.io.FileOutputStream import java.text.SimpleDateFormat import java.util.* import javax.swing.BoxLayout import javax.swing.Icon import javax.swing.ImageIcon import javax.swing.JButton import javax.swing.JCheckBox import javax.swing.JDialog import javax.swing.JFileChooser import javax.swing.JFrame import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.JSplitPane import javax.swing.JTextArea import javax.swing.JTree import javax.swing.SwingUtilities import javax.swing.UIManager import javax.swing.WindowConstants import javax.swing.tree.DefaultTreeCellRenderer import javax.swing.tree.DefaultTreeModel import javax.swing.tree.TreeSelectionModel class MainWindow private constructor() : JFrame() { private val controlPoint: ControlPoint private val rootNode: UpnpNode = UpnpNode("Device").also { it.allowsChildren = true } private val tree: JTree = JTree(rootNode, true).also { it.selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION it.cellRenderer = MyTreeCellRenderer() } private val detail1: JTextArea = makeTextArea() private val detail2: JTextArea = makeTextArea() private val eventArea: JTextArea = makeTextArea() init { controlPoint = ControlPointFactory.create(protocol = Protocol.DUAL_STACK).also { it.setIconFilter(iconFilter { list -> list }) it.initialize() } title = "UPnP" setSize(800, 800) setLocationRelativeTo(null) defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeControlPanel(), BorderLayout.NORTH) val detail = JSplitPane(JSplitPane.VERTICAL_SPLIT, JScrollPane(detail1), JScrollPane(detail2)).also { it.dividerLocation = 250 } val main = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, JScrollPane(tree), detail).also { it.dividerLocation = 300 } val content = JSplitPane(JSplitPane.VERTICAL_SPLIT, main, JScrollPane(eventArea)).also { it.dividerLocation = 600 } contentPane.add(content, BorderLayout.CENTER) isVisible = true setUpControlPoint() setUpTree() } private fun setUpControlPoint() { controlPoint.addDiscoveryListener(discoveryListener({ update() }, { update() })) controlPoint.addEventListener(eventListener { service, seq, properties -> properties.forEach { eventArea.text = "${eventArea.text}${service.serviceType} : $seq : ${it.first} : ${it.second}\n" } }) } private fun update() { rootNode.removeAllChildren() controlPoint.deviceList.forEach { rootNode.add(DeviceNode(it)) } val model = tree.model as DefaultTreeModel model.reload() } private fun setUpTree() { tree.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (!SwingUtilities.isRightMouseButton(e)) { return } val x = e.x val y = e.y val row = tree.getRowForLocation(x, y) if (row < 0) { return } tree.setSelectionRow(row) val node = tree.lastSelectedPathComponent as? UpnpNode ?: return node.showContextMenu(this@MainWindow, tree, x, y) } }) tree.addTreeSelectionListener { val node = tree.lastSelectedPathComponent as? UpnpNode ?: return@addTreeSelectionListener detail1.text = node.formatDescription() detail2.text = node.getDetailXml() } } private fun makeStartButton(): JButton = JButton("START").also { it.addActionListener { controlPoint.start() controlPoint.search() } } private fun makeStopButton(): JButton = JButton("STOP").also { it.addActionListener { controlPoint.stop() } } private fun makeClearButton(): JButton = JButton("CLEAR").also { it.addActionListener { controlPoint.clearDeviceList() } } private fun makeSearchButton(): JButton = JButton("M-SEARCH").also { it.addActionListener { controlPoint.search() } } private fun makeDumpButton(): JButton = JButton("Device Dump").also { it.addActionListener { dump() } } private fun makeLogLevelDialog(): JButton = JButton("Log").also { it.addActionListener { val dialog = JDialog() val panel = JPanel() panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS) for (i in Logger.VERBOSE..Logger.ERROR) { val label = when (i) { Logger.VERBOSE -> "VERBOSE" Logger.DEBUG -> "DEBUG" Logger.INFO -> "INFO" Logger.WARN -> "WARN" Logger.ERROR -> "ERROR" else -> "" } panel.add(JCheckBox(label).also { checkBox -> checkBox.isSelected = enabledLogLevel[i] checkBox.addChangeListener { enabledLogLevel[i] = checkBox.isSelected } }) } dialog.add(panel) dialog.pack() dialog.setLocationRelativeTo(null) dialog.isModal = true dialog.isVisible = true } } private fun selectSaveDirectory(): File? { val chooser = JFileChooser().also { it.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY it.dialogTitle = "select directory" } val selected = chooser.showSaveDialog(this) return if (selected == JFileChooser.APPROVE_OPTION) { chooser.selectedFile } else null } private fun dump() { val dir = selectSaveDirectory() ?: return val json = controlPoint.deviceList .map { Server(it.location, it.friendlyName) } .let { Json.encodeToString(it) } FileOutputStream(File(dir, "locations.json")).use { it.write(json.toByteArray()) } } @Serializable private data class Server( val location: String, val friendlyName: String ) private fun makeControlPanel(): JPanel = JPanel().also { it.layout = FlowLayout() it.add(makeStartButton()) it.add(makeStopButton()) it.add(makeClearButton()) it.add(makeSearchButton()) it.add(makeDumpButton()) it.add(makeLogLevelDialog()) } private fun makeTextArea(): JTextArea = JTextArea().also { it.tabSize = 2 it.isEditable = false } private class MyTreeCellRenderer : DefaultTreeCellRenderer() { private val rootIcon: Icon private val deviceIcon: Icon private val serviceIcon: Icon private val variableListIcon: Icon private val variableIcon: Icon private val argumentIcon: Icon private val actionIcon: Icon init { val classLoader = MyTreeCellRenderer::class.java.classLoader rootIcon = ImageIcon(classLoader.getResource("root.png")) deviceIcon = ImageIcon(classLoader.getResource("device.png")) serviceIcon = ImageIcon(classLoader.getResource("service.png")) variableListIcon = ImageIcon(classLoader.getResource("folder.png")) variableIcon = ImageIcon(classLoader.getResource("variable.png")) argumentIcon = ImageIcon(classLoader.getResource("variable.png")) actionIcon = ImageIcon(classLoader.getResource("action.png")) } override fun getTreeCellRendererComponent( tree: JTree, value: Any, sel: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean ): Component { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus) when (value) { is DeviceNode -> icon = deviceIcon is ServiceNode -> { icon = serviceIcon if (value.isSubscribing) { foreground = Color.BLUE } } is StateVariableListNode -> icon = variableListIcon is StateVariableNode -> icon = variableIcon is ArgumentNode -> icon = argumentIcon is ActionNode -> icon = actionIcon else -> icon = rootIcon } return this } } companion object { private const val DMS_PREFIX = "urn:schemas-upnp-org:device:MediaServer" private const val DMR_PREFIX = "urn:schemas-upnp-org:device:MediaRenderer" private val enabledLogLevel = Array(7) { true } private val FORMAT = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US) @JvmStatic fun main(args: Array<String>) { setUpLogger() UIManager.getInstalledLookAndFeels() .find { it.className.contains("Nimbus") } ?.let { UIManager.setLookAndFeel(it.className) } MainWindow() } private fun setUpLogger() { Logger.setLogLevel(Logger.VERBOSE) Logger.setSender(DefaultSender.create { level, tag, message -> if (!enabledLogLevel[level]) return@create GlobalScope.launch(Dispatchers.Main) { val prefix = "$dateString ${level.toLogLevelString()} [$tag] " message.split("\n") .let { if (message.endsWith("\n")) it.dropLast(1) else it } .forEach { println(prefix + it) } } }) } private val dateString: String get() = FORMAT.format(Date(System.currentTimeMillis())) private fun Int.toLogLevelString(): String = when (this) { Logger.VERBOSE -> "V" Logger.DEBUG -> "D" Logger.INFO -> "I" Logger.WARN -> "W" Logger.ERROR -> "E" else -> " " } } }
mit
8109f8214153ee5e1688b988c1f7d69e
34.301887
112
0.604222
4.809769
false
false
false
false
HedvigInsurance/bot-service
src/main/java/com/hedvig/botService/chat/Conversation.kt
1
12945
package com.hedvig.botService.chat import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import com.hedvig.botService.dataTypes.HedvigDataType import com.hedvig.botService.dataTypes.TextInput import com.hedvig.botService.enteties.UserContext import com.hedvig.botService.enteties.message.* import com.hedvig.botService.services.events.MessageSentEvent import com.hedvig.botService.utils.MessageUtil import com.hedvig.libs.translations.Translations import org.slf4j.LoggerFactory import org.springframework.context.ApplicationEventPublisher import org.springframework.security.jwt.JwtHelper import org.springframework.stereotype.Component import java.io.IOException import java.lang.Long.valueOf import java.util.* typealias SelectItemMessageCallback = (MessageBodySingleSelect, UserContext) -> String typealias GenericMessageCallback = (Message, UserContext) -> String typealias AddMessageCallback = (UserContext) -> Unit @Component abstract class Conversation( open var eventPublisher: ApplicationEventPublisher, val translations: Translations, userContext: UserContext ) { private val callbacks = TreeMap<String, SelectItemMessageCallback>() val genericCallbacks = TreeMap<String, GenericMessageCallback>() val addMessageCallbacks = TreeMap<String, AddMessageCallback>() private val messageList = TreeMap<String, Message>() private val relayList = TreeMap<String, String>() open val userContext: UserContext = userContext enum class conversationStatus { INITIATED, ONGOING, COMPLETE } enum class EventTypes { MESSAGE_FETCHED } fun getMessage(key: String): Message? { val m = messageList[key] if (m == null) { // These happen literally all the time, and I (Fredrik TB) made an attempt at // making them disappear by calling addMessage(Message) from createBackOfficeMessage(...) // which should end up here. But I think what differs that code path (createBackOfficeMessage) // is that all/most the other ones that end up in `messageList` are added in constructors of // subclasses of Conversation (see subclass CallMeConversation for instance), // whereas createBackOfficeMessage is called from some endpoint. Therefore it probably is not automatically // present in the messageList. But I don't really know how all of this fits together. // // But since this happens aaaall the time, it cannot possible be a real error. I guess someone // who knows more about how bot-service works should look into actually handling these in a way // that makes more sense. if (key == "free.chat.from.bo" || key == "message.main.start.free.text.chat") { log.info("Message not found with id: $key") } else { log.error("Message not found with id: $key") } } return m } fun addMessage(message: Message) { messageList[message.id] = message } protected fun addRelayToChatMessage(s1: String, s2: String) { val i = findLastChatMessageId(s1) relayList[i] = s2 } protected fun addRelay(s1: String, s2: String) { relayList[s1] = s2 } fun findLastChatMessageId(messageId: String): String { var i = 0 while (messageList.containsKey(String.format(CHAT_ID_FORMAT, messageId, i))) { i++ if (i == 100) { val format = String.format("Found 100 ChatMessages messages for %s, this seems strange", messageId) throw RuntimeException(format) } } return if (i > 0) { String.format(CHAT_ID_FORMAT, messageId, i - 1) } else messageId } protected fun getRelay(s1: String): String? { return relayList[s1] } fun addToChat(messageId: String) { addToChat(getMessage(messageId)) } abstract fun getSelectItemsForAnswer(): List<SelectItem> abstract fun canAcceptAnswerToQuestion(): Boolean public open fun addToChat(m: Message?) { m!!.render(userContext, translations) log.info("Putting message: " + m.id + " content: " + m.body.text) userContext.addToHistory(m) addMessageCallbacks[m.id]?.invoke(userContext) eventPublisher.publishEvent(MessageSentEvent(userContext.memberId, m)) } fun createMessage(id:String, header: MessageHeader, body: MessageBody){ this.createMessage(id, header,body, null) } fun createMessage(id:String, body: MessageBody){ this.createMessage(id, body = body, avatarName = null) } fun createMessage(id:String, body:MessageBody, delay: Int){ this.createMessage(id, body = body, avatarName = null, delay = delay) } fun createMessage( id: String, header: MessageHeader = MessageHeader(MessageHeader.HEDVIG_USER_ID, -1), body: MessageBody, avatarName: String? = null, delay: Int? = null) { val m = Message() m.id = id m.header = header m.body = body if (delay != null) { m.header.pollingInterval = valueOf(delay.toLong()) } if(avatarName != null){ m.header.avatarName = avatarName } messageList[m.id] = m } internal fun hasSelectItemCallback(messageId: String): Boolean { return this.callbacks.containsKey(messageId) } internal fun execSelectItemCallback(messageId: String, message: MessageBodySingleSelect): String { return this.callbacks[messageId]!!.invoke(message, userContext) } protected fun startConversation(startId: String) { log.info("Starting conversation with message: $startId") addToChat(messageList[startId]) } fun setExpectedReturnType(messageId: String, type: HedvigDataType) { if (getMessage(messageId) != null) { log.debug( "Setting the expected return typ for message: " + messageId + " to " + type.javaClass.name) getMessage(findLastChatMessageId(messageId))!!.expectedType = type } else { log.error("ERROR: ------------> Message not found: $messageId") } } // If the message has a preferred return type it is validated otherwise not fun validateReturnType(m: Message): Boolean { val mCorr = getMessage(MessageUtil.removeNotValidFromId(m.id)) if (mCorr != null) { var ok = true // All text input are validated to prevent null pointer exceptions if (mCorr.body.javaClass == MessageBodyText::class.java) { val t = TextInput() ok = t.validate(m.body.text) if (!ok) mCorr.body.text = t.getErrorMessage() } // Input with explicit validation if (mCorr.expectedType != null) { ok = mCorr.expectedType.validate(m.body.text) if (!ok) { mCorr.id += NOT_VALID_POST_FIX val localizedErrorMessage = translations.get(mCorr.expectedType.errorMessageId, userContext.locale) ?: mCorr.expectedType.getErrorMessage() mCorr.body.text = localizedErrorMessage.replace("{INPUT}", m.body.text) m.id = mCorr.expectedType.errorMessageId + ".input" + NOT_VALID_POST_FIX } } if (m.body.text == null) { m.body.text = "" } if (!ok) { addToChat(m) addToChat(mCorr) } return ok } return true } // ------------------------------------------------------------------------------- // fun receiveMessage(m: Message) { var nxtMsg:String? = null if(validateReturnType(m)) { //Generic Lambda if (this.hasGenericCallback(m.strippedBaseMessageId)) { nxtMsg = this.execGenericCallback(m) } if (nxtMsg != null) { this.completeRequest(nxtMsg) } else { handleMessage(m) } } } abstract fun handleMessage(m: Message) protected open fun completeRequest(nxtMsg: String) { if (getMessage(nxtMsg) != null) { addToChat(getMessage(nxtMsg)) } } open fun receiveEvent(e: EventTypes, value: String) {} abstract fun init() abstract fun init(startMessage: String) // ----------------------------------------------------------------------------------------------------------------- // final inline fun <reified T:MessageBody>createChatMessage(id:String, message:WrappedMessage<T>){ this.createChatMessage(id, avatar = null, body = message.message) this.genericCallbacks[id] = {m,u -> message.receiveMessageCallback(m.body as T, u, m)} if(message.addMessageCallback != null) { this.addMessageCallbacks[id] = message.addMessageCallback } } fun createChatMessage(id: String, body: MessageBody) { this.createChatMessage(id, body, null) } /* * Splits the message text into separate messages based on \f and adds 'Hedvig is thinking' messages in between * */ fun createChatMessage(id: String, body: MessageBody, avatar: String?) { val text = translations.get(id, userContext.locale) ?: body.text val paragraphs = text.split("\u000C".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() var pId = 0 val msgs = ArrayList<String>() for (i in 0 until paragraphs.size - 1) { val s = paragraphs[i] val s1 = if (i == 0) id else String.format(CHAT_ID_FORMAT, id, pId++) val s2 = String.format(CHAT_ID_FORMAT, id, pId++) createMessage(s2, body = MessageBodyParagraph(s)) // if(i==0){ // createMessage(s1, new MessageBodyParagraph(""),"h_symbol",(s.length()*delayFactor)); // }else{ createMessage(s1, body = MessageBodyParagraph(""), delay = minOf(s.length * MESSAGE_DELAY_FACTOR_MS, MESSAGE_MAX_DELAY_MS)) // } msgs.add(s1) msgs.add(s2) } // The 'actual' message val sWrite = if (pId == 0) id else String.format(CHAT_ID_FORMAT, id, pId++) val sFinal = String.format(CHAT_ID_FORMAT, id, pId++) val s = paragraphs[paragraphs.size - 1] // Last paragraph is put on actual message body.text = s // createMessage(sWrite, new MessageBodyParagraph(""), "h_symbol",(s.length()*delayFactor)); createMessage(sWrite, body = MessageBodyParagraph(""), delay = minOf(s.length * MESSAGE_DELAY_FACTOR_MS, MESSAGE_MAX_DELAY_MS)) if (avatar != null) { createMessage(sFinal, body = body, avatarName = avatar) } else { createMessage(sFinal, body = body) } msgs.add(sWrite) msgs.add(sFinal) // Connect all messages in relay chain for (i in 0 until msgs.size - 1) addRelay(msgs[i], msgs[i + 1]) } @JvmOverloads fun addMessageFromBackOffice(message: String, messageId: String, userId: String? = null): Boolean { if (!this.canAcceptAnswerToQuestion()) { return false } val msg = createBackOfficeMessage(message, messageId) msg.author = getUserId(userId) userContext.memberChat.addToHistory(msg) if (eventPublisher != null) { eventPublisher.publishEvent(MessageSentEvent(userContext.memberId, msg)) } return true } open fun createBackOfficeMessage(message: String, id: String): Message { val msg = Message() val selectionItems = getSelectItemsForAnswer() msg.body = MessageBodySingleSelect(message, selectionItems) msg.globalId = null msg.header = MessageHeader.createRichTextHeader() msg.header.messageId = null msg.body.id = null msg.id = id addMessage(msg) return msg } private fun getUserId(token: String?): String? { return try { val map = ObjectMapper().readValue<Map<String, String>>(JwtHelper.decode(token!!).claims, object : TypeReference<Map<String, String>>() { }) map["email"] } catch (e: IOException) { log.error(e.message) "" } catch (e: RuntimeException) { log.error(e.message) "" } } fun hasGenericCallback(id: String): Boolean { return genericCallbacks.containsKey(id) } fun execGenericCallback(m: Message): String { return this.genericCallbacks[m.strippedBaseMessageId]!!.invoke(m, userContext) } fun hasMessage(id: String) = messageList[id] != null fun handleSingleSelect(m: Message, nxtMsg: String, exceptions: List<String> = emptyList()): String { var nxtMsgOut = nxtMsg /* * In a Single select, there is only one trigger event. Set default here to be a link to a new message */ if (nxtMsg == "" && m.body is MessageBodySingleSelect) { for (o in (m.body as MessageBodySingleSelect).choices) { if (o.selected) { if (!hasMessage(o.value) && !exceptions.contains(o.value)) { resetConversation() } else { m.body.text = o.text addToChat(m) nxtMsgOut = o.value } } } } return nxtMsgOut } fun resetConversation() { startConversation(FreeChatConversation.FREE_CHAT_START) } companion object { private val CHAT_ID_FORMAT = "%s.%s" const val NOT_VALID_POST_FIX = ".not.valid" private val MESSAGE_DELAY_FACTOR_MS = 15 private val MESSAGE_MAX_DELAY_MS = 1000 private val log = LoggerFactory.getLogger(Conversation::class.java) } }
agpl-3.0
20d034de2e34eccbb1046845e145d6fb
30.343826
143
0.661414
4.084885
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/animate/AnimateLibrary.kt
1
11910
@file:OptIn(KorgeInternal::class) package com.soywiz.korge.animate import com.soywiz.kds.* import com.soywiz.kds.iterators.* import com.soywiz.klock.* import com.soywiz.korau.sound.* import com.soywiz.korge.animate.serialization.* import com.soywiz.korge.html.* import com.soywiz.korge.internal.* import com.soywiz.korge.render.* import com.soywiz.korge.view.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korim.format.* import com.soywiz.korio.lang.* import com.soywiz.korio.util.* import com.soywiz.korma.geom.* import com.soywiz.korma.geom.vector.* import com.soywiz.korma.interpolation.* import kotlin.collections.set import kotlin.coroutines.* open class AnSymbol( val id: Int = -1, var name: String? = null ) : Extra by Extra.Mixin() { open fun create(library: AnLibrary): AnElement = AnEmptyView(library) override fun toString(): String = "Symbol(id=$id, name=$name)" } object AnSymbolEmpty : AnSymbol(-1, "") class AnSymbolButton(id: Int, name: String?) : AnSymbol(id, name) { } class AnSymbolVideo(id: Int, name: String?) : AnSymbol(id, name) { } class AnSymbolSound(id: Int, name: String?, private var inputSound: Sound?, val dataBytes: ByteArray?) : AnSymbol(id, name) { private val nativeSoundCache = AsyncOnce<Sound>() suspend fun getNativeSound(): Sound = nativeSoundCache { if (inputSound == null) { inputSound = try { nativeSoundProvider.createSound(dataBytes ?: byteArrayOf()) } catch (e: Throwable) { nativeSoundProvider.createSound(AudioData.DUMMY) } } inputSound!! } } class AnTextFieldSymbol(id: Int, name: String?, val initialHtml: String, val bounds: Rectangle) : AnSymbol(id, name) { override fun create(library: AnLibrary): AnElement = AnTextField(library, this) } open class AnSymbolBaseShape(id: Int, name: String?, var bounds: Rectangle, val path: VectorPath? = null) : AnSymbol(id, name) { } class AnSymbolShape( id: Int, name: String?, bounds: Rectangle, var textureWithBitmap: TextureWithBitmapSlice?, path: VectorPath? = null ) : AnSymbolBaseShape(id, name, bounds, path) { override fun create(library: AnLibrary): AnElement = AnShape(library, this) } class AnSymbolMorphShape( id: Int, name: String?, bounds: Rectangle, var texturesWithBitmap: Timed<TextureWithBitmapSlice> = Timed(), path: VectorPath? = null ) : AnSymbolBaseShape(id, name, bounds, path) { override fun create(library: AnLibrary): AnElement = AnMorphShape(library, this) } class AnSymbolBitmap(id: Int, name: String?, val bmp: Bitmap) : AnSymbol(id, name) { //override fun create(library: AnLibrary): AnElement = AnShape(library, this) } class AnConstantPool( val stringPool: Array<String> ) // @TODO: Matrix and ColorTransform pools? Maybe smaller size, reusability and possibility of compute values fast data class AnSymbolTimelineFrame( var depth: Int = -1, var uid: Int = -1, var clipDepth: Int = -1, var ratio: Double = 0.0, var transform: Matrix = Matrix(), var name: String? = null, var colorTransform: ColorTransform = ColorTransform(), var blendMode: BlendMode = BlendMode.INHERIT ) { fun setToInterpolated(l: AnSymbolTimelineFrame, r: AnSymbolTimelineFrame, ratio: Double) { this.transform.setToInterpolated(ratio, l.transform, r.transform) this.colorTransform.setToInterpolated(ratio, l.colorTransform, r.colorTransform) this.ratio = ratio.interpolate(l.ratio, r.ratio) this.name = l.name this.blendMode = l.blendMode } companion object { fun setToViewInterpolated(view: View, l: AnSymbolTimelineFrame, r: AnSymbolTimelineFrame, ratio: Double) { view.setMatrixInterpolated(ratio, l.transform, r.transform) view.colorTransform = view.colorTransform.setToInterpolated(ratio, l.colorTransform, r.colorTransform) view.ratio = ratio.interpolate(l.ratio, r.ratio) view.name = l.name view.blendMode = l.blendMode } } fun setToView(view: View) { view.ratio = ratio view.setMatrix(transform) view.name = name view.colorTransform = colorTransform view.blendMode = blendMode } fun copyFrom(other: AnSymbolTimelineFrame) { this.depth = other.depth this.uid = other.uid this.clipDepth = other.clipDepth this.ratio = other.ratio this.transform.copyFrom(other.transform) this.name = other.name this.colorTransform.copyFrom(other.colorTransform) this.blendMode = other.blendMode } //fun setToInterpolated(l: AnSymbolTimelineFrame, r: AnSymbolTimelineFrame, ratio: Double) { // this.depth = l.depth // this.uid = l.uid // this.clipDepth = l.clipDepth // this.ratio = ratio.interpolate(l.ratio, r.ratio) // this.transform.setToInterpolated(l.transform, r.transform, ratio) // this.name = l.name // this.colorTransform.setToInterpolated(l.colorTransform, r.colorTransform, ratio) // this.blendMode = l.blendMode //} // //fun writeCompressedPack(s: SyncStream, cp: AnConstantPool) { // val hasUid = uid >= 0 // val hasClipDepth = clipDepth >= 0 // val hasRatio = clipDepth >= 0 // val hasTransform = transform.getType() != Matrix2d.Type.IDENTITY // val hasName = name != null // val hasColorTransform = !colorTransform.isIdentity() // val hasBlendMode = blendMode != BlendMode.INHERIT // s.writeU_VL(0 // .insert(hasUid, 0) // .insert(hasClipDepth, 1) // .insert(hasRatio, 2) // .insert(hasTransform, 3) // .insert(hasName, 4) // .insert(hasColorTransform, 5) // .insert(hasBlendMode, 6) // ) // // if (hasUid) s.writeU_VL(uid) // if (hasClipDepth) s.writeU_VL(clipDepth) // if (hasRatio) s.write8((ratio * 255).toInt()) // // @TODO: optimized // if (hasTransform) { // val t = transform // s.writeF32LE(t.a.toFloat()) // s.writeF32LE(t.b.toFloat()) // s.writeF32LE(t.c.toFloat()) // s.writeF32LE(t.d.toFloat()) // s.writeF32LE(t.tx.toFloat()) // s.writeF32LE(t.ty.toFloat()) // } // // @TODO: Use constantpool to store just integer // if (hasName) { // s.writeStringVL(name!!) // } // // @TODO: optimized // if (hasColorTransform) { // val ct = colorTransform // s.writeF32LE(ct.mRf) // s.writeF32LE(ct.mGf) // s.writeF32LE(ct.mBf) // s.writeF32LE(ct.mAf) // s.write32LE(ct.aR) // s.write32LE(ct.aG) // s.write32LE(ct.aB) // s.write32LE(ct.aA) // } // if (hasBlendMode) { // s.write8(blendMode.ordinal) // } //} // //fun readCompressedPack(s: FastByteArrayInputStream, cp: AnConstantPool) { // val flags = s.readU_VL() // val t = transform // val ct = colorTransform // uid = if (flags.extract(0)) s.readU_VL() else -1 // clipDepth = if (flags.extract(1)) s.readU_VL() else -1 // ratio = if (flags.extract(2)) s.readU8().toDouble() / 255.0 else 0.0 // if (flags.extract(3)) { // t.setTo( // s.readF32LE().toDouble(), // s.readF32LE().toDouble(), // s.readF32LE().toDouble(), // s.readF32LE().toDouble(), // s.readF32LE().toDouble(), // s.readF32LE().toDouble() // ) // } else { // t.setToIdentity() // } // if (flags.extract(4)) { // name = s.readStringVL() // } else { // name = null // } // if (flags.extract(5)) { // name = s.readStringVL() // } else { // name = null // } // if (flags.extract(6)) { // ct.setTo( // s.readF32LE().toDouble(), // s.readF32LE().toDouble(), // s.readF32LE().toDouble(), // s.readF32LE().toDouble(), // s.readS32LE(), // s.readS32LE(), // s.readS32LE(), // s.readS32LE() // ) // } else { // ct.setToIdentity() // } //} } interface AnAction data class AnPlaySoundAction(val soundId: Int) : AnAction data class AnEventAction(val event: String) : AnAction class AnDepthTimeline(val depth: Int) : Timed<AnSymbolTimelineFrame>() class AnSymbolLimits constructor(val totalDepths: Int, val totalFrames: Int, val totalUids: Int, val totalTime: TimeSpan) class AnSymbolUidDef(val characterId: Int, val extraProps: MutableMap<String, String> = LinkedHashMap()) class AnSymbolMovieClipSubTimeline(totalDepths: Int) { //var name: String = "default" var totalTime = 0.milliseconds //val totalTimeSeconds: Double get() = totalTime / 1_000_000.0 //val totalTimeSeconds: Double get() = 100.0 val timelines: Array<AnDepthTimeline> = Array<AnDepthTimeline>(totalDepths) { AnDepthTimeline(it) } val actions = Timed<AnAction>() var nextState: String? = null var nextStatePlay: Boolean = false } class AnSymbolMovieClipState(val name: String, val subTimeline: AnSymbolMovieClipSubTimeline, val startTime: TimeSpan) class AnSymbolMovieClip(id: Int, name: String?, val limits: AnSymbolLimits) : AnSymbol(id, name) { var ninePatch: Rectangle? = null val states = hashMapOf<String, AnSymbolMovieClipState>() val uidInfo = Array(limits.totalUids) { AnSymbolUidDef(-1, hashMapOf()) } override fun create(library: AnLibrary): AnElement = AnMovieClip(library, this) } val Views.animateLibraryLoaders by Extra.Property { arrayListOf<KorgeFileLoaderTester<AnLibrary>>( KorgeFileLoaderTester("core/ani") { s, injector -> when { (s.readString(8) == AniFile.MAGIC) -> KorgeFileLoader("ani") { content, views -> this.readAni( AnLibrary.Context(views), content = content ) } else -> null } } ) } //e: java.lang.UnsupportedOperationException: Class literal annotation arguments are not yet supported: Factory //@AsyncFactoryClass(AnLibrary.Factory::class) class AnLibrary(val context: Context, val width: Int, val height: Int, val fps: Double) : Extra by Extra.Mixin() { val fontsCatalog = Html.FontsCatalog(null) data class Context( val coroutineContext: CoroutineContext = EmptyCoroutineContext, val imageFormats: ImageFormat = RegisteredImageFormats, ) { companion object { operator fun invoke(views: Views) = Context(views.coroutineContext, views.imageFormats) } } val msPerFrameDouble: Double = (1000 / fps) val msPerFrame: Int = msPerFrameDouble.toInt() var bgcolor: RGBA = Colors.WHITE val symbolsById = arrayListOf<AnSymbol>() val symbolsByName = hashMapOf<String, AnSymbol>() var defaultSmoothing = true //var defaultSmoothing = false fun addSymbol(symbol: AnSymbol) { while (symbolsById.size <= symbol.id) symbolsById += AnSymbolEmpty if (symbol.id >= 0) symbolsById[symbol.id] = symbol } fun processSymbolNames() { symbolsById.fastForEach { symbol -> if (symbol.name != null) symbolsByName[symbol.name!!] = symbol } } fun AnSymbol.findFirstTexture(): BmpSlice? { when (this) { is AnSymbolEmpty -> return null is AnSymbolSound -> return null is AnTextFieldSymbol -> return null is AnSymbolShape -> return this.textureWithBitmap?.texture is AnSymbolMorphShape -> return this.texturesWithBitmap.objects.firstOrNull()?.texture is AnSymbolBitmap -> return null is AnSymbolMovieClip -> { this.uidInfo.fastForEach { uid -> val res = create(uid.characterId).findFirstTexture() if (res != null) return res } return null } else -> throw RuntimeException("Don't know how to handle ${this::class}") } } fun AnElement.findFirstTexture(): BmpSlice? = this.symbol.findFirstTexture() fun create(id: Int) = if (id < 0) TODO("id=$id") else symbolsById.getOrElse(id) { AnSymbolEmpty }.create(this) fun createShape(id: Int) = create(id) as AnShape fun createMovieClip(id: Int) = create(id) as AnMovieClip fun getTexture(id: Int) = create(id).findFirstTexture() fun create(name: String) = symbolsByName[name]?.create(this) ?: invalidOp("Can't find symbol with name '$name'") fun createShape(name: String) = create(name) as AnShape fun createMovieClip(name: String) = create(name) as AnMovieClip fun getTexture(name: String) = create(name).findFirstTexture() fun getBitmap(id: Int) = (symbolsById[id] as AnSymbolBitmap).bmp fun getBitmap(name: String) = (symbolsByName[name] as AnSymbolBitmap).bmp val mainTimeLineInfo: AnSymbolMovieClip get() = symbolsById[0] as AnSymbolMovieClip fun createMainTimeLine() = createMovieClip(0) }
apache-2.0
72cc1125327298afc765b328f59c5358
31.016129
121
0.702015
3.058552
false
false
false
false
stoman/competitive-programming
problems/2020adventofcode21a/submissions/accepted/Stefan.kt
2
1110
import java.util.* fun main() { val s = Scanner(System.`in`).useDelimiter("\\n") var possibleCandidates = mutableMapOf<String, Set<String>>() val namesCount = mutableMapOf<String, Int>() while (s.hasNext()) { val sLine = Scanner(s.next()).useDelimiter("""\s\(|\)|,\s|\s""") val names = mutableListOf<String>() var firstPart = true while (sLine.hasNext()) { val next = sLine.next() when { next == "contains" -> { firstPart = false } firstPart -> { names += next namesCount[next] = 1 + (namesCount[next] ?: 0) } else -> { possibleCandidates[next] = names.intersect(possibleCandidates[next] ?: names) } } } } while (true) { val elim: String = possibleCandidates.filter { it.value.size == 1 }.keys.firstOrNull() ?: break val name = possibleCandidates[elim]!!.first() possibleCandidates = possibleCandidates.mapValues { it.value.minus(name) }.toMutableMap() namesCount.remove(name) possibleCandidates.remove(elim) } println(namesCount.values.sum()) }
mit
d1edd9f712e7adbf87865882b3e0d8c3
29.833333
99
0.597297
3.922261
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/ui/UITextEdit.kt
1
12757
package com.soywiz.korge.ui /** * * @author Matthias Wienand and Dr.D.H.Akehurst * */ /* class UITextEdit(textArg: String, fontArg: TtfFont, sizeArg: Double, colorArg: RGBA) { var font = fontArg var size = sizeArg var color = colorArg var text = textArg val caret = Caret({ text.length }) { image.bitmap = render() } val selection = Selection() // initial rendering val image = Image(render()) var _handle_input = false fun handleKeyboardInput() { if (_handle_input) return _handle_input = true image.onKeyUp { onKeyUp(it) } image.onKeyDown { onKeyDown(it) } // TODO: unregister (maybe replace Image) } var readOnly = false fun hideCaret() { caret.stopBlinking() if (caret.showCaret) { caret.showCaret = false image.bitmap = render() } } fun showCaret() { caret.stopBlinking() if (!caret.showCaret) { caret.showCaret = true image.bitmap = render() } } fun setReadOnly() { readOnly = true } fun setEditable() { readOnly = false handleKeyboardInput() showCaret() } class Caret(endPosArg: ()->Int, blinkActionArg: ()->Unit) { // TODO: clean-up relationship between TextEdit.text and Caret // -> Maybe have setter for the text and notify caret about text changes val _getEndPos = endPosArg val endpos get() = _getEndPos() var pos = endpos var blinkAction = blinkActionArg var caretColor = Colors.DARKGREY var showCaret = false interface CaretRenderer { fun render(ctxt: Context2d, height: Int, charWidth: Int, dsc: Int): Int } val Center = object : CaretRenderer { var width = 2 override fun render(ctxt: Context2d, height: Int, charWidth: Int, dsc: Int): Int { var extra = 0 if (pos == endpos) extra = width / 2 val loc = if (pos == 0) 0 else -width / 2 ctxt.fillRect(loc, 0, width, height) return extra } } val FillChar = object : CaretRenderer { override fun render(ctxt: Context2d, height: Int, charWidth: Int, dsc: Int): Int { ctxt.fillRect(0, 0, charWidth, height) return charWidth } } val Underscore = object : CaretRenderer { var width = 4 override fun render(ctxt: Context2d, height: Int, charWidth: Int, dsc: Int): Int { ctxt.fillRect(0, height - dsc - width, charWidth, width) return charWidth } } var type = Center fun render(ctxt: Context2d, height: Int, charWidth: Int, dsc: Int): Int { if (!showCaret) return 0 var extra = 0 // extra space needed on the right side of the rendering to show the caret ctxt.fillStyle(caretColor) { extra = type.render(ctxt, height, charWidth, dsc) } return extra } var blinkId = 0 var blinkDuration = 500L var blinkTime = DateTime.now().unixMillisLong - blinkDuration fun resetBlinkTimer() { showCaret = true blinkTime = DateTime.now().unixMillisLong + blinkDuration } suspend fun blink() { suspend fun doBlink(id: Int) { val now = DateTime.now().unixMillisLong if (blinkTime <= now) { // we need to blink immediately! showCaret = !showCaret blinkAction() blinkTime = now + blinkDuration } else { // sleep for the remaining time var sleep = blinkTime - now if (sleep > blinkDuration) sleep = blinkDuration delay(TimeSpan(sleep.toDouble())) } // blink until stopped if (id == blinkId) doBlink(id) } doBlink(blinkId) } fun stopBlinking() { blinkId++ } fun moveTo(xArg: Int, mods: ModSet, sel: Selection) { // sanitize inputs var x = xArg if (x < 0) x = 0 else if (x > endpos) x = endpos // update selection if (mods.shift) { sel.change(pos, x - pos) } else { sel.reset() } // update caret position pos = x } fun moveBy(step: Int, mods: ModSet, selection: Selection) { moveTo(pos + step, mods, selection) } fun delete(text: String, direction: Int): String { val next = pos + direction if (next < 0 || next > endpos) return text val res = text.substring(0, minOf(pos, next)) + text.substring(maxOf(pos, next)) pos += direction return res } } class Selection { var range = 0..0 var foreground = Colors.BLACK var background = Colors.LIGHTBLUE val start get() = range.start val last get() = range.last fun isEmpty() = start == last fun isPresent() = start != last fun contains(x: Int) = range.contains(x) fun reset() { range = 0..0 } fun change(x: Int, by: Int) { var next = x + by if (next < 0) next = 0 if (next == x) return if (isEmpty()) range = minOf(x, next) .. maxOf(next, x) else { if (next <= x) { if (start <= next) range = start .. next else range = next .. last } else { if (last < next) range = start .. next else range = next .. last } } } fun cut(text: String): String { val res = text.substring(0, start) + text.substring(last) range = start .. start return res } fun replace(text: String, replacement: String): String { val res = text.substring(0, start) + replacement + text.substring(last) range = start .. start return res } } constructor(textArg: String, fontArg: TtfFont) : this(textArg, fontArg, 32.0, Colors.BLACK) constructor(fontArg: TtfFont) : this("", fontArg) fun render(): BitmapSlice<Bitmap> { val asc = font.ascender / 72 val dsc = asc / 2 val h = (size + asc + 0.5).toInt() val nativeImage = NativeImage(1024, h) val ctxt = nativeImage.getContext2d() // TODO: refactor rendering commands if (selection.contains(caret.pos)) { // selection rendering val preSel = text.substring(0, selection.start) val preCaret = text.substring(selection.start, caret.pos) val postCaret = text.substring(caret.pos, selection.last) val postSel = text.substring(selection.last) // render text before selection if (preSel.isNotEmpty()) { font.drawText(ctxt, text=preSel, size=size, x=0.0, y=0.0, paint=ColorPaint(color), TtfFont.Origin.TOP) } // save selection's x positions while rendering it the first time val selX1 = (ctxt.translate(0, 0).tx + 0.5).toInt() ctxt.save() val selText = preCaret + postCaret if (selText.isNotEmpty()) { font.drawText(ctxt, text=selText, size=size, x=0.0, y=0.0, paint=ColorPaint(color), TtfFont.Origin.TOP) } val selX2 = (ctxt.translate(0, 0).tx + 0.5).toInt() // render text after the selection and save final x position if (postSel.isNotEmpty()) { font.drawText(ctxt, text=postSel, size=size, x=0.0, y=0.0,paint=ColorPaint( color), TtfFont.Origin.TOP) } val finalX = (ctxt.translate(0, 0).tx + 0.5).toInt() // render selection background (drawing over the text) ctxt.fillStyle(selection.background) { ctxt.fillRect(-finalX + selX1, 0, selX2 - selX1, h) } // render the selected text (drawing over the selection background) ctxt.restore() if (preCaret.isNotEmpty()) { font.drawText(ctxt, text=preCaret, size=size,x= 0.0, y=0.0, paint=ColorPaint(selection.foreground), TtfFont.Origin.TOP) } val extra = caret.render(ctxt, h, _charWidth(), dsc) if (postCaret.isNotEmpty()) { font.drawText(ctxt, text=postCaret, size=size,x= 0.0, y=0.0, paint=ColorPaint(selection.foreground), TtfFont.Origin.TOP) } // return bitmap sliced to the actual text bounds var w = if (finalX < 1) 0 else finalX w += extra return nativeImage.sliceWithSize(0, 0, w, h) } // regular rendering val textPreCaret = text.substring(0, caret.pos) val textPostCaret = text.substring(caret.pos) if (textPreCaret.isNotEmpty()) { font.drawText(ctxt, size=size, text=textPreCaret, x=0.0, y=0.0, paint=ColorPaint(color), TtfFont.Origin.TOP) } val extra = caret.render(ctxt, h, _charWidth(), dsc) if (textPostCaret.isNotEmpty()) { font.drawText(ctxt, text=textPostCaret, size=size, x=0.0, y=0.0, paint=ColorPaint(color), TtfFont.Origin.TOP) } val w = (ctxt.translate(0, 0).tx + 0.5).toInt() + extra return nativeImage.sliceWithSize(0, 0, if (w < 1) 0 else w, h) } // TODO: real character width computation, test with mono font fun _charWidth() = (size / 2).toInt() // manage state of modifier keys class ModKey(vararg keySetArg: Key) { var isOn = false val keyMap = mutableMapOf<Key, Boolean>().apply { // TODO: initialize with actual keyboard state keySetArg.forEach { this[it] = false } } fun update(ev: KeyEvent) { if (ev.key in keyMap) { keyMap[ev.key] = ev.type == KeyEvent.Type.DOWN isOn = keyMap.any { it.value } } } } class ModSet { val modAlt = ModKey(Key.LEFT_ALT, Key.RIGHT_ALT) val modShift = ModKey(Key.LEFT_SHIFT, Key.RIGHT_SHIFT) val alt: Boolean get() = modAlt.isOn val shift: Boolean get() = modShift.isOn fun update(ev: KeyEvent) { modAlt.update(ev) modShift.update(ev) } } val mods = ModSet() // user interaction fun onKeyUp(ev: KeyEvent) { mods.update(ev) } fun _delete(direction: Int) { if (selection.isPresent()) { text = selection.cut(text) caret.pos = selection.start } else { text = caret.delete(text, direction) } } fun onKeyDown(ev: KeyEvent) { mods.update(ev) caret.resetBlinkTimer() //println("ev: " + ev.key + ", " + ev.keyCode + " <" + ev.character + ">") if (ev.key == Key.BACKSPACE) { if (!readOnly) _delete(-1) } else if (ev.key == Key.DELETE) { if (!readOnly) _delete(1) } else if (ev.key == Key.LEFT) { caret.moveBy(-1, mods, selection) } else if (ev.key == Key.RIGHT) { caret.moveBy(1, mods, selection) } else if (ev.character.isPrintable() && !readOnly) { if (selection.isPresent()) { text = selection.replace(text, ev.character.toString()) caret.pos = selection.start + 1 } else { text = text.substring(0, caret.pos) + ev.character + text.substring(caret.pos) caret.pos++ } } else { // prevent unnecessary rendering return // TODO: word-by-word with ALT // TODO: full line with CMD } image.bitmap = render() } // TODO: restricted width + align (left,center,right) + ellipsis ("some text that is too lo...") // TODO: font styles (bold, underlined, overlined, striked-through, italic, etc.) // Maybe consider building stuff around this: // TextEditFlow: multi-line text (and multi-line selection) // . line-wrap (by word or by character) // . attributed sections (define_style('x', Style(Bold, Underlined)); set_style('x', 4, 6)) // . optimized use of resources (if necessary) } */
apache-2.0
f5bb0a2257395100e1ab2a68087c5d17
33.201072
136
0.529984
4.108535
false
false
false
false
apixandru/intellij-community
xml/impl/src/com/intellij/ide/browsers/actions/SelectInDefaultBrowserTarget.kt
18
2157
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.browsers.actions import com.intellij.ide.SelectInContext import com.intellij.ide.SelectInTarget import com.intellij.ide.StandardTargetWeights import com.intellij.ide.browsers.createOpenInBrowserRequest import com.intellij.ide.browsers.impl.WebBrowserServiceImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.vfs.impl.http.HttpVirtualFile import com.intellij.psi.PsiElement import com.intellij.testFramework.LightVirtualFile import com.intellij.xml.XmlBundle import com.intellij.xml.util.HtmlUtil private val LOG = Logger.getInstance(SelectInDefaultBrowserTarget::class.java) internal class SelectInDefaultBrowserTarget : SelectInTarget { override fun canSelect(context: SelectInContext): Boolean { val selectorInFile = context.selectorInFile as? PsiElement ?: return false val request = createOpenInBrowserRequest(selectorInFile) ?: return false val urlProvider = WebBrowserServiceImpl.getProvider(request) if (urlProvider == null) { val virtualFile = request.virtualFile ?: return false return virtualFile is HttpVirtualFile || (HtmlUtil.isHtmlFile(request.file) && virtualFile !is LightVirtualFile) } return true } override fun toString() = XmlBundle.message("browser.select.in.default.name") override fun selectIn(context: SelectInContext, requestFocus: Boolean) { BaseOpenInBrowserAction.open(createOpenInBrowserRequest(context.selectorInFile as PsiElement), false, null) } override fun getWeight() = StandardTargetWeights.OS_FILE_MANAGER }
apache-2.0
e4497597306ebe02776d2eed0415d8c2
41.294118
118
0.789522
4.393075
false
false
false
false
panpf/sketch
sketch-zoom/src/main/java/com/github/panpf/sketch/zoom/internal/LocationRunnable.kt
1
2125
/* * Copyright (C) 2022 panpf <[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.github.panpf.sketch.zoom.internal import android.content.Context import android.view.animation.AccelerateDecelerateInterpolator import android.widget.Scroller import androidx.core.view.ViewCompat internal class LocationRunnable( context: Context, private val zoomerHelper: ZoomerHelper, private val scaleDragHelper: ScaleDragHelper, private val startX: Int, private val startY: Int, private val endX: Int, private val endY: Int ) : Runnable { private val scroller = Scroller(context, AccelerateDecelerateInterpolator()) private var currentX = 0 private var currentY = 0 val isRunning: Boolean get() = !scroller.isFinished fun start() { cancel() currentX = startX currentY = startY scroller.startScroll(startX, startY, endX - startX, endY - startY, 300) zoomerHelper.view.post(this) } fun cancel() { zoomerHelper.view.removeCallbacks(this) scroller.forceFinished(true) } override fun run() { if (scroller.isFinished) { return } if (scroller.computeScrollOffset()) { val newX = scroller.currX val newY = scroller.currY val dx = (currentX - newX).toFloat() val dy = (currentY - newY).toFloat() scaleDragHelper.translateBy(dx, dy) currentX = newX currentY = newY ViewCompat.postOnAnimation(zoomerHelper.view, this) } } }
apache-2.0
7624075c77d91f7650e528204a8b788a
29.371429
80
0.669647
4.4926
false
false
false
false
andretortolano/GithubSearch
app/src/main/java/com/example/andretortolano/githubsearch/ui/screens/searchuser/SearchUserView.kt
1
3537
package com.example.andretortolano.githubsearch.ui.screens.searchuser import android.os.Bundle import android.support.v4.view.MenuItemCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.SearchView import android.view.* import com.example.andretortolano.githubsearch.R import com.example.andretortolano.githubsearch.api.github.GithubService import com.example.andretortolano.githubsearch.api.github.responses.User import com.example.andretortolano.githubsearch.ui.components.CustomRecyclerViewListener import com.example.andretortolano.githubsearch.ui.components.UserRecyclerAdapter import com.example.andretortolano.githubsearch.ui.screens.BaseFragment import com.example.andretortolano.githubsearch.ui.screens.showuser.ShowUserView import kotlinx.android.synthetic.main.fragment_search_user.* class SearchUserView : BaseFragment<SearchUserContract.Presenter>(), SearchUserContract.View { override lateinit var mPresenter: SearchUserContract.Presenter private val mAdapter: UserRecyclerAdapter = UserRecyclerAdapter(ArrayList<User>(), object : CustomRecyclerViewListener<User> { override fun onItemSelect(item: User) { openUserDetails(item) } }) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mPresenter = SearchUserPresenter(this, GithubService()) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?) = inflater!!.inflate(R.layout.fragment_search_user, container, false)!! override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler_view.layoutManager = LinearLayoutManager(context) recycler_view.adapter = mAdapter } override fun showUsers(users: List<User>) { mAdapter.userList.clear() mAdapter.userList.addAll(users) mAdapter.notifyDataSetChanged() } override fun showProgress() { progress_view.visibility = View.VISIBLE } override fun hideProgress() { progress_view.visibility = View.GONE } override fun openUserDetails(user: User) { val frag: ShowUserView = ShowUserView.newInstance(user.login) fragmentManager.beginTransaction() .replace(R.id.content_frame, frag) .addToBackStack(BACK_STACK_NAME) .commit() } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { val searchActionItem = menu?.findItem(R.id.action_search) val searchView = MenuItemCompat.getActionView(searchActionItem) as SearchView searchView.queryHint = getString(R.string.user_view_search_hint) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String?) = false override fun onQueryTextSubmit(query: String?): Boolean { mPresenter.searchUsers(query); return false } }) MenuItemCompat.setOnActionExpandListener(searchActionItem, object : MenuItemCompat.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem?) = true override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { mPresenter.onCloseActionSearch() return true } }) super.onCreateOptionsMenu(menu, inflater) } }
mit
9040263048ec4d014b30983c31311934
38.3
130
0.720667
5.163504
false
false
false
false
shlusiak/Freebloks-Android
app/src/main/java/de/saschahlusiak/freebloks/view/Freebloks3DView.kt
1
10583
package de.saschahlusiak.freebloks.view import android.annotation.SuppressLint import android.content.Context import android.opengl.GLSurfaceView import android.util.AttributeSet import android.view.MotionEvent import androidx.annotation.UiThread import androidx.annotation.WorkerThread import de.saschahlusiak.freebloks.client.GameClient import de.saschahlusiak.freebloks.client.GameEventObserver import de.saschahlusiak.freebloks.model.* import de.saschahlusiak.freebloks.network.message.MessageServerStatus import de.saschahlusiak.freebloks.theme.FeedbackType import de.saschahlusiak.freebloks.theme.Theme import de.saschahlusiak.freebloks.utils.PointF import de.saschahlusiak.freebloks.view.effects.* import de.saschahlusiak.freebloks.view.scene.AnimationType import de.saschahlusiak.freebloks.view.scene.Scene import kotlin.math.sqrt import kotlin.random.Random class Freebloks3DView(context: Context?, attrs: AttributeSet?) : GLSurfaceView(context, attrs), GameEventObserver { private lateinit var scene: Scene private lateinit var renderer: FreebloksRenderer private var scale = 1.0f private var thread: AnimateThread? = null private var oldDist = 0f fun setScene(scene: Scene) { setEGLConfigChooser(GLConfigChooser(2)) this.scene = scene renderer = FreebloksRenderer(context, scene).apply { zoom = scale } setRenderer(renderer) renderMode = RENDERMODE_WHEN_DIRTY debugFlags = DEBUG_CHECK_GL_ERROR } fun setTheme(backgroundTheme: Theme, boardTheme: Theme) { renderer.backgroundRenderer.setTheme(backgroundTheme) renderer.boardRenderer.setTheme(boardTheme) } fun setGameClient(client: GameClient?) { if (client != null) { scene.setGameClient(client) } scene.clearEffects() queueEvent { if (client != null) { val game = client.game scene.boardObject.lastSize = game.board.width for (i in 0 until Board.PLAYER_MAX) if (game.isLocalPlayer(i)) { scene.basePlayer = i break } renderer.updateModelViewMatrix = true scene.wheel.update(scene.boardObject.showWheelPlayer) newCurrentPlayer(game.currentPlayer) } renderer.init(scene.boardObject.lastSize) requestRender() } } private fun spacing(event: MotionEvent): Float { val x = event.getX(0) - event.getX(1) val y = event.getY(0) - event.getY(1) return sqrt(x * x + y * y) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { val modelPoint = renderer.windowToModel(PointF(event.x, event.y)) when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { scene.handlePointerDown(modelPoint) } MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1) { val newDist = spacing(event) if (newDist > 10f) { scale *= newDist / oldDist if (scale > 3.0f) scale = 3.0f if (scale < 0.3f) scale = 0.3f oldDist = newDist renderer.updateModelViewMatrix = true renderer.zoom = scale requestRender() } } else { scene.handlePointerMove(modelPoint) } MotionEvent.ACTION_POINTER_DOWN -> { scene.handlePointerUp(modelPoint) oldDist = spacing(event) } MotionEvent.ACTION_UP -> { scene.handlePointerUp(modelPoint) } } if (scene.isInvalidated()) { requestRender() } return true } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { renderer.updateModelViewMatrix = true super.onSizeChanged(w, h, oldw, oldh) } override fun newCurrentPlayer(player: Int) { if (scene.game.isLocalPlayer() || scene.wheel.currentPlayer != scene.boardObject.showWheelPlayer) scene.wheel.update(scene.boardObject.showWheelPlayer) requestRender() } override fun stoneWillBeSet(turn: Turn) { queueEvent { if (scene.hasAnimations() && !scene.game.isLocalPlayer(turn.player)) { val e = ShapeRollEffect(scene, turn, 4.0f, -7.0f) val set = EffectSet() set.add(e) set.add(ShapeFadeEffect(scene, turn, 2.0f)) scene.addEffect(set) } } } override fun stoneHasBeenSet(turn: Turn) { if (scene.game.isLocalPlayer(turn.player) || turn.player == scene.wheel.currentPlayer) scene.wheel.update(scene.boardObject.showWheelPlayer) requestRender() if (!scene.game.isLocalPlayer(turn.player)) { scene.playSound(FeedbackType.StoneHasBeenSet, speed = 0.9f + Random.nextFloat() * 0.2f) } } override fun playerIsOutOfMoves(player: Player) { val game = scene.game val board = game.board if (scene.hasAnimations()) { val gameMode = game.gameMode val seed = board.getPlayerSeed(player.number, gameMode) ?: return for (x in 0 until board.width) for (y in 0 until board.height) if (board.getFieldPlayer(y, x) == player.number) { var effected = false synchronized(scene.effects) { for (j in scene.effects.indices) if (scene.effects.get(j).isEffected(x, y)) { effected = true break } } if (!effected) { val distance = sqrt((x - seed.x) * (x - seed.x) + (y - seed.y) * (y - seed.y).toFloat()) val effect: Effect = BoardStoneGlowEffect( (scene), gameMode.colorOf(player.number), x, y, distance) scene.addEffect(effect) } } } } @WorkerThread override fun hintReceived(turn: Turn) { queueEvent { if (turn.player != scene.game.currentPlayer) return@queueEvent if (!scene.game.isLocalPlayer()) return@queueEvent scene.boardObject.resetRotation() scene.wheel.update(turn.player) scene.wheel.showStone(turn.shapeNumber) scene.playSound(FeedbackType.Hint, volume = 0.9f) val currentPlayer = scene.game.currentPlayer val st: Stone if (currentPlayer >= 0) st = scene.board.getPlayer(currentPlayer).getStone(turn.shapeNumber) else return@queueEvent val p = PointF( turn.x - 0.5f + st.shape.size.toFloat() / 2.0f, turn.y - 0.5f + st.shape.size.toFloat() / 2.0f ) scene.currentStone.startDragging(p, st, turn.orientation, scene.getPlayerColor(turn.player)) requestRender() } } override fun gameFinished() { scene.boardObject.resetRotation() requestRender() } override fun gameStarted() { scene.basePlayer = 0 for (i in 0 until Board.PLAYER_MAX) if (scene.game.isLocalPlayer(i)) { scene.basePlayer = i break } scene.wheel.update(scene.boardObject.showWheelPlayer) renderer.updateModelViewMatrix = true scene.reset() requestRender() } override fun stoneUndone(t: Turn) { if (scene.hasAnimations()) { val e: Effect = ShapeUndoEffect(scene, t) scene.addEffect(e) } scene.currentStone.stopDragging() requestRender() } override fun serverStatus(status: MessageServerStatus) { if (status.width != scene.boardObject.lastSize) { scene.boardObject.lastSize = status.width queueEvent { renderer.boardRenderer.setBoardSize(scene.board.width) requestRender() } } } @UiThread override fun onConnected(client: GameClient) { newCurrentPlayer(client.game.currentPlayer) } /** * Execute the scene for the given amount of seconds. * * If the scene reports that it would like to be rendered * * @param elapsed time in seconds, but never 0.0f * @param lastRendered how long ago we last rendered the scene * @return true if the scene has been rendered, false otherwise */ @WorkerThread fun execute(elapsed: Float, lastRendered: Float): Boolean { val currentRenderMode = renderMode if (scene.execute(elapsed) || scene.isInvalidated()) { // scene has changed and would like to be rendered // without animations we render exactly when the scene wants to, but ideally it would be smart // enough to not have animations at all if (scene.showAnimations == AnimationType.Off) { requestRender() } else { // we switch to continuous render mode whenever the scene has changed if (currentRenderMode == RENDERMODE_WHEN_DIRTY) renderMode = RENDERMODE_CONTINUOUSLY } return true } else { // and revert to when_dirty when we had no animations for 0.3s if (lastRendered >= 0.3f && currentRenderMode == RENDERMODE_CONTINUOUSLY) renderMode = RENDERMODE_WHEN_DIRTY return false } } override fun onPause() { super.onPause() try { thread?.goDown = true thread?.interrupt() thread?.join() } catch (e: InterruptedException) { e.printStackTrace() } scene.effects.clear() thread = null } override fun onResume() { super.onResume() scene.clearEffects() if (thread == null) { thread = AnimateThread(scene, this::execute).also { it.start() } } } fun setScale(scale: Float) { this.scale = scale renderer.zoom = scale renderer.updateModelViewMatrix = true } fun getScale(): Float { return scale } }
gpl-2.0
cff49a852f8f1b1b6e81f309e6d7953d
33.588235
125
0.580365
4.581385
false
false
false
false
pokk/KotlinKnifer
kotlinknifer/src/main/java/com/devrapid/kotlinknifer/Uri.kt
1
6171
@file:Suppress("NOTHING_TO_INLINE") package com.devrapid.kotlinknifer import android.content.ContentUris import android.content.Context import android.net.Uri import android.os.Build import android.os.Environment import android.provider.DocumentsContract import android.provider.MediaStore import android.provider.OpenableColumns import com.devrapid.kotlinshaver.copyFrom import java.io.BufferedReader import java.io.File import java.io.IOException import java.io.InputStreamReader /** * @author Jieyi Wu * @since 2018/03/23 */ /** * For above [Build.VERSION_CODES.KITKAT], convert the uri to the absolute path. */ fun Uri.toPath(context: Context): String? { val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT // DocumentProvider return if (isKitKat && DocumentsContract.isDocumentUri(context, this)) { val docId = DocumentsContract.getDocumentId(this) val split = docId .split(":".toRegex()) .dropLastWhile(String::isEmpty) .toTypedArray() val type = split[0] // ExternalStorageProvider return if (isExternalStorageDocument()) { if ("primary".equals(type, ignoreCase = true)) { "${Environment.getExternalStorageDirectory()}/${split[1]}" } // TODO handle non-primary volumes else { "storage/${docId.replace(":", "/")}" } } // DownloadsProvider else if (isDownloadsDocument()) { getFilePath(context, this)?.let { return "${Environment.getExternalStorageDirectory()}/Download/$it" } val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), docId.toLong()) getDataColumn(context, contentUri) } // MediaProvider else if (isMediaDocument()) { val contentUri = when (type) { "image" -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI "video" -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI "audio" -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI else -> null } val selection = "_id=?" val selectionArgs = arrayOf(split[1]) if (contentUri == null) return null getDataColumn(context, contentUri, selection, selectionArgs) } else null } // MediaStore (and general) else if ("content".equals(scheme, ignoreCase = true)) { // Return the remote address. if (isGooglePhotosUri()) { return lastPathSegment } getDataColumn(context, this) } // File else if ("file".equals(scheme, ignoreCase = true)) { path } else null } fun Uri.getRealFileName(context: Context): String { val uriString = toString() val file = File(uriString) return when { uriString.startsWith("content://") -> context.contentResolver.query(this, null, null, null, null)?.use { if (it.moveToFirst()) { it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME)) } else { null } }.orEmpty() uriString.startsWith("file://") -> file.name.orEmpty() else -> "" } } @Throws(IOException::class) fun Uri.readText(context: Context) = buildString { context.contentResolver.openInputStream(this@readText)?.use { inputStream -> BufferedReader(InputStreamReader(inputStream)).use { reader -> var line = reader.readLine() while (line != null) { append(line) line = reader.readLine() } } } } @Throws(NullPointerException::class) fun Uri.toFile(context: Context, prefix: String = "temp", suffix: String? = null) = File.createTempFile(prefix, suffix).also { try { it.copyFrom(requireNotNull(context.contentResolver.openInputStream(this))) } catch (e: IllegalArgumentException) { throw NullPointerException(e.localizedMessage) } } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ internal fun getDataColumn( context: Context, uri: Uri, selection: String? = null, selectionArgs: Array<String>? = null, ): String? { val column = "_data" val projection = arrayOf(column) return context.contentResolver.query(uri, projection, selection, selectionArgs, null)?.use { if (it.moveToFirst()) { val columnIndex = it.getColumnIndexOrThrow(column) it.getString(columnIndex) } else { null } } } internal fun getFilePath(context: Context, uri: Uri): String? { val projection = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME) return context.contentResolver.query(uri, projection, null, null, null)?.use { if (it.moveToFirst()) { val index = it.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME) return it.getString(index) } else { null } } } /** * The Uri authority is ExternalStorageProvider. */ inline fun Uri.isExternalStorageDocument() = "com.android.externalstorage.documents" == authority /** * The Uri authority is DownloadsProvider. */ inline fun Uri.isDownloadsDocument() = "com.android.providers.downloads.documents" == authority /** * The Uri authority is MediaProvider. */ inline fun Uri.isMediaDocument() = "com.android.providers.media.documents" == authority /** * The Uri authority is Google Photos Uri. */ inline fun Uri.isGooglePhotosUri() = "com.google.android.apps.photos.content" == authority
apache-2.0
faf6574f3846ec8064b186b5af3ba3ea
30.646154
97
0.617242
4.619012
false
false
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/adapters/GridViewDatabaseItemCheckBoxAdapter.kt
1
1351
package com.sapuseven.untis.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import com.sapuseven.untis.R import com.sapuseven.untis.models.untis.timetable.PeriodElement class GridViewDatabaseItemCheckBoxAdapter(context: Context) : GridViewDatabaseItemAdapter(context) { private var inflater: LayoutInflater = LayoutInflater.from(context) private val selectedItems: MutableList<PeriodElement> = ArrayList() override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = convertView ?: inflater.inflate(R.layout.item_gridview_checkbox, parent, false) val holder = Holder(view.findViewById(R.id.checkbox)) holder.checkBox.text = getItem(position) holder.checkBox.setOnCheckedChangeListener(null) holder.checkBox.isChecked = selectedItems.contains(itemAt(position)) holder.checkBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked && !selectedItems.contains(itemAt(position))) selectedItems.add(itemAt(position)) else if (selectedItems.contains(itemAt(position))) selectedItems.remove(itemAt(position)) } return view } fun getSelectedItems(): List<PeriodElement> { return selectedItems.toList() } private data class Holder( var checkBox: CheckBox ) }
gpl-3.0
5c1ab1d7fa766efbf67e82b4fff41725
33.666667
92
0.789785
4.020833
false
false
false
false
robohorse/gpversionchecker
gpversionchecker/src/main/kotlin/com/robohorse/gpversionchecker/utils/DataParser.kt
1
2000
package com.robohorse.gpversionchecker.utils import android.text.TextUtils import com.robohorse.gpversionchecker.domain.Version import org.jsoup.nodes.Document class DataParser( private val textFormatter: TextFormatter ) { fun parse(document: Document?, url: String?): Version { var newVersion = EMPTY_STRING document?.let { val elements = document.getElementsContainingOwnText(DIV_VERSION) for (element in elements) { if (element.siblingElements() != null) { val subElements = element.siblingElements() for (subElement in subElements) { newVersion = subElement.text() } } } } var changes: String? = EMPTY_STRING var description: String? = EMPTY_STRING document?.let { description = textFormatter.format(document.select(DIV_DESCRIPTION) .html()) val elements = document.select(DIV_CHANGES) if (null != elements) { val changesElements = elements.select(DIV_CHANGES) if (!changesElements.isEmpty()) { changes = textFormatter.format(changesElements.last().html()) if (TextUtils.equals(changes, description)) { changes = null } } } } return Version( newVersionCode = newVersion, changes = changes, description = description, url = url ) } fun replaceNonDigits(value: String) = value.replace("[^\\d.]".toRegex(), EMPTY_STRING) .replace(".", EMPTY_STRING) } private const val DIV_VERSION = "Current Version" private const val DIV_CHANGES = "div[class=DWPxHb]" private const val DIV_DESCRIPTION = "div[itemprop=description]" private const val EMPTY_STRING = ""
mit
10af4f81019a3378d91aecf5f36fa159
34.087719
81
0.5555
5.102041
false
false
false
false
AlexLandau/semlang
kotlin/semlang-parser/src/main/kotlin/modules/fake0Versions.kt
1
1979
package net.semlang.modules import net.semlang.api.CURRENT_NATIVE_MODULE_VERSION import net.semlang.api.RawContext import net.semlang.api.ValidatedModule import net.semlang.parser.UnvalidatedModule import net.semlang.parser.writeToString import net.semlang.transforms.invalidate import net.semlang.validator.getTypesInfo import java.security.MessageDigest import kotlin.experimental.xor /** * A utility for computing a version under a "fake0" scheme that is similar in intention to hash-based versioning, * but different in implementation. */ // TODO: Consider adding the module name as an input to the hash fun computeFake0Version(context: RawContext, upstreamModules: Collection<ValidatedModule>): String { return computeFake0Hash(context, upstreamModules).toHexString() } private fun computeFake0Hash(module: ValidatedModule): ByteArray { return computeFake0Hash(invalidate(module), module.upstreamModules.values) } private fun computeFake0Hash(context: RawContext, upstreamModules: Collection<ValidatedModule>): ByteArray { val md: MessageDigest = MessageDigest.getInstance("SHA-256") md.update(xor32ByteArrays(upstreamModules.map { computeFake0Hash(it) })) val moduleAsString = writeToString(context, deterministicMode = true) md.update(moduleAsString.toByteArray()) return md.digest() } // Only accepts 256/8 = 32-length arrays private fun xor32ByteArrays(arrays: List<ByteArray>): ByteArray { val combination = ByteArray(32, { i -> 0 }) for (array in arrays) { if (array.size != 32) { error("Expected 32-byte arrays, but length was ${array.size}") } for (i in 0..31) { combination[i] = combination[i].xor(array[i]) } } return combination } private fun ByteArray.toHexString(): String { return this.map { byte -> var asInt = byte.toInt() if (asInt < 0) { asInt += 256 } asInt.toString(16) }.joinToString("") }
apache-2.0
03441d138dea01e67ea9bcae6fc2d66b
33.12069
114
0.720061
4.114345
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/YouTrackPluginApiService.kt
1
2753
package com.github.jk1.ytplugin import com.github.jk1.ytplugin.commands.model.YouTrackCommandExecution import com.github.jk1.ytplugin.issues.model.Issue import com.github.jk1.ytplugin.rest.CommandRestClient import com.github.jk1.ytplugin.rest.IssuesRestClient import com.github.jk1.ytplugin.ui.IssueViewer import com.intellij.openapi.components.Service import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.content.ContentFactory @Service class YouTrackPluginApiService(override val project: Project): YouTrackPluginApi, ComponentAware { override fun openIssueInToolWidow(issueId: String) { openIssueInToolWidow(findIssue(issueId)) } override fun search(query: String): List<YouTrackIssue> { return taskManagerComponent.getAllConfiguredYouTrackRepositories().flatMap { IssuesRestClient(it).getIssues(query) } } override fun executeCommand(issue: YouTrackIssue, command: String): YouTrackCommandExecutionResult { if (issue !is Issue) { throw IllegalArgumentException("Can't handle issue that was not loaded from the plugin API") } val client = CommandRestClient(taskManagerComponent.getYouTrackRepository(issue)) return client.executeCommand(YouTrackCommandExecution(issue, command, commentVisibleGroup = "All Users")) } fun openIssueInToolWidow(issue: Issue) { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow("YouTrack")!! val viewer = IssueViewer() val contentManager = toolWindow.contentManager val contentFactory = ContentFactory.SERVICE.getInstance() val content = contentFactory.createContent(viewer, issue.id, false) content.isCloseable = true contentManager.addContent(content) viewer.showIssue(issue) contentManager.setSelectedContent(content) toolWindow.show { contentManager.setSelectedContent(content) viewer.showIssue(issue) } } private fun findIssue(id: String): Issue { return taskManagerComponent.getAllConfiguredYouTrackRepositories() .map { issueStoreComponent[it] } .flatMap { it.getAllIssues() } .find { it.id == id } ?: findIssueOnServer(id) } private fun findIssueOnServer(id: String): Issue { for (server in taskManagerComponent.getAllConfiguredYouTrackRepositories()){ try { return IssuesRestClient(server).getIssue(id) } catch (e: RuntimeException) { // most likely 404 from server } } throw IllegalArgumentException("No issue found for id $id") } }
apache-2.0
b8102463eb100f4f71514cf1afd948f4
40.104478
113
0.705412
4.804538
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/lang/utils/snapshot/SnapshotMapTest.kt
4
1288
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.utils.snapshot import junit.framework.TestCase /** * [SnapshotMap] shares snapshot logic with [ org.rust.lang.core.type.RsUnificationTableTest], * so snapshot/rollback mechanics mostly tested in [org.rust.lang.core.type.RsUnificationTableTest] */ class SnapshotMapTest : TestCase() { private object Key private sealed class Value { object Value1 : Value() object Value2 : Value() } fun `test simple insert`() { val map = SnapshotMap<Key, Value>() map[Key] = Value.Value1 check(map[Key] == Value.Value1) } fun `test snapshot-rollback insert`() { val map = SnapshotMap<Key, Value>() val snapshot = map.startSnapshot() map[Key] = Value.Value1 check(map[Key] == Value.Value1) snapshot.rollback() check(map[Key] == null) } fun `test snapshot-rollback overwrite`() { val map = SnapshotMap<Key, Value>() map[Key] = Value.Value1 val snapshot = map.startSnapshot() map[Key] = Value.Value2 check(map[Key] == Value.Value2) snapshot.rollback() check(map[Key] == Value.Value1) } }
mit
abe89f8c521ecc6d902b0948003530fa
26.404255
99
0.623447
3.844776
false
true
false
false
TeamWizardry/LibrarianLib
modules/glitter/src/test/kotlin/com/teamwizardry/librarianlib/glitter/test/systems/FloodSystem.kt
1
3260
package com.teamwizardry.librarianlib.glitter.test.systems import com.teamwizardry.librarianlib.glitter.bindings.ConstantBinding import com.teamwizardry.librarianlib.glitter.modules.BasicPhysicsUpdateModule import com.teamwizardry.librarianlib.glitter.modules.SpriteRenderModule import com.teamwizardry.librarianlib.glitter.modules.SpriteRenderOptions import net.minecraft.entity.Entity import net.minecraft.util.Identifier import net.minecraft.util.math.MathHelper import net.minecraft.util.math.Vec3d object FloodSystem : TestSystem(Identifier("liblib-glitter-test:flood")) { override fun configure() { val position = bind(3) val previousPosition = bind(3) val velocity = bind(3) val color = bind(4) updateModules.add( BasicPhysicsUpdateModule( position = position, previousPosition = previousPosition, velocity = velocity, enableCollision = true, gravity = ConstantBinding(0.02), bounciness = ConstantBinding(0.8), friction = ConstantBinding(0.02), damping = ConstantBinding(0.01) ) ) renderModules.add( SpriteRenderModule.build( renderOptions = SpriteRenderOptions.build(Identifier("ll-glitter-test:textures/glitter/glow.png")) .additiveBlending() .writeDepth(false) .blur(true) .build(), position = position ) .previousPosition(previousPosition) .color(color) .size(2.0) .build() ) } override fun spawn(player: Entity) { val eyePos = player.getCameraPosVec(1f) repeat(20) { doSpawn( eyePos, player.pitch + (Math.random() - 0.5).toFloat() * 40, player.yaw + (Math.random() - 0.5).toFloat() * 180 ) } } fun doSpawn(pos: Vec3d, pitch: Float, yaw: Float) { val look = getVectorForRotation(pitch, yaw) val spawnDistance = 2 val spawnVelocity = 1.0 this.addParticle( 200, // position pos.x + look.x * spawnDistance, pos.y + look.y * spawnDistance, pos.z + look.z * spawnDistance, // previous position pos.x + look.x * spawnDistance, pos.y + look.y * spawnDistance, pos.z + look.z * spawnDistance, // velocity look.x * spawnVelocity, look.y * spawnVelocity, look.z * spawnVelocity, // color Math.random() * 0.1, Math.random() * 0.1, Math.random() * 0.1, 1.0 ) } fun getVectorForRotation(pitch: Float, yaw: Float): Vec3d { val f = pitch * (Math.PI.toFloat() / 180f) val f1 = -yaw * (Math.PI.toFloat() / 180f) val f2 = MathHelper.cos(f1) val f3 = MathHelper.sin(f1) val f4 = MathHelper.cos(f) val f5 = MathHelper.sin(f) return Vec3d((f3 * f4).toDouble(), (-f5).toDouble(), (f2 * f4).toDouble()) } }
lgpl-3.0
43795b2aeae9fc2aae90e6dea6ea06f1
32.618557
114
0.553067
4.306473
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/fixes/ConvertLetDeclTypeFix.kt
2
1394
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator.fixes import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.ide.presentation.renderInsertionSafe import org.rust.lang.core.psi.RsLetDecl import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.types.ty.Ty /** * Change the declared type of a local variable. */ class ConvertLetDeclTypeFix( decl: RsLetDecl, private val fixText: String, @SafeFieldForPreview private val ty: Ty ) : LocalQuickFixAndIntentionActionOnPsiElement(decl) { override fun getFamilyName(): String = "Convert type of local variable" override fun getText(): String = fixText override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val decl = startElement as? RsLetDecl ?: return val factory = RsPsiFactory(project) val type = factory.tryCreateType(ty.renderInsertionSafe()) ?: return decl.typeReference?.replace(type) } }
mit
6c8a787f4639b975902500bd7665f786
30.681818
78
0.741033
4.411392
false
false
false
false
petropavel13/2photo-android
TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/views/AuthorItemView.kt
1
1437
package com.github.petropavel13.twophoto.views import android.content.Context import android.net.Uri import android.util.AttributeSet import android.widget.FrameLayout import android.widget.TextView import com.facebook.drawee.view.SimpleDraweeView import com.github.petropavel13.twophoto.R import com.github.petropavel13.twophoto.model.Post /** * Created by petropavel on 14/04/15. */ class AuthorItemView: FrameLayout { var avatarImageView: SimpleDraweeView? = null var nameTextView: TextView? = null override fun onFinishInflate() { super.onFinishInflate() avatarImageView = findViewById(R.id.post_detail_author_avatar_image_view) as? SimpleDraweeView nameTextView = findViewById(R.id.post_detail_author_name_text_view) as? TextView } constructor(ctx: Context): super(ctx) { } constructor(ctx: Context, attrs: AttributeSet): super(ctx, attrs) { } constructor(ctx: Context, attrs: AttributeSet, defStyleAttr: Int): super(ctx, attrs, defStyleAttr) { } constructor(ctx: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int): super(ctx, attrs, defStyleAttr, defStyleRes) { } private var _author = Post.Author() var author: Post.Author get() = _author set(newValue) { _author = newValue nameTextView?.setText(newValue.name) avatarImageView?.setImageURI(Uri.parse(newValue.avatar_url)) } }
mit
c1274bba68f36fbc4a868dc3356dee32
30.26087
137
0.716771
4.226471
false
false
false
false
hellenxu/testing
UnitTestApp/app/src/test/java/ca/six/unittestapp/kt/OnePresenterTest.kt
1
5322
package ca.six.unittestapp.kt import ca.six.unittestapp.rules.CustomSchedulersRule import io.reactivex.Flowable import io.reactivex.exceptions.MissingBackpressureException import io.reactivex.observers.TestObserver import io.reactivex.processors.PublishProcessor import io.reactivex.schedulers.Schedulers import io.reactivex.schedulers.TestScheduler import io.reactivex.subscribers.TestSubscriber import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mockito import java.util.concurrent.TimeUnit /** * @CopyRight six.ca * Created by Heavens on 2018-10-25. */ class OnePresenterTest { private lateinit var model: OneModel private lateinit var view: OneView private lateinit var presenter: OnePresenter private val items = ArrayList<OneItem>() private val testScheduler = TestScheduler() @Before fun setUp() { model = Mockito.mock(OneModel::class.java) view = Mockito.mock(OneView::class.java) presenter = OnePresenter(model, view, testScheduler, testScheduler) for (i in 0..5) { items.add(OneItem(i, "brand: $i")) } } @Test fun loadItems() { Mockito.doReturn(Flowable.just(items).toObservable()).`when`(model).fetch() presenter.loadItems() testScheduler.triggerActions() //simulate items emmit Mockito.verify(model).fetch() Mockito.verify(view).updateView(items) } //rx2.0 what's new in testing @Test fun newFeatures() { Flowable.range(1, 3) .test() .assertResult(1, 2, 3) } @Test fun requestMore() { Flowable.range(5, 10) .test(0) .assertNoValues() .requestMore(1) .assertValue(5) .requestMore(2) .assertValues(5, 6, 7) } @Test fun assertException() { val publishProcessor = PublishProcessor.create<Int>() val testSubscriber = publishProcessor.test(0) testSubscriber.request(1) publishProcessor.onNext(1) publishProcessor.onNext(2) testSubscriber.assertFailure(MissingBackpressureException::class.java, 1) } @Test fun asynchronousSource() { Flowable.just(1) .subscribeOn(Schedulers.single()) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1) } //failed test: OnErrorNotImplementedException // @Test // fun getItems() { // val oneModel = OneModel() // oneModel.fetch() // .subscribe { // assertEquals(0, it.size) // } // } @Test fun getItems() { val items = ArrayList<OneItem>() val oneModel = OneModel() oneModel.fetch() .subscribe { items.addAll(it) } assertEquals(11, items.size) } @Test fun observerTest() { val testObserver = TestObserver.create<Int>() testObserver.onNext(1) testObserver.onNext(3) testObserver.onNext(7) testObserver.assertValues(1, 3, 7) testObserver.assertNotComplete() testObserver.onComplete() testObserver.assertComplete() } @Test fun testSubscriber() { val testSubscriber = TestSubscriber.create<String>() Flowable.just("!", "432", "erw", "wrou", " mm") .subscribe(testSubscriber) assertTrue(testSubscriber.hasSubscription()) testSubscriber.assertValueCount(5) testSubscriber.assertNever("test") testSubscriber.assertValues("!", "432", "erw", "wrou", " mm") testSubscriber.assertComplete() } @Test fun testBuffer() { val testSubscriber = TestSubscriber.create<List<String>>() Flowable.just("1", "3", "5", "7") .buffer(2) .subscribe(testSubscriber) assertTrue(testSubscriber.hasSubscription()) testSubscriber.assertValueCount(2) testSubscriber.assertValues(arrayListOf("1", "3"), arrayListOf("5", "7")) testSubscriber.assertTerminated() } @Rule @JvmField val rule = CustomSchedulersRule() @Test fun interval() { val testSubscriber = TestSubscriber.create<Long>() Flowable.interval(1, TimeUnit.SECONDS) .take(10) .subscribe(testSubscriber) testSubscriber.assertValueCount(10) testSubscriber.assertTerminated() } @Test fun intervalWithScheduler() { val testSubscriber = TestSubscriber.create<Long>() val testScheduler = TestScheduler() Flowable.interval(1, TimeUnit.SECONDS, testScheduler) .take(10) .subscribe(testSubscriber) testScheduler.advanceTimeBy(3, TimeUnit.SECONDS) testSubscriber.assertValueCount(3) testSubscriber.assertValues(0, 1, 2) testSubscriber.assertNotTerminated() testScheduler.advanceTimeBy(5, TimeUnit.SECONDS) testSubscriber.assertValueCount(8) testSubscriber.assertValues(0, 1, 2, 3, 4, 5, 6, 7) testSubscriber.assertNotTerminated() } }
apache-2.0
215b0a7859b808991ba44d54719e56fd
27.61828
83
0.616122
4.599827
false
true
false
false
androidx/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/text/matchers/BitmapSubject.kt
3
2099
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text.matchers import android.graphics.Bitmap import com.google.common.truth.FailureMetadata import com.google.common.truth.Subject import com.google.common.truth.Subject.Factory /** * Truth extension for Bitmap. */ internal class BitmapSubject private constructor( failureMetadata: FailureMetadata?, private val subject: Bitmap? ) : Subject(failureMetadata, subject) { companion object { internal val SUBJECT_FACTORY: Factory<BitmapSubject?, Bitmap?> = Factory { failureMetadata, subject -> BitmapSubject(failureMetadata, subject) } } /** * Checks the equality of two [Bitmap]s. * * @param bitmap the [Bitmap] to be matched. */ fun isEqualToBitmap(bitmap: Bitmap) { if (subject == bitmap) return check("isNotNull()").that(subject).isNotNull() check("sameAs()").that(subject!!.sameAs(bitmap)).isTrue() } /** * Checks the inequality of two [Bitmap]s. * * @param bitmap the [Bitmap] to be matched. */ fun isNotEqualToBitmap(bitmap: Bitmap) { if (subject != bitmap) return check("sameAs()").that(subject.sameAs(bitmap)).isFalse() } override fun actualCustomStringRepresentation(): String { return if (subject != null) { "($subject ${subject.width}x${subject.height} ${subject.config.name})" } else { super.actualCustomStringRepresentation() } } }
apache-2.0
528dbc0d0e372cb7b81a03e6311517d8
31.307692
91
0.676989
4.327835
false
false
false
false
androidx/androidx
compose/foundation/foundation-layout/src/commonMain/kotlin/androidx/compose/foundation/layout/Padding.kt
3
14490
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.layout import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.layout.LayoutModifier import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.MeasureScope import androidx.compose.ui.Modifier import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.constrainHeight import androidx.compose.ui.unit.constrainWidth import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.offset /** * Apply additional space along each edge of the content in [Dp]: [start], [top], [end] and * [bottom]. The start and end edges will be determined by the current [LayoutDirection]. * Padding is applied before content measurement and takes precedence; content may only be as large * as the remaining space. * * Negative padding is not permitted — it will cause [IllegalArgumentException]. * See [Modifier.offset]. * * Example usage: * @sample androidx.compose.foundation.layout.samples.PaddingModifier */ @Stable fun Modifier.padding( start: Dp = 0.dp, top: Dp = 0.dp, end: Dp = 0.dp, bottom: Dp = 0.dp ) = this.then( PaddingModifier( start = start, top = top, end = end, bottom = bottom, rtlAware = true, inspectorInfo = debugInspectorInfo { name = "padding" properties["start"] = start properties["top"] = top properties["end"] = end properties["bottom"] = bottom } ) ) /** * Apply [horizontal] dp space along the left and right edges of the content, and [vertical] dp * space along the top and bottom edges. * Padding is applied before content measurement and takes precedence; content may only be as large * as the remaining space. * * Negative padding is not permitted — it will cause [IllegalArgumentException]. * See [Modifier.offset]. * * Example usage: * @sample androidx.compose.foundation.layout.samples.SymmetricPaddingModifier */ @Stable fun Modifier.padding( horizontal: Dp = 0.dp, vertical: Dp = 0.dp ) = this.then( PaddingModifier( start = horizontal, top = vertical, end = horizontal, bottom = vertical, rtlAware = true, inspectorInfo = debugInspectorInfo { name = "padding" properties["horizontal"] = horizontal properties["vertical"] = vertical } ) ) /** * Apply [all] dp of additional space along each edge of the content, left, top, right and bottom. * Padding is applied before content measurement and takes precedence; content may only be as large * as the remaining space. * * Negative padding is not permitted — it will cause [IllegalArgumentException]. * See [Modifier.offset]. * * Example usage: * @sample androidx.compose.foundation.layout.samples.PaddingAllModifier */ @Stable fun Modifier.padding(all: Dp) = this.then( PaddingModifier( start = all, top = all, end = all, bottom = all, rtlAware = true, inspectorInfo = debugInspectorInfo { name = "padding" value = all } ) ) /** * Apply [PaddingValues] to the component as additional space along each edge of the content's left, * top, right and bottom. Padding is applied before content measurement and takes precedence; * content may only be as large as the remaining space. * * Negative padding is not permitted — it will cause [IllegalArgumentException]. * See [Modifier.offset]. * * Example usage: * @sample androidx.compose.foundation.layout.samples.PaddingValuesModifier */ @Stable fun Modifier.padding(paddingValues: PaddingValues) = this.then( PaddingValuesModifier( paddingValues = paddingValues, inspectorInfo = debugInspectorInfo { name = "padding" properties["paddingValues"] = paddingValues } ) ) /** * Apply additional space along each edge of the content in [Dp]: [left], [top], [right] and * [bottom]. These paddings are applied without regard to the current [LayoutDirection], see * [padding] to apply relative paddings. Padding is applied before content measurement and takes * precedence; content may only be as large as the remaining space. * * Negative padding is not permitted — it will cause [IllegalArgumentException]. * See [Modifier.offset]. * * Example usage: * @sample androidx.compose.foundation.layout.samples.AbsolutePaddingModifier */ @Stable fun Modifier.absolutePadding( left: Dp = 0.dp, top: Dp = 0.dp, right: Dp = 0.dp, bottom: Dp = 0.dp ) = this.then( PaddingModifier( start = left, top = top, end = right, bottom = bottom, rtlAware = false, inspectorInfo = debugInspectorInfo { name = "absolutePadding" properties["left"] = left properties["top"] = top properties["right"] = right properties["bottom"] = bottom } ) ) /** * Describes a padding to be applied along the edges inside a box. * See the [PaddingValues] factories and [Absolute] for convenient ways to * build [PaddingValues]. */ @Stable interface PaddingValues { /** * The padding to be applied along the left edge inside a box. */ fun calculateLeftPadding(layoutDirection: LayoutDirection): Dp /** * The padding to be applied along the top edge inside a box. */ fun calculateTopPadding(): Dp /** * The padding to be applied along the right edge inside a box. */ fun calculateRightPadding(layoutDirection: LayoutDirection): Dp /** * The padding to be applied along the bottom edge inside a box. */ fun calculateBottomPadding(): Dp /** * Describes an absolute (RTL unaware) padding to be applied along the edges inside a box. */ @Immutable class Absolute( @Stable private val left: Dp = 0.dp, @Stable private val top: Dp = 0.dp, @Stable private val right: Dp = 0.dp, @Stable private val bottom: Dp = 0.dp ) : PaddingValues { override fun calculateLeftPadding(layoutDirection: LayoutDirection) = left override fun calculateTopPadding() = top override fun calculateRightPadding(layoutDirection: LayoutDirection) = right override fun calculateBottomPadding() = bottom override fun equals(other: Any?): Boolean { if (other !is Absolute) return false return left == other.left && top == other.top && right == other.right && bottom == other.bottom } override fun hashCode() = ((left.hashCode() * 31 + top.hashCode()) * 31 + right.hashCode()) * 31 + bottom.hashCode() override fun toString() = "PaddingValues.Absolute(left=$left, top=$top, right=$right, bottom=$bottom)" } } /** * The padding to be applied along the start edge inside a box: along the left edge if * the layout direction is LTR, or along the right edge for RTL. */ @Stable fun PaddingValues.calculateStartPadding(layoutDirection: LayoutDirection) = if (layoutDirection == LayoutDirection.Ltr) { calculateLeftPadding(layoutDirection) } else { calculateRightPadding(layoutDirection) } /** * The padding to be applied along the end edge inside a box: along the right edge if * the layout direction is LTR, or along the left edge for RTL. */ @Stable fun PaddingValues.calculateEndPadding(layoutDirection: LayoutDirection) = if (layoutDirection == LayoutDirection.Ltr) { calculateRightPadding(layoutDirection) } else { calculateLeftPadding(layoutDirection) } /** * Creates a padding of [all] dp along all 4 edges. */ @Stable fun PaddingValues(all: Dp): PaddingValues = PaddingValuesImpl(all, all, all, all) /** * Creates a padding of [horizontal] dp along the left and right edges, and of [vertical] * dp along the top and bottom edges. */ @Stable fun PaddingValues(horizontal: Dp = 0.dp, vertical: Dp = 0.dp): PaddingValues = PaddingValuesImpl(horizontal, vertical, horizontal, vertical) /** * Creates a padding to be applied along the edges inside a box. In LTR contexts [start] will * be applied along the left edge and [end] will be applied along the right edge. In RTL contexts, * [start] will correspond to the right edge and [end] to the left. */ @Stable fun PaddingValues( start: Dp = 0.dp, top: Dp = 0.dp, end: Dp = 0.dp, bottom: Dp = 0.dp ): PaddingValues = PaddingValuesImpl(start, top, end, bottom) @Immutable internal class PaddingValuesImpl( @Stable val start: Dp = 0.dp, @Stable val top: Dp = 0.dp, @Stable val end: Dp = 0.dp, @Stable val bottom: Dp = 0.dp ) : PaddingValues { override fun calculateLeftPadding(layoutDirection: LayoutDirection) = if (layoutDirection == LayoutDirection.Ltr) start else end override fun calculateTopPadding() = top override fun calculateRightPadding(layoutDirection: LayoutDirection) = if (layoutDirection == LayoutDirection.Ltr) end else start override fun calculateBottomPadding() = bottom override fun equals(other: Any?): Boolean { if (other !is PaddingValuesImpl) return false return start == other.start && top == other.top && end == other.end && bottom == other.bottom } override fun hashCode() = ((start.hashCode() * 31 + top.hashCode()) * 31 + end.hashCode()) * 31 + bottom.hashCode() override fun toString() = "PaddingValues(start=$start, top=$top, end=$end, bottom=$bottom)" } private class PaddingModifier( val start: Dp = 0.dp, val top: Dp = 0.dp, val end: Dp = 0.dp, val bottom: Dp = 0.dp, val rtlAware: Boolean, inspectorInfo: InspectorInfo.() -> Unit ) : LayoutModifier, InspectorValueInfo(inspectorInfo) { init { require( (start.value >= 0f || start == Dp.Unspecified) && (top.value >= 0f || top == Dp.Unspecified) && (end.value >= 0f || end == Dp.Unspecified) && (bottom.value >= 0f || bottom == Dp.Unspecified) ) { "Padding must be non-negative" } } override fun MeasureScope.measure( measurable: Measurable, constraints: Constraints ): MeasureResult { val horizontal = start.roundToPx() + end.roundToPx() val vertical = top.roundToPx() + bottom.roundToPx() val placeable = measurable.measure(constraints.offset(-horizontal, -vertical)) val width = constraints.constrainWidth(placeable.width + horizontal) val height = constraints.constrainHeight(placeable.height + vertical) return layout(width, height) { if (rtlAware) { placeable.placeRelative(start.roundToPx(), top.roundToPx()) } else { placeable.place(start.roundToPx(), top.roundToPx()) } } } override fun hashCode(): Int { var result = start.hashCode() result = 31 * result + top.hashCode() result = 31 * result + end.hashCode() result = 31 * result + bottom.hashCode() result = 31 * result + rtlAware.hashCode() return result } override fun equals(other: Any?): Boolean { val otherModifier = other as? PaddingModifier ?: return false return start == otherModifier.start && top == otherModifier.top && end == otherModifier.end && bottom == otherModifier.bottom && rtlAware == otherModifier.rtlAware } } private class PaddingValuesModifier( val paddingValues: PaddingValues, inspectorInfo: InspectorInfo.() -> Unit ) : LayoutModifier, InspectorValueInfo(inspectorInfo) { override fun MeasureScope.measure( measurable: Measurable, constraints: Constraints ): MeasureResult { require( paddingValues.calculateLeftPadding(layoutDirection) >= 0.dp && paddingValues.calculateTopPadding() >= 0.dp && paddingValues.calculateRightPadding(layoutDirection) >= 0.dp && paddingValues.calculateBottomPadding() >= 0.dp ) { "Padding must be non-negative" } val horizontal = paddingValues.calculateLeftPadding(layoutDirection).roundToPx() + paddingValues.calculateRightPadding(layoutDirection).roundToPx() val vertical = paddingValues.calculateTopPadding().roundToPx() + paddingValues.calculateBottomPadding().roundToPx() val placeable = measurable.measure(constraints.offset(-horizontal, -vertical)) val width = constraints.constrainWidth(placeable.width + horizontal) val height = constraints.constrainHeight(placeable.height + vertical) return layout(width, height) { placeable.place( paddingValues.calculateLeftPadding(layoutDirection).roundToPx(), paddingValues.calculateTopPadding().roundToPx() ) } } override fun hashCode() = paddingValues.hashCode() override fun equals(other: Any?): Boolean { val otherModifier = other as? PaddingValuesModifier ?: return false return paddingValues == otherModifier.paddingValues } }
apache-2.0
2cd5481253671583dbadea2ecf46e261
32.287356
100
0.65297
4.577932
false
false
false
false
yschimke/okhttp
okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/RealCall.kt
1
18093
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.connection import java.io.IOException import java.io.InterruptedIOException import java.lang.ref.WeakReference import java.net.Socket import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.ExecutorService import java.util.concurrent.RejectedExecutionException import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLSocketFactory import okhttp3.Address import okhttp3.Call import okhttp3.Callback import okhttp3.CertificatePinner import okhttp3.EventListener import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.internal.assertThreadDoesntHoldLock import okhttp3.internal.assertThreadHoldsLock import okhttp3.internal.cache.CacheInterceptor import okhttp3.internal.closeQuietly import okhttp3.internal.http.BridgeInterceptor import okhttp3.internal.http.CallServerInterceptor import okhttp3.internal.http.RealInterceptorChain import okhttp3.internal.http.RetryAndFollowUpInterceptor import okhttp3.internal.platform.Platform import okhttp3.internal.threadName import okio.AsyncTimeout import okio.Timeout /** * Bridge between OkHttp's application and network layers. This class exposes high-level application * layer primitives: connections, requests, responses, and streams. * * This class supports [asynchronous canceling][cancel]. This is intended to have the smallest * blast radius possible. If an HTTP/2 stream is active, canceling will cancel that stream but not * the other streams sharing its connection. But if the TLS handshake is still in progress then * canceling may break the entire connection. */ class RealCall( val client: OkHttpClient, /** The application's original request unadulterated by redirects or auth headers. */ val originalRequest: Request, val forWebSocket: Boolean ) : Call { private val connectionPool: RealConnectionPool = client.connectionPool.delegate internal val eventListener: EventListener = client.eventListenerFactory.create(this) private val timeout = object : AsyncTimeout() { override fun timedOut() { cancel() } }.apply { timeout(client.callTimeoutMillis.toLong(), MILLISECONDS) } private val executed = AtomicBoolean() // These properties are only accessed by the thread executing the call. /** Initialized in [callStart]. */ private var callStackTrace: Any? = null /** Finds an exchange to send the next request and receive the next response. */ private var routePlanner: RoutePlanner? = null var connection: RealConnection? = null private set private var timeoutEarlyExit = false /** * This is the same value as [exchange], but scoped to the execution of the network interceptors. * The [exchange] field is assigned to null when its streams end, which may be before or after the * network interceptors return. */ internal var interceptorScopedExchange: Exchange? = null private set // These properties are guarded by this. They are typically only accessed by the thread executing // the call, but they may be accessed by other threads for duplex requests. /** True if this call still has a request body open. */ private var requestBodyOpen = false /** True if this call still has a response body open. */ private var responseBodyOpen = false /** True if there are more exchanges expected for this call. */ private var expectMoreExchanges = true // These properties are accessed by canceling threads. Any thread can cancel a call, and once it's // canceled it's canceled forever. @Volatile private var canceled = false @Volatile private var exchange: Exchange? = null internal val plansToCancel = CopyOnWriteArrayList<RoutePlanner.Plan>() override fun timeout(): Timeout = timeout @SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state. override fun clone(): Call = RealCall(client, originalRequest, forWebSocket) override fun request(): Request = originalRequest /** * Immediately closes the socket connection if it's currently held. Use this to interrupt an * in-flight request from any thread. It's the caller's responsibility to close the request body * and response body streams; otherwise resources may be leaked. * * This method is safe to be called concurrently, but provides limited guarantees. If a transport * layer connection has been established (such as a HTTP/2 stream) that is terminated. Otherwise * if a socket connection is being established, that is terminated. */ override fun cancel() { if (canceled) return // Already canceled. canceled = true exchange?.cancel() for (plan in plansToCancel) { plan.cancel() } eventListener.canceled(this) } override fun isCanceled(): Boolean = canceled override fun execute(): Response { check(executed.compareAndSet(false, true)) { "Already Executed" } timeout.enter() callStart() try { client.dispatcher.executed(this) return getResponseWithInterceptorChain() } finally { client.dispatcher.finished(this) } } override fun enqueue(responseCallback: Callback) { check(executed.compareAndSet(false, true)) { "Already Executed" } callStart() client.dispatcher.enqueue(AsyncCall(responseCallback)) } override fun isExecuted(): Boolean = executed.get() private fun callStart() { this.callStackTrace = Platform.get().getStackTraceForCloseable("response.body().close()") eventListener.callStart(this) } @Throws(IOException::class) internal fun getResponseWithInterceptorChain(): Response { // Build a full stack of interceptors. val interceptors = mutableListOf<Interceptor>() interceptors += client.interceptors interceptors += RetryAndFollowUpInterceptor(client) interceptors += BridgeInterceptor(client.cookieJar) interceptors += CacheInterceptor(client.cache) interceptors += ConnectInterceptor if (!forWebSocket) { interceptors += client.networkInterceptors } interceptors += CallServerInterceptor(forWebSocket) val chain = RealInterceptorChain( call = this, interceptors = interceptors, index = 0, exchange = null, request = originalRequest, connectTimeoutMillis = client.connectTimeoutMillis, readTimeoutMillis = client.readTimeoutMillis, writeTimeoutMillis = client.writeTimeoutMillis ) var calledNoMoreExchanges = false try { val response = chain.proceed(originalRequest) if (isCanceled()) { response.closeQuietly() throw IOException("Canceled") } return response } catch (e: IOException) { calledNoMoreExchanges = true throw noMoreExchanges(e) as Throwable } finally { if (!calledNoMoreExchanges) { noMoreExchanges(null) } } } /** * Prepare for a potential trip through all of this call's network interceptors. This prepares to * find an exchange to carry the request. * * Note that an exchange will not be needed if the request is satisfied by the cache. * * @param newRoutePlanner true if this is not a retry and new routing can be performed. */ fun enterNetworkInterceptorExchange( request: Request, newRoutePlanner: Boolean, chain: RealInterceptorChain, ) { check(interceptorScopedExchange == null) synchronized(this) { check(!responseBodyOpen) { "cannot make a new request because the previous response is still open: " + "please call response.close()" } check(!requestBodyOpen) } if (newRoutePlanner) { this.routePlanner = RealRoutePlanner( client, createAddress(request.url), this, chain, ) } } /** Finds a new or pooled connection to carry a forthcoming request and response. */ internal fun initExchange(chain: RealInterceptorChain): Exchange { synchronized(this) { check(expectMoreExchanges) { "released" } check(!responseBodyOpen) check(!requestBodyOpen) } val routePlanner = this.routePlanner!! val connection = when { client.fastFallback -> FastFallbackExchangeFinder(routePlanner, client.taskRunner).find() else -> ExchangeFinder(routePlanner).find() } val codec = connection.newCodec(client, chain) val result = Exchange(this, eventListener, routePlanner, codec) this.interceptorScopedExchange = result this.exchange = result synchronized(this) { this.requestBodyOpen = true this.responseBodyOpen = true } if (canceled) throw IOException("Canceled") return result } fun acquireConnectionNoEvents(connection: RealConnection) { connection.assertThreadHoldsLock() check(this.connection == null) this.connection = connection connection.calls.add(CallReference(this, callStackTrace)) } /** * Releases resources held with the request or response of [exchange]. This should be called when * the request completes normally or when it fails due to an exception, in which case [e] should * be non-null. * * If the exchange was canceled or timed out, this will wrap [e] in an exception that provides * that additional context. Otherwise [e] is returned as-is. */ internal fun <E : IOException?> messageDone( exchange: Exchange, requestDone: Boolean, responseDone: Boolean, e: E ): E { if (exchange != this.exchange) return e // This exchange was detached violently! var bothStreamsDone = false var callDone = false synchronized(this) { if (requestDone && requestBodyOpen || responseDone && responseBodyOpen) { if (requestDone) requestBodyOpen = false if (responseDone) responseBodyOpen = false bothStreamsDone = !requestBodyOpen && !responseBodyOpen callDone = !requestBodyOpen && !responseBodyOpen && !expectMoreExchanges } } if (bothStreamsDone) { this.exchange = null this.connection?.incrementSuccessCount() } if (callDone) { return callDone(e) } return e } internal fun noMoreExchanges(e: IOException?): IOException? { var callDone = false synchronized(this) { if (expectMoreExchanges) { expectMoreExchanges = false callDone = !requestBodyOpen && !responseBodyOpen } } if (callDone) { return callDone(e) } return e } /** * Complete this call. This should be called once these properties are all false: * [requestBodyOpen], [responseBodyOpen], and [expectMoreExchanges]. * * This will release the connection if it is still held. * * It will also notify the listener that the call completed; either successfully or * unsuccessfully. * * If the call was canceled or timed out, this will wrap [e] in an exception that provides that * additional context. Otherwise [e] is returned as-is. */ private fun <E : IOException?> callDone(e: E): E { assertThreadDoesntHoldLock() val connection = this.connection if (connection != null) { connection.assertThreadDoesntHoldLock() val toClose: Socket? = synchronized(connection) { releaseConnectionNoEvents() // Sets this.connection to null. } if (this.connection == null) { toClose?.closeQuietly() eventListener.connectionReleased(this, connection) } else { check(toClose == null) // If we still have a connection we shouldn't be closing any sockets. } } val result = timeoutExit(e) if (e != null) { eventListener.callFailed(this, result!!) } else { eventListener.callEnd(this) } return result } /** * Remove this call from the connection's list of allocations. Returns a socket that the caller * should close. */ internal fun releaseConnectionNoEvents(): Socket? { val connection = this.connection!! connection.assertThreadHoldsLock() val calls = connection.calls val index = calls.indexOfFirst { it.get() == this@RealCall } check(index != -1) calls.removeAt(index) this.connection = null if (calls.isEmpty()) { connection.idleAtNs = System.nanoTime() if (connectionPool.connectionBecameIdle(connection)) { return connection.socket() } } return null } private fun <E : IOException?> timeoutExit(cause: E): E { if (timeoutEarlyExit) return cause if (!timeout.exit()) return cause val e = InterruptedIOException("timeout") if (cause != null) e.initCause(cause) @Suppress("UNCHECKED_CAST") // E is either IOException or IOException? return e as E } /** * Stops applying the timeout before the call is entirely complete. This is used for WebSockets * and duplex calls where the timeout only applies to the initial setup. */ fun timeoutEarlyExit() { check(!timeoutEarlyExit) timeoutEarlyExit = true timeout.exit() } /** * @param closeExchange true if the current exchange should be closed because it will not be used. * This is usually due to either an exception or a retry. */ internal fun exitNetworkInterceptorExchange(closeExchange: Boolean) { synchronized(this) { check(expectMoreExchanges) { "released" } } if (closeExchange) { exchange?.detachWithViolence() } interceptorScopedExchange = null } private fun createAddress(url: HttpUrl): Address { var sslSocketFactory: SSLSocketFactory? = null var hostnameVerifier: HostnameVerifier? = null var certificatePinner: CertificatePinner? = null if (url.isHttps) { sslSocketFactory = client.sslSocketFactory hostnameVerifier = client.hostnameVerifier certificatePinner = client.certificatePinner } return Address( uriHost = url.host, uriPort = url.port, dns = client.dns, socketFactory = client.socketFactory, sslSocketFactory = sslSocketFactory, hostnameVerifier = hostnameVerifier, certificatePinner = certificatePinner, proxyAuthenticator = client.proxyAuthenticator, proxy = client.proxy, protocols = client.protocols, connectionSpecs = client.connectionSpecs, proxySelector = client.proxySelector ) } fun retryAfterFailure(): Boolean = routePlanner!!.hasFailure() && routePlanner!!.hasMoreRoutes() /** * Returns a string that describes this call. Doesn't include a full URL as that might contain * sensitive information. */ private fun toLoggableString(): String { return ((if (isCanceled()) "canceled " else "") + (if (forWebSocket) "web socket" else "call") + " to " + redactedUrl()) } internal fun redactedUrl(): String = originalRequest.url.redact() inner class AsyncCall( private val responseCallback: Callback ) : Runnable { @Volatile var callsPerHost = AtomicInteger(0) private set fun reuseCallsPerHostFrom(other: AsyncCall) { this.callsPerHost = other.callsPerHost } val host: String get() = originalRequest.url.host val request: Request get() = originalRequest val call: RealCall get() = this@RealCall /** * Attempt to enqueue this async call on [executorService]. This will attempt to clean up * if the executor has been shut down by reporting the call as failed. */ fun executeOn(executorService: ExecutorService) { client.dispatcher.assertThreadDoesntHoldLock() var success = false try { executorService.execute(this) success = true } catch (e: RejectedExecutionException) { val ioException = InterruptedIOException("executor rejected") ioException.initCause(e) noMoreExchanges(ioException) responseCallback.onFailure(this@RealCall, ioException) } finally { if (!success) { client.dispatcher.finished(this) // This call is no longer running! } } } override fun run() { threadName("OkHttp ${redactedUrl()}") { var signalledCallback = false timeout.enter() try { val response = getResponseWithInterceptorChain() signalledCallback = true responseCallback.onResponse(this@RealCall, response) } catch (e: IOException) { if (signalledCallback) { // Do not signal the callback twice! Platform.get().log("Callback failure for ${toLoggableString()}", Platform.INFO, e) } else { responseCallback.onFailure(this@RealCall, e) } } catch (t: Throwable) { cancel() if (!signalledCallback) { val canceledException = IOException("canceled due to $t") canceledException.addSuppressed(t) responseCallback.onFailure(this@RealCall, canceledException) } throw t } finally { client.dispatcher.finished(this) } } } } internal class CallReference( referent: RealCall, /** * Captures the stack trace at the time the Call is executed or enqueued. This is helpful for * identifying the origin of connection leaks. */ val callStackTrace: Any? ) : WeakReference<RealCall>(referent) }
apache-2.0
4cdc8741776052bb546fa1fe78949238
31.19395
100
0.697397
4.661943
false
false
false
false
OpenConference/DroidconBerlin2017
businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/database/SessionDateTimeComparator.kt
1
1085
package com.openconference.model.database import de.droidcon.berlin2018.model.Session import java.util.Comparator /** * * * @author Hannes Dorfmann */ class SessionDateTimeComparator : Comparator<Session> { override fun compare(lhs: Session, rhs: Session): Int { if (lhs.startTime() == null && rhs.startTime() == null) { return 0 } if (lhs.startTime() == null && rhs.startTime() != null){ return 1 } if (lhs.startTime() != null && rhs.startTime() == null){ return -1 } val dateComparisonResult = lhs.startTime()!!.compareTo(rhs.startTime()) if (dateComparisonResult != 0){ return dateComparisonResult } val lhsLocationName = lhs.locationName() val rhsLocationName = rhs.locationName() if (lhsLocationName == null && rhsLocationName == null){ return 0 } if (lhsLocationName == null && rhsLocationName != null){ return 1 } if (lhsLocationName != null && rhsLocationName == null){ return -1 } return lhsLocationName!!.compareTo(rhsLocationName!!) } }
apache-2.0
5b49ee41cd25273313339ea66ac4915c
20.27451
76
0.63318
4.09434
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/SliderAdapter.kt
2
1476
package ru.fantlab.android.ui.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.swiperefreshlayout.widget.CircularProgressDrawable import androidx.viewpager.widget.PagerAdapter import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.slider_item_layout.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.SliderModel class SliderAdapter(private var mContext: Context, private val photoSlide: ArrayList<SliderModel>?) : PagerAdapter() { override fun isViewFromObject(view: View, `object`: Any): Boolean { return view == `object` } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } override fun getCount(): Int { return photoSlide!!.size } override fun instantiateItem(container: ViewGroup, position: Int): Any { val view: View = LayoutInflater.from(mContext).inflate(R.layout.slider_item_layout, container, false) val circularProgressDrawable = CircularProgressDrawable(view.context) circularProgressDrawable.strokeWidth = 5f circularProgressDrawable.centerRadius = 30f circularProgressDrawable.start() Glide.with(mContext) .load(photoSlide?.get(position)?.imageUrl) .placeholder(circularProgressDrawable) .into(view.imageView) view.imageText.text = photoSlide?.get(position)?.text container.addView(view, 0) return view } }
gpl-3.0
3f6e58f60147edf03358f49326bbc876
33.348837
118
0.788618
3.946524
false
false
false
false
JakeWharton/Reagent
reagent/common/src/main/kotlin/reagent/operator/iterator.kt
1
921
package reagent.operator import reagent.Observable import reagent.Task interface SuspendableIterator<out I> { suspend operator fun hasNext(): Boolean suspend operator fun next(): I } operator fun <I> Observable<I>.iterator(): SuspendableIterator<I> = ObservableIterator(this) operator fun <I> Task<I>.iterator(): SuspendableIterator<I> = TaskIterator(this) internal class ObservableIterator<out I>(private val observable: Observable<I>) : SuspendableIterator<I> { // TODO i_have_no_idea_what_im_doing.gif override suspend fun hasNext() = TODO() override suspend fun next() = TODO() } internal class TaskIterator<out I>(private val task: Task<I>) : SuspendableIterator<I> { private var done = false override suspend fun hasNext() = !done override suspend fun next(): I { if (done) throw IllegalStateException("Must call hasNext() before next()") done = true return task.produce() } }
apache-2.0
c8336ac6cb3ef33a0e954458a98eb50a
28.709677
106
0.731813
4.021834
false
false
false
false
daniloqueiroz/nsync
src/main/kotlin/nsync/storage/StorageDriver.kt
1
1679
package nsync.storage import commons.Server import commons.Signal import commons.SignalBus import mu.KotlinLogging import nsync.* import java.nio.file.Path interface StorageDriver { val bus: SignalBus val scheme: String suspend fun syncFile(localFile: Path, folder: SyncFolder) suspend fun deleteFile(localFile: Path, folder: SyncFolder) } class StorageServer(private val bus: SignalBus) : Server(bus, listOf(TransferFile::class, DeleteFile::class)) { private val logger = KotlinLogging.logger {} private val drivers: MutableMap<String, StorageDriver> = mutableMapOf() fun loadDrivers() { // TODO change later to use this https://youtrack.jetbrains.com/issue/KT-14657 listOf(::LocalFileStorage).forEach { val drive = it(bus) // TODO pass this (as StorageController interface to drivers) logger.info { "Adding driver ${drive::class.java.canonicalName} for scheme '${drive.scheme}://'" } drivers[drive.scheme] = drive } } suspend override fun handle(msg: Signal<*>) { val file = msg.payload as RemoteFile drivers[file.folder.schemeRemote]?.let { when (msg) { is TransferFile -> this.transfer(file, it) is DeleteFile -> this.delete(file, it) else -> logger.info { "Unexpected message: $msg" } } } } private suspend fun transfer(file: RemoteFile, driver: StorageDriver) { driver.syncFile(file.localFilePath, file.folder) } private suspend fun delete(file: RemoteFile, driver: StorageDriver) { driver.deleteFile(file.localFilePath, file.folder) } }
gpl-3.0
10cd5f20693524d617969d4ee3cb1185
33.285714
111
0.661703
4.294118
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/viewmodel/ServerDetailFragmentModel.kt
1
2861
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.viewmodel import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.view.View import androidx.core.graphics.drawable.DrawableCompat import net.mm2d.android.upnp.cds.MediaServer import net.mm2d.android.util.ActivityUtils import net.mm2d.android.util.DrawableUtils import net.mm2d.dmsexplorer.Const import net.mm2d.dmsexplorer.R import net.mm2d.dmsexplorer.Repository import net.mm2d.dmsexplorer.log.EventLogger import net.mm2d.dmsexplorer.settings.Settings import net.mm2d.dmsexplorer.view.ContentListActivity import net.mm2d.dmsexplorer.view.adapter.PropertyAdapter import net.mm2d.upnp.Icon /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class ServerDetailFragmentModel( private val context: Context, repository: Repository ) { val collapsedColor: Int val expandedColor: Int val icon: Drawable val title: String val propertyAdapter: PropertyAdapter init { val server = repository.controlPointModel.selectedMediaServer ?: throw IllegalStateException() title = server.friendlyName propertyAdapter = PropertyAdapter.ofServer(context, server) val iconBitmap = createIconBitmap(server.getIcon()) icon = createIconDrawable(context, server, iconBitmap) Settings.get() .themeParams .serverColorExtractor .invoke(server, iconBitmap) expandedColor = server.getIntTag(Const.KEY_TOOLBAR_EXPANDED_COLOR, Color.BLACK) collapsedColor = server.getIntTag(Const.KEY_TOOLBAR_COLLAPSED_COLOR, Color.BLACK) } private fun createIconBitmap(icon: Icon?): Bitmap? { val binary = icon?.binary ?: return null return BitmapFactory.decodeByteArray(binary, 0, binary.size) } private fun createIconDrawable( context: Context, server: MediaServer, icon: Bitmap? ): Drawable { if (icon != null) { return BitmapDrawable(context.resources, icon) } val generator = Settings.get() .themeParams .themeColorGenerator return DrawableUtils.getOrThrow(context, R.drawable.ic_circle).also { it.mutate() DrawableCompat.setTint(it, generator.getIconColor(server.friendlyName)) } } fun onClickFab(view: View) { val intent = ContentListActivity.makeIntent(context) context.startActivity(intent, ActivityUtils.makeScaleUpAnimationBundle(view)) EventLogger.sendSelectServer() } }
mit
30501798b10a5a26e2508c381458cd89
32.081395
89
0.715993
4.304085
false
false
false
false
google/zsldemo
app/src/main/java/com/hadrosaur/zsldemo/ZSLCoordinator.kt
1
3279
/* * Copyright 2019 Google 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 com.hadrosaur.zsldemo import android.hardware.camera2.CaptureResult import android.hardware.camera2.TotalCaptureResult import android.media.Image import android.util.Log import com.hadrosaur.zsldemo.CameraController.recaptureRequest import com.hadrosaur.zsldemo.CameraController.stopRepeating import com.hadrosaur.zsldemo.MainActivity.Companion.Logd class ZSLPair (val image: Image, val result: TotalCaptureResult){ } class ZSLCoordinator { val imageBuffer = CircularImageBuffer() val resultBuffer = CircularResultBuffer() //Returns null if no pair found fun getBestFrame() : ZSLPair? { var bestImage: Image? = null var bestResult = resultBuffer.findBestFrame() if (bestResult != null) { bestImage = imageBuffer.findMatchingImage(bestResult) if (bestImage != null) { return ZSLPair(bestImage, bestResult) } } else { Logd("Best result == null. No good frames found.") } return null } fun capturePhoto(activity: MainActivity, params: CameraParams) { //stopRepeating(params) val bestPair: ZSLPair? = getBestFrame() // listTimestamps() if (bestPair != null) { // Logd("Found a good image/result pair. Doing recapture and saving to disk!") Logd("Doing recapture. Timestamp Image: " + bestPair.image.timestamp + ", timestamp Result: " + bestPair.result.get(CaptureResult.SENSOR_TIMESTAMP)) recaptureRequest(activity, params, bestPair) //Now remove the bestPair from the buffer so we don't try to access the image again imageBuffer.remove(bestPair.image) resultBuffer.remove(bestPair.result) } else { //Do regular capture Logd("No best frame found. Fallback to regular capture.") } } fun listTimestamps() { val resultStamps = ArrayList<Long>() for (result in resultBuffer.buffer) { if (result.get(CaptureResult.SENSOR_TIMESTAMP) != null) resultStamps.add(result.get(CaptureResult.SENSOR_TIMESTAMP)!!) } val imageStamps = ArrayList<Long>() for (image in imageBuffer.buffer) imageStamps.add(image.timestamp) Logd("Listing Timestamps. " + resultStamps.size + " result stamps. " + imageStamps.size + " image stamps.") if (resultStamps.size != imageStamps.size) { Logd("Sizes are different not listing!!") } else { for (i in 0 until resultStamps.size) { Logd("Result: " + resultStamps[i] + " Image: " + imageStamps[i]) } } } }
apache-2.0
6f16d1eedebc26a0f54c5b1110a53646
34.652174
160
0.655993
4.193095
false
false
false
false
robfletcher/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartTaskHandlerTest.kt
1
7188
/* * Copyright 2017 Netflix, 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.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.DefaultStageResolver import com.netflix.spinnaker.orca.TaskResolver import com.netflix.spinnaker.orca.api.pipeline.SkippableTask import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.test.pipeline import com.netflix.spinnaker.orca.api.test.stage import com.netflix.spinnaker.orca.events.TaskComplete import com.netflix.spinnaker.orca.events.TaskStarted import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.q.CompleteTask import com.netflix.spinnaker.orca.q.DummyTask import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.StageDefinitionBuildersProvider import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.orca.q.TasksProvider import com.netflix.spinnaker.orca.q.buildTasks import com.netflix.spinnaker.orca.q.singleTaskStage import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.check import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.doThrow import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.junit.jupiter.api.Assertions.assertThrows import org.springframework.context.ApplicationEventPublisher import org.springframework.core.env.Environment object StartTaskHandlerTest : SubjectSpek<StartTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val publisher: ApplicationEventPublisher = mock() val environment: Environment = mock() val task: DummyTask = mock { on { extensionClass } doReturn DummyTask::class.java on { aliases() } doReturn emptyList<String>() on { isEnabledPropertyName } doReturn SkippableTask.isEnabledPropertyName("DummyTask") } val taskResolver = TaskResolver(TasksProvider(listOf(task))) val stageResolver = DefaultStageResolver(StageDefinitionBuildersProvider(emptyList())) val clock = fixedClock() subject(GROUP) { StartTaskHandler(queue, repository, ContextParameterProcessor(), DefaultStageDefinitionBuilderFactory(stageResolver), publisher, taskResolver, clock, environment) } fun resetMocks() = reset(queue, repository, publisher, environment) describe("when a task starts") { val pipeline = pipeline { stage { type = singleTaskStage.type singleTaskStage.buildTasks(this) } } val message = StartTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1") beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(environment.getProperty("tasks.dummyTask.enabled", Boolean::class.java, true)) doReturn true } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as running") { verify(repository).storeStage( check { it.tasks.first().apply { assertThat(status).isEqualTo(RUNNING) assertThat(startTime).isEqualTo(clock.millis()) } } ) } it("runs the task") { verify(queue).push( RunTask( message.executionType, message.executionId, "foo", message.stageId, message.taskId, DummyTask::class.java ) ) } it("publishes a TaskStarted event") { argumentCaptor<TaskStarted>().apply { verify(publisher).publishEvent(capture()) firstValue.apply { assertThat(executionType).isEqualTo(pipeline.type) assertThat(executionId).isEqualTo(pipeline.id) assertThat(stageId).isEqualTo(message.stageId) assertThat(taskId).isEqualTo(message.taskId) } } } } describe("when a skippable task starts") { val pipeline = pipeline { stage { type = singleTaskStage.type singleTaskStage.buildTasks(this) } } val message = StartTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1") beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(environment.getProperty("tasks.dummyTask.enabled", Boolean::class.java, true)) doReturn false } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as skipped") { verify(repository).storeStage( check { it.tasks.first().apply { assertThat(status).isEqualTo(SKIPPED) assertThat(startTime).isEqualTo(null) } } ) } it("completes the task") { verify(queue).push( CompleteTask( message, SKIPPED ) ) } it("publishes a TaskComplete event") { argumentCaptor<TaskComplete>().apply { verify(publisher).publishEvent(capture()) firstValue.apply { assertThat(executionType).isEqualTo(pipeline.type) assertThat(executionId).isEqualTo(pipeline.id) assertThat(stageId).isEqualTo(message.stageId) assertThat(taskId).isEqualTo(message.taskId) } } } } describe("when the execution repository has a problem") { val pipeline = pipeline { stage { type = singleTaskStage.type singleTaskStage.buildTasks(this) } } val message = StartTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1") beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doThrow NullPointerException() } afterGroup(::resetMocks) it("propagates any exception") { assertThrows(NullPointerException::class.java) { subject.handle(message) } } } })
apache-2.0
b6f0290fdb242cf86f0279bbc6efaa05
32.90566
166
0.715776
4.489694
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/step_quiz_fullscreen_code/ui/dialog/CodeStepQuizFullScreenDialogFragment.kt
2
16204
package org.stepik.android.view.step_quiz_fullscreen_code.ui.dialog import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager import android.widget.RelativeLayout import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.viewpager.widget.ViewPager import com.google.android.material.button.MaterialButton import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlinx.android.synthetic.main.dialog_step_quiz_code_fullscreen.* import kotlinx.android.synthetic.main.layout_step_quiz_code_fullscreen_instruction.view.* import kotlinx.android.synthetic.main.layout_step_quiz_code_fullscreen_playground.view.* import kotlinx.android.synthetic.main.layout_step_quiz_code_fullscreen_run_code.view.* import kotlinx.android.synthetic.main.layout_step_quiz_code_keyboard_extension.* import kotlinx.android.synthetic.main.view_centered_toolbar.* import kotlinx.android.synthetic.main.view_step_quiz_submit_button.view.* import org.stepic.droid.R import org.stepic.droid.base.App import org.stepic.droid.code.ui.CodeEditorLayout import org.stepic.droid.code.util.CodeToolbarUtil import org.stepic.droid.model.code.ProgrammingLanguage import org.stepic.droid.persistence.model.StepPersistentWrapper import org.stepic.droid.ui.adapters.CodeToolbarAdapter import org.stepic.droid.ui.dialogs.ChangeCodeLanguageDialog import org.stepic.droid.ui.dialogs.ProgrammingLanguageChooserDialogFragment import org.stepic.droid.ui.dialogs.ResetCodeDialogFragment import org.stepic.droid.ui.util.setOnKeyboardOpenListener import org.stepic.droid.ui.util.setTintedNavigationIcon import org.stepik.android.presentation.step_quiz_code.StepQuizCodeRunPresenter import org.stepik.android.view.step_quiz_code.ui.delegate.CodeLayoutDelegate import org.stepik.android.view.step_quiz_code.ui.delegate.CodeQuizInstructionDelegate import org.stepik.android.view.step_quiz_code.ui.delegate.CodeStepRunCodeDelegate import org.stepik.android.view.step_quiz_fullscreen_code.ui.adapter.CodeStepQuizFullScreenPagerAdapter import ru.nobird.android.view.base.ui.extension.argument import ru.nobird.android.view.base.ui.extension.hideKeyboard import javax.inject.Inject class CodeStepQuizFullScreenDialogFragment : DialogFragment(), ChangeCodeLanguageDialog.Callback, ProgrammingLanguageChooserDialogFragment.Callback, ResetCodeDialogFragment.Callback { companion object { const val TAG = "CodeStepQuizFullScreenDialogFragment" private const val ARG_LANG = "LANG" private const val ARG_CODE = "CODE" private const val INSTRUCTION_TAB = 0 private const val CODE_TAB = 1 private const val RUN_CODE_TAB = 2 fun newInstance(lang: String, code: String, codeTemplates: Map<String, String>, stepPersistentWrapper: StepPersistentWrapper, lessonTitle: String): DialogFragment = CodeStepQuizFullScreenDialogFragment() .apply { this.lang = lang this.code = code this.codeTemplates = codeTemplates this.stepWrapper = stepPersistentWrapper this.lessonTitle = lessonTitle } } private lateinit var codeLayoutDelegate: CodeLayoutDelegate private var runCodeDelegate: CodeStepRunCodeDelegate? = null private lateinit var instructionsLayout: View private lateinit var playgroundLayout: View private var runCodeLayout: View? = null /** * Code play ground views */ private lateinit var codeLayout: CodeEditorLayout private lateinit var submitButtonSeparator: View private lateinit var codeSubmitFab: FloatingActionButton private lateinit var codeSubmitButton: MaterialButton private lateinit var retryButton: View private lateinit var codeToolbarAdapter: CodeToolbarAdapter // Flag is necessary, because keyboard listener is constantly invoked (probably global layout listener reacts to view changes) private var keyboardShown: Boolean = false /** * Run code views */ private var runCodeActionSeparator: View? = null private var runCodeFab: FloatingActionButton? = null private var runCodeAction: MaterialButton? = null private var lang: String by argument() private var code: String by argument() private var codeTemplates: Map<String, String> by argument() private var lessonTitle: String by argument() private var stepWrapper: StepPersistentWrapper by argument() @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory private val codeRunPresenter: StepQuizCodeRunPresenter by viewModels { viewModelFactory } private fun injectComponent() { App.component() .userCodeRunComponentBuilder() .build() .inject(this) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.setCanceledOnTouchOutside(false) dialog.setCancelable(false) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) return dialog } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NO_TITLE, R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen) injectComponent() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.dialog_step_quiz_code_fullscreen, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) centeredToolbarTitle.text = lessonTitle centeredToolbar.inflateMenu(R.menu.code_playground_menu) centeredToolbar.setNavigationOnClickListener { dismiss() } centeredToolbar.setTintedNavigationIcon(R.drawable.ic_close_dark) centeredToolbar.setOnMenuItemClickListener { item -> if (item?.itemId == R.id.action_reset_code) { val dialog = ResetCodeDialogFragment.newInstance() if (!dialog.isAdded) { dialog.show(childFragmentManager, null) } true } else { false } } if (savedInstanceState != null) { lang = savedInstanceState.getString(ARG_LANG) ?: return code = savedInstanceState.getString(ARG_CODE) ?: return } val isShowRunCode = resolveIsShowRunCode( isRunCodeEnabled = stepWrapper.step.block?.options?.isRunUserCodeAllowed ?: false, hasSamples = stepWrapper.step.block?.options?.samples?.isNotEmpty() ?: false ) initViewPager(isShowRunCode = isShowRunCode) val text = stepWrapper .step .block ?.text ?.takeIf(String::isNotEmpty) instructionsLayout.stepQuizCodeTextContent.setText(text) /** * Code play ground view binding */ submitButtonSeparator = playgroundLayout.submitButtonSeparator codeSubmitFab = playgroundLayout.codeSubmitFab codeSubmitButton = playgroundLayout.stepQuizAction retryButton = playgroundLayout.stepQuizRetry codeLayout = playgroundLayout.codeStepLayout runCodeDelegate = runCodeLayout?.let { layout -> CodeStepRunCodeDelegate( runCodeLayout = layout, codeRunPresenter = codeRunPresenter, fullScreenCodeTabs = fullScreenCodeTabs, codeLayout = codeLayout, context = requireContext(), stepWrapper = stepWrapper ) } runCodeDelegate?.lang = lang /** * Run code view binding */ runCodeActionSeparator = runCodeLayout?.runCodeActionSeparator runCodeFab = runCodeLayout?.runCodeFab runCodeAction = runCodeLayout?.runCodeAction retryButton.isVisible = false setupCodeToolAdapter() setupKeyboardExtension() codeLayoutDelegate = CodeLayoutDelegate( codeContainerView = playgroundLayout, step = stepWrapper.step, codeTemplates = codeTemplates, codeQuizInstructionDelegate = CodeQuizInstructionDelegate(instructionsLayout, false), codeToolbarAdapter = codeToolbarAdapter, onChangeLanguageClicked = ::onChangeLanguageClicked ) codeLayoutDelegate.setLanguage(lang, code) codeLayoutDelegate.setDetailsContentData(lang) fullScreenCodeViewPager.setCurrentItem(CODE_TAB, false) codeSubmitButton.setIconResource(R.drawable.ic_submit_code) codeSubmitButton.iconPadding = requireContext().resources.getDimensionPixelSize(R.dimen.step_quiz_full_screen_code_layout_action_button_icon_padding) codeSubmitFab.setOnClickListener { submitCodeActionClick() } codeSubmitButton.setOnClickListener { submitCodeActionClick() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(ARG_LANG, lang) outState.putString(ARG_CODE, codeLayout.text.toString()) } private fun initViewPager(isShowRunCode: Boolean) { val pagerAdapter = CodeStepQuizFullScreenPagerAdapter(requireContext(), isShowRunCode = isShowRunCode) fullScreenCodeViewPager.adapter = pagerAdapter fullScreenCodeTabs.setupWithViewPager(fullScreenCodeViewPager) fullScreenCodeViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(p0: Int) {} override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {} override fun onPageSelected(p0: Int) { view?.hideKeyboard() } }) instructionsLayout = pagerAdapter.getViewAt(0) playgroundLayout = pagerAdapter.getViewAt(1) runCodeLayout = if (isShowRunCode) { pagerAdapter.getViewAt(2) } else { null } } override fun onStart() { super.onStart() dialog ?.window ?.let { window -> window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) window.setWindowAnimations(R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen) } dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) runCodeDelegate?.let { codeRunPresenter.attachView(it) } } override fun onPause() { (parentFragment as? Callback) ?.onSyncCodeStateWithParent(lang, codeLayout.text.toString()) super.onPause() } override fun onStop() { runCodeDelegate?.let { it.onDetach() codeRunPresenter.detachView(it) } super.onStop() } override fun onChangeLanguage() { val languages = codeTemplates.keys.sorted().toTypedArray() val dialog = ProgrammingLanguageChooserDialogFragment.newInstance(languages) if (!dialog.isAdded) { dialog.show(childFragmentManager, null) } } override fun onLanguageChosen(programmingLanguage: String) { lang = programmingLanguage runCodeDelegate?.lang = lang codeLayoutDelegate.setLanguage(programmingLanguage) codeLayoutDelegate.setDetailsContentData(programmingLanguage) (parentFragment as? Callback) ?.onSyncCodePreference(programmingLanguage) } override fun onReset() { codeLayoutDelegate.setLanguage(lang) } private fun setupCodeToolAdapter() { codeToolbarAdapter = CodeToolbarAdapter(requireContext()) .apply { onSymbolClickListener = object : CodeToolbarAdapter.OnSymbolClickListener { override fun onSymbolClick(symbol: String, offset: Int) { codeLayout.insertText(CodeToolbarUtil.mapToolbarSymbolToPrintable(symbol, codeLayout.indentSize), offset) } } } } /** * Keyboard extension */ private fun setupKeyboardExtension() { stepQuizCodeKeyboardExtension.adapter = codeToolbarAdapter stepQuizCodeKeyboardExtension.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) codeLayout.codeToolbarAdapter = codeToolbarAdapter setOnKeyboardOpenListener( coordinator, onKeyboardHidden = { if (keyboardShown) { if (fullScreenCodeViewPager.currentItem == CODE_TAB && runCodeDelegate != null) { codeRunPresenter.resolveRunCodePopup() } stepQuizCodeKeyboardExtension.visibility = View.GONE codeLayout.isNestedScrollingEnabled = true codeLayout.layoutParams = (codeLayout.layoutParams as RelativeLayout.LayoutParams) .apply { bottomMargin = 0 } codeLayout.setPadding( 0, 0, 0, requireContext().resources.getDimensionPixelSize(R.dimen.step_quiz_fullscreen_code_layout_bottom_padding) ) setViewsVisibility(needShow = true) keyboardShown = false } }, onKeyboardShown = { if (!keyboardShown) { // We show the keyboard extension only when "Code" tab is opened if (fullScreenCodeViewPager.currentItem == CODE_TAB) { stepQuizCodeKeyboardExtension.visibility = View.VISIBLE } codeLayout.isNestedScrollingEnabled = false codeLayout.layoutParams = (codeLayout.layoutParams as RelativeLayout.LayoutParams) .apply { bottomMargin = stepQuizCodeKeyboardExtension.height } codeLayout.setPadding(0, 0, 0, 0) setViewsVisibility(needShow = false) keyboardShown = true } } ) } /** * Hiding views upon opening keyboard */ private fun setViewsVisibility(needShow: Boolean) { submitButtonSeparator.isVisible = needShow codeSubmitFab.isVisible = !needShow codeSubmitButton.isVisible = needShow centeredToolbar.isVisible = needShow fullScreenCodeTabs.isVisible = needShow runCodeActionSeparator?.isVisible = needShow runCodeFab?.isVisible = !needShow runCodeAction?.isVisible = needShow } private fun onChangeLanguageClicked() { val dialog = ChangeCodeLanguageDialog.newInstance() if (!dialog.isAdded) { dialog.show(childFragmentManager, null) } } private fun resolveIsShowRunCode(isRunCodeEnabled: Boolean, hasSamples: Boolean): Boolean = (lang == ProgrammingLanguage.SQL.serverPrintableName && isRunCodeEnabled) || (isRunCodeEnabled && hasSamples) private fun submitCodeActionClick() { (parentFragment as? Callback) ?.onSyncCodeStateWithParent(lang, codeLayout.text.toString(), onSubmitClicked = true) dismiss() } interface Callback { fun onSyncCodeStateWithParent(lang: String, code: String, onSubmitClicked: Boolean = false) fun onSyncCodePreference(lang: String) } }
apache-2.0
d8696ce88067cb85f456bd49c82852b4
39.012346
172
0.671131
5.180307
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/TriStateItem.kt
1
2848
package eu.kanade.tachiyomi.ui.catalogue.filter import android.support.design.R import android.support.graphics.drawable.VectorDrawableCompat import android.support.v7.widget.RecyclerView import android.view.View import android.widget.CheckedTextView import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.util.dpToPx import eu.kanade.tachiyomi.util.getResourceColor import eu.kanade.tachiyomi.R as TR open class TriStateItem(val filter: Filter.TriState) : AbstractFlexibleItem<TriStateItem.Holder>() { override fun getLayoutRes(): Int { return TR.layout.navigation_view_checkedtext } override fun getItemViewType(): Int { return 103 } override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): Holder { return Holder(view, adapter) } override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: Holder, position: Int, payloads: List<Any?>?) { val view = holder.text view.text = filter.name fun getIcon() = VectorDrawableCompat.create(view.resources, when (filter.state) { Filter.TriState.STATE_IGNORE -> TR.drawable.ic_check_box_outline_blank_24dp Filter.TriState.STATE_INCLUDE -> TR.drawable.ic_check_box_24dp Filter.TriState.STATE_EXCLUDE -> TR.drawable.ic_check_box_x_24dp else -> throw Exception("Unknown state") }, null)?.apply { val color = if (filter.state == Filter.TriState.STATE_INCLUDE) R.attr.colorAccent else android.R.attr.textColorSecondary setTint(view.context.getResourceColor(color)) } view.setCompoundDrawablesWithIntrinsicBounds(getIcon(), null, null, null) holder.itemView.setOnClickListener { filter.state = (filter.state + 1) % 3 view.setCompoundDrawablesWithIntrinsicBounds(getIcon(), null, null, null) } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return filter == (other as TriStateItem).filter } override fun hashCode(): Int { return filter.hashCode() } class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) { val text: CheckedTextView = itemView.findViewById(TR.id.nav_view_item) init { // Align with native checkbox text.setPadding(4.dpToPx, 0, 0, 0) text.compoundDrawablePadding = 20.dpToPx } } }
apache-2.0
9a6b48db0e7f85728ee9a6ee49f9b135
36
149
0.690309
4.600969
false
false
false
false
apollostack/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/unified/ir/IrRootFieldBuilder.kt
1
6794
package com.apollographql.apollo3.compiler.unified.ir import com.apollographql.apollo3.api.BooleanExpression import com.apollographql.apollo3.graphql.ast.GQLField import com.apollographql.apollo3.graphql.ast.GQLFragmentDefinition import com.apollographql.apollo3.graphql.ast.GQLFragmentSpread import com.apollographql.apollo3.graphql.ast.GQLInlineFragment import com.apollographql.apollo3.graphql.ast.GQLSelection import com.apollographql.apollo3.graphql.ast.GQLTypeDefinition import com.apollographql.apollo3.graphql.ast.Schema import com.apollographql.apollo3.graphql.ast.possibleTypes /** * For a list of selections collect all the typeConditions. * Then for each combination of typeConditions, collect all the fields recursively. * * While doing so, record all the used fragments and used types */ class IrRootFieldBuilder( private val schema: Schema, private val allGQLFragmentDefinitions: Map<String, GQLFragmentDefinition>, private val fieldMerger: FieldMerger, ) : RootFieldBuilder { val collectedFragments = mutableSetOf<String>() override fun build( selections: List<GQLSelection>, rawTypeName: String, ): IrField { val info = IrFieldInfo( name = "data", alias = null, description = null, deprecationReason = null, arguments = emptyList(), type = IrModelType(IrUnknownModelId), rawTypeName = rawTypeName ) return buildField( info = info, selections = selections, condition = BooleanExpression.True, ) } private fun List<GQLSelection>.collectUserTypeSets(currentTypeSet: TypeSet): List<TypeSet> { return listOf(currentTypeSet) + flatMap { when (it) { is GQLField -> emptyList() is GQLInlineFragment -> it.selectionSet.selections.collectUserTypeSets(currentTypeSet + it.typeCondition.name) is GQLFragmentSpread -> { collectedFragments.add(it.name) val fragmentDefinition = allGQLFragmentDefinitions[it.name]!! fragmentDefinition.selectionSet.selections.collectUserTypeSets(currentTypeSet + fragmentDefinition.typeCondition.name) } } } } private fun List<GQLSelection>.collectFragments(): Set<String> { return flatMap { when (it) { is GQLField -> emptySet() is GQLInlineFragment -> { it.selectionSet.selections.collectFragments() } // We do not recurse here as inheriting the first namedFragment will // inherit nested ones as well is GQLFragmentSpread -> return@flatMap setOf(it.name) } }.toSet() } data class Shape(val typeSet: TypeSet, val schemaPossibleTypes: PossibleTypes, val actualPossibleTypes: PossibleTypes) private fun buildField( info: IrFieldInfo, condition: BooleanExpression, selections: List<GQLSelection>, ): IrField { if (selections.isEmpty()) { return IrField( info = info, condition = condition, fieldSets = emptyList(), fragments = emptySet() ) } val rawTypeName = info.rawTypeName val userTypeSets = selections.collectUserTypeSets(setOf(rawTypeName)).distinct().toSet() val typeConditionToPossibleTypes = userTypeSets.union().map { it to schema.typeDefinition(it).possibleTypes(schema) }.toMap() val shapes = userTypeSets.map { Shape( it, it.map { typeConditionToPossibleTypes[it]!! }.intersection(), emptySet() ) }.toMutableList() schema.typeDefinitions.values.filterIsInstance<GQLTypeDefinition>().forEach { objectTypeDefinition -> val concreteType = objectTypeDefinition.name val superShapes = mutableListOf<Shape>() shapes.forEachIndexed { index, shape -> if (shapes[index].schemaPossibleTypes.contains(concreteType)) { superShapes.add(shape) } } if(superShapes.isEmpty()) { // This type will not be included in this query return@forEach } /** * This type will fall in the bucket that has all the typeConditions. It might be that we have to create a new bucket * if two leaf fragments point to the same type */ val bucketTypeSet = superShapes.fold(emptySet<String>()) { acc, shape -> acc.union(shape.typeSet) } val index = shapes.indexOfFirst { it.typeSet == bucketTypeSet } if (index < 0) { shapes.add( Shape( bucketTypeSet, bucketTypeSet.map { typeConditionToPossibleTypes[it]!! }.intersection(), setOf(concreteType) ) ) } else { val existingShape = shapes[index] shapes[index] = existingShape.copy(actualPossibleTypes = existingShape.actualPossibleTypes + concreteType) } } val fieldSets = shapes.map { shape -> buildFieldSet( selections = selections, rawTypeName = rawTypeName, typeSet = shape.typeSet, possibleTypes = shape.actualPossibleTypes, ) } return IrField( info = info, condition = condition, fieldSets = fieldSets, fragments = selections.collectFragments() ) } /** */ private fun collectFieldsInternal( selections: List<GQLSelection>, typeCondition: String, typeSet: TypeSet, ): List<FieldWithParent> { return selections.flatMap { when (it) { is GQLField -> listOf(FieldWithParent(it, typeCondition)) is GQLInlineFragment -> { if (typeSet.contains(it.typeCondition.name)) { collectFieldsInternal(it.selectionSet.selections, it.typeCondition.name, typeSet) } else { emptyList() } } is GQLFragmentSpread -> { val fragment = allGQLFragmentDefinitions[it.name]!! if (typeSet.contains(fragment.typeCondition.name)) { collectFieldsInternal(fragment.selectionSet.selections, fragment.typeCondition.name, typeSet) } else { emptyList() } } } } } private fun buildFieldSet( selections: List<GQLSelection>, rawTypeName: String, typeSet: TypeSet, possibleTypes: PossibleTypes, ): IrFieldSet { val fields = collectFieldsInternal( selections = selections, typeCondition = rawTypeName, typeSet = typeSet, ).let { fieldMerger.merge(it) }.map { mergedField -> buildField( info = mergedField.info, condition = mergedField.condition, selections = mergedField.selections, ) } return IrFieldSet( typeSet = typeSet, possibleTypes = possibleTypes, fields = fields, ) } }
mit
a7e10e2c54cf1d0fe99f9159fe2416fd
30.453704
128
0.649985
4.56586
false
false
false
false
SirLYC/Android-Gank-Share
app/src/main/java/com/lyc/gank/article/ArticleActivity.kt
1
4165
package com.lyc.gank.article import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View.* import android.view.ViewGroup import android.webkit.WebChromeClient import android.webkit.WebSettings import android.webkit.WebView import com.lyc.data.resp.GankItem import com.lyc.gank.R import com.lyc.gank.utils.openWebPage import com.lyc.gank.utils.textCopy import com.lyc.gank.utils.toast import kotlinx.android.synthetic.main.activity_article.* class ArticleActivity : AppCompatActivity() { companion object { private const val TAG = "Article" private const val KEY_URL = "KEY_URL" fun start(context: Context, gankItem: GankItem) { val intent = Intent(context, ArticleActivity::class.java) .apply { putExtra(KEY_URL, gankItem.url) } context.startActivity(intent) } } private var showActionBar = true private var url: String? = null @SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_article) setSupportActionBar(tb_article) supportActionBar?.setDisplayHomeAsUpEnabled(true) url = intent.getStringExtra(KEY_URL) if (url == null) { //todo : show invalid url return } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { wv_article.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW } wv_article.webChromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView?, newProgress: Int) { super.onProgressChanged(view, newProgress) if (newProgress in 1..99) { pb_article.visibility = VISIBLE pb_article.progress = newProgress } else { pb_article.visibility = GONE } } } wv_article.settings.javaScriptEnabled = true wv_article.settings.builtInZoomControls = true wv_article.settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK wv_article.loadUrl(url) tb_article.translationY = 0f showActionBar = true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { if (wv_article.canGoBack()) { wv_article.goBack() } else { finish() } true } R.id.close -> { finish() true } R.id.refresh -> { wv_article.reload() true } R.id.share -> { textCopy(wv_article.url) toast("已将网址复制到剪贴板") true } R.id.open_in_browser -> { openWebPage(wv_article.url) true } else -> false } } override fun onBackPressed() { if (wv_article.canGoBack()) { wv_article.goBack() } else { super.onBackPressed() } } override fun onResume() { wv_article.onResume() wv_article.resumeTimers() super.onResume() } override fun onPause() { wv_article.onPause() wv_article.pauseTimers() super.onPause() } override fun onDestroy() { (wv_article.parent as ViewGroup) .removeView(wv_article) wv_article.visibility = GONE wv_article.destroy() super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_article, menu) return true } }
apache-2.0
91b592f62af0cc2541c5a038e0884d17
27.784722
89
0.573703
4.652076
false
false
false
false
garmax1/material-flashlight
app/src/main/java/co/garmax/materialflashlight/features/modes/SoundStrobeMode.kt
1
3763
package co.garmax.materialflashlight.features.modes import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.media.AudioFormat import android.media.AudioRecord import android.media.MediaRecorder import androidx.core.content.ContextCompat import co.garmax.materialflashlight.ui.PermissionsActivity import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.disposables.Disposable import timber.log.Timber import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.min /** * Interrupted light depending on the around noise volume */ class SoundStrobeMode( private val context: Context, private val workerScheduler: Scheduler ) : ModeBase() { private var disposableInterval: Disposable? = null // Audio staff private var audioRecord: AudioRecord? = null private var bufferSize = 0 private var maxAmplitude = 0 private var minAmplitude = 0 override fun checkPermissions(): Boolean { if (ContextCompat.checkSelfPermission( context, Manifest.permission.RECORD_AUDIO ) != PackageManager.PERMISSION_GRANTED ) { PermissionsActivity.startActivity(context, arrayOf(Manifest.permission.RECORD_AUDIO)) return false } return true } override fun start() { bufferSize = AudioRecord.getMinBufferSize( 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT ) audioRecord = AudioRecord( MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize ).apply { startRecording() } minAmplitude = 0 maxAmplitude = 0 disposableInterval = Observable.interval( 0, CHECK_AMPLITUDE_PERIOD, TimeUnit.MILLISECONDS, workerScheduler ) .subscribe { _: Long? -> setBrightness(amplitudePercentage(amplitude)) } setBrightness(MAX_AMPLITUDE) } override fun stop() { setBrightness(MIN_LIGHT_VOLUME) disposableInterval?.dispose() audioRecord?.stop() } private val amplitude: Int get() { val buffer = ShortArray(bufferSize) audioRecord?.read(buffer, 0, bufferSize) var max: Short = 0 for (s in buffer) { if (s > max) { max = s } } return max.toInt() } private fun amplitudePercentage(curAmplitude: Int): Int { // Reduce amplitude min\max tunnel // because min\max value can be above or below initial avg value // and limit with 0 and max amplitude value maxAmplitude = max(maxAmplitude - INCREASE_STEP, 0) minAmplitude = min(minAmplitude + INCREASE_STEP, MAX_AMPLITUDE) // Save min max values maxAmplitude = max(maxAmplitude, curAmplitude) minAmplitude = min(minAmplitude, curAmplitude) // If min and max equal, exit to prevent dividing by zero if (minAmplitude == maxAmplitude) { return 0 } // Calculate percentage of current amplitude of difference max and min amplitude val avgAmplitude = (curAmplitude - minAmplitude) * 100 / (maxAmplitude - minAmplitude) Timber.d("Sound amplitude min: $minAmplitude, max: $maxAmplitude, cur: $curAmplitude; avg: $avgAmplitude") return avgAmplitude } companion object { private const val CHECK_AMPLITUDE_PERIOD = 50L private const val INCREASE_STEP = 150 private const val MAX_AMPLITUDE = 32767 } }
apache-2.0
5ccda69aa46366e2dce0a8777a554fea
30.898305
114
0.645761
4.775381
false
false
false
false
k9mail/k-9
backend/testing/src/main/java/app/k9mail/backend/testing/InMemoryBackendFolder.kt
2
5289
package app.k9mail.backend.testing import com.fsck.k9.backend.api.BackendFolder import com.fsck.k9.backend.api.BackendFolder.MoreMessages import com.fsck.k9.mail.Flag import com.fsck.k9.mail.FolderType import com.fsck.k9.mail.Message import com.fsck.k9.mail.MessageDownloadState import com.fsck.k9.mail.internet.MimeMessage import java.util.Date import okio.Buffer import okio.buffer import okio.source import org.junit.Assert.assertEquals class InMemoryBackendFolder(override var name: String, var type: FolderType) : BackendFolder { val extraStrings: MutableMap<String, String> = mutableMapOf() val extraNumbers: MutableMap<String, Long> = mutableMapOf() private val messages = mutableMapOf<String, Message>() private val messageFlags = mutableMapOf<String, MutableSet<Flag>>() private var moreMessages: MoreMessages = MoreMessages.UNKNOWN private var status: String? = null private var lastChecked = 0L override var visibleLimit: Int = 25 fun assertMessages(vararg messagePairs: Pair<String, String>) { for ((messageServerId, resourceName) in messagePairs) { assertMessageContents(messageServerId, resourceName) } val messageServerIds = messagePairs.map { it.first }.toSet() assertEquals(messageServerIds, messages.keys) } private fun assertMessageContents(messageServerId: String, resourceName: String) { val message = messages[messageServerId] ?: error("Message $messageServerId not found") assertEquals(loadResource(resourceName), getMessageContents(message)) } fun createMessages(vararg messagePairs: Pair<String, String>) { for ((messageServerId, resourceName) in messagePairs) { val inputStream = javaClass.getResourceAsStream(resourceName) ?: error("Couldn't load resource: $resourceName") val message = inputStream.use { MimeMessage.parseMimeMessage(inputStream, false) } messages[messageServerId] = message messageFlags[messageServerId] = mutableSetOf() } } private fun getMessageContents(message: Message): String { val buffer = Buffer() buffer.outputStream().use { message.writeTo(it) } return buffer.readUtf8() } override fun getMessageServerIds(): Set<String> { return messages.keys.toSet() } override fun getAllMessagesAndEffectiveDates(): Map<String, Long?> { return messages .map { (serverId, message) -> serverId to message.sentDate.time } .toMap() } override fun destroyMessages(messageServerIds: List<String>) { for (messageServerId in messageServerIds) { messages.remove(messageServerId) messageFlags.remove(messageServerId) } } override fun clearAllMessages() { destroyMessages(messages.keys.toList()) } override fun getMoreMessages(): MoreMessages = moreMessages override fun setMoreMessages(moreMessages: MoreMessages) { this.moreMessages = moreMessages } override fun setLastChecked(timestamp: Long) { lastChecked = timestamp } override fun setStatus(status: String?) { this.status = status } override fun isMessagePresent(messageServerId: String): Boolean { return messages[messageServerId] != null } override fun getMessageFlags(messageServerId: String): Set<Flag> { return messageFlags[messageServerId] ?: error("Message $messageServerId not found") } override fun setMessageFlag(messageServerId: String, flag: Flag, value: Boolean) { val flags = messageFlags[messageServerId] ?: error("Message $messageServerId not found") if (value) { flags.add(flag) } else { flags.remove(flag) } } override fun saveMessage(message: Message, downloadState: MessageDownloadState) { val messageServerId = checkNotNull(message.uid) messages[messageServerId] = message val flags = message.flags.toMutableSet() when (downloadState) { MessageDownloadState.ENVELOPE -> Unit MessageDownloadState.PARTIAL -> flags.add(Flag.X_DOWNLOADED_PARTIAL) MessageDownloadState.FULL -> flags.add(Flag.X_DOWNLOADED_FULL) } messageFlags[messageServerId] = flags } override fun getOldestMessageDate(): Date? { throw UnsupportedOperationException("not implemented") } override fun getFolderExtraString(name: String): String? = extraStrings[name] override fun setFolderExtraString(name: String, value: String?) { if (value != null) { extraStrings[name] = value } else { extraStrings.remove(name) } } override fun getFolderExtraNumber(name: String): Long? = extraNumbers[name] override fun setFolderExtraNumber(name: String, value: Long) { extraNumbers[name] = value } private fun loadResource(name: String): String { val resourceAsStream = javaClass.getResourceAsStream(name) ?: error("Couldn't load resource: $name") return resourceAsStream.use { it.source().buffer().readUtf8() } } }
apache-2.0
91bab7a06879dc6393722b634bda60b1
33.344156
108
0.673662
4.68883
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/mailstore/KoinModule.kt
1
1448
package com.fsck.k9.mailstore import com.fsck.k9.message.extractors.AttachmentCounter import com.fsck.k9.message.extractors.MessageFulltextCreator import com.fsck.k9.message.extractors.MessagePreviewCreator import org.koin.dsl.module val mailStoreModule = module { single { FolderRepository(messageStoreManager = get(), accountManager = get()) } single { MessageViewInfoExtractorFactory(get(), get(), get()) } single { StorageManager.getInstance(get()) } single { SearchStatusManager() } single { SpecialFolderSelectionStrategy() } single { K9BackendStorageFactory( preferences = get(), folderRepository = get(), messageStoreManager = get(), specialFolderSelectionStrategy = get(), saveMessageDataCreator = get() ) } factory { SpecialLocalFoldersCreator(preferences = get(), localStoreProvider = get()) } single { MessageStoreManager(accountManager = get(), messageStoreFactory = get()) } single { MessageRepository(messageStoreManager = get()) } factory { MessagePreviewCreator.newInstance() } factory { MessageFulltextCreator.newInstance() } factory { AttachmentCounter.newInstance() } factory { SaveMessageDataCreator( encryptionExtractor = get(), messagePreviewCreator = get(), messageFulltextCreator = get(), attachmentCounter = get() ) } }
apache-2.0
c8996b0402e75369e2372e545b506e82
38.135135
91
0.678177
4.94198
false
false
false
false
PolymerLabs/arcs
particles/Native/Wasm/Kotlin/TestParticle.kt
2
4275
/** * @license * Copyright (c) 2019 Google Inc. All rights reserved. * 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 import arcs.sdk.Utils.abort import arcs.sdk.Utils.log import arcs.sdk.wasm.WasmHandle import kotlin.Exception /** * Sample WASM Particle. */ class TestParticle : AbstractTestParticle() { override fun onHandleUpdate(handle: WasmHandle) { log("A handle was updated!") if (handle.name.equals("data")) { log("data was updated") updated = 1 } else if (handle.name.equals("info")) { log("info was updated.") updated = 2 } } override fun populateModel(slotName: String, model: Map<String, Any>): Map<String, Any> { val dataCol = if (updated == 1) "color: blue;" else "" val dataStr = "${handles.data.fetch()}\n" val infoCol = if (updated == 2) "color: blue;" else "" var infoStr = "Size: ${handles.info.size}\n" if (!handles.info.isEmpty()) { var i = 0 handles.info.fetchAll().forEach { info -> infoStr += "${(++i)}. $info | \n" } } else { infoStr = "<i>(empty)</i>" } return mapOf( "dataCol" to dataCol, "dataStr" to dataStr, "infoCol" to infoCol, "infoStr" to infoStr ) } override fun getTemplate(slotName: String): String { log("getting template") return """ <style> #data {{dataCol}} #info {{infoCol}} #panel { margin: 10px; } #panel pre { margin-left: 20px; } th,td { padding: 4px 16px; } </style> <div id="panel"> <b id="data">[data]</b> <pre>{{dataStr}}</pre> <b id="info">[info]</b> <pre>{{infoStr}}</pre> </div> <table> <tr> <th>Singleton</th> <th>Collection</th> <th>Errors</th> </tr> <tr> <td><button on-click="add">Add</button></td> <td><button on-click="store">Store</button></td> <td> <button on-click="throw">Throw</button> &nbsp; <button on-click="abort">Abort</button> </td> </tr> <tr> <td><button on-click="dataclear">Clear</button></td> <td><button on-click="remove">Remove</button></td> <td> <button on-click="assert">Assert</button> &nbsp; <button on-click="exit">Exit</button> </td> </tr> <tr> <td></td> <td><button on-click="infoclear">Clear</button></td> </tr> </table>""".trimIndent() } private var updated = 0 private var storeCount = 0 init { eventHandler("add") { val newData = handles.data.fetch() ?: TestParticle_Data( num = 0.0, txt = "", lnk = "", flg = false ) handles.data.store( newData.copy( num = newData.num.let { it + 2 }, txt = "${newData.txt}!!!!!!" ) ) } eventHandler("dataclear") { handles.data.clear() } eventHandler("store") { val info = TestParticle_Info( for_ = "", val_ = 0.0 ) handles.info.store( info.copy( val_ = (handles.info.size + storeCount).toDouble() ) ) } eventHandler("remove") { val iterator = handles.info.fetchAll().iterator() if (iterator.hasNext()) { handles.info.remove(iterator.next()) } } eventHandler("infoclear") { handles.info.clear() } eventHandler("throw") { throw Exception("this message doesn't get passed (yet?)") } eventHandler("assert") { assert(2 + 2 == 3) } eventHandler("abort") { abort() } eventHandler("exit") { // exit(1) } } }
bsd-3-clause
e9160f50ba16872dc21738310356e02a
25.886792
91
0.491462
3.947368
false
false
false
false
Maccimo/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/PluginLayout.kt
1
16385
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.impl import com.intellij.util.containers.MultiMap import kotlinx.collections.immutable.PersistentList import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.JvmArchitecture import org.jetbrains.intellij.build.OsFamily import org.jetbrains.intellij.build.PluginBundlingRestrictions import org.jetbrains.intellij.build.io.copyDir import org.jetbrains.intellij.build.io.copyFileToDir import java.nio.file.Files import java.nio.file.Path import java.util.function.* /** * Describes layout of a plugin in the product distribution */ class PluginLayout(val mainModule: String): BaseLayout() { private var mainJarName = "${convertModuleNameToFileName(mainModule)}.jar" lateinit var directoryName: String var versionEvaluator: VersionEvaluator = object : VersionEvaluator { override fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext) = ideBuildVersion } var pluginXmlPatcher: UnaryOperator<String> = UnaryOperator.identity() var directoryNameSetExplicitly: Boolean = false @JvmField internal var bundlingRestrictions: PluginBundlingRestrictions = PluginBundlingRestrictions.NONE val pathsToScramble: MutableList<String> = mutableListOf() val scrambleClasspathPlugins: MutableList<Pair<String /*plugin name*/, String /*relative path*/>> = mutableListOf() var scrambleClasspathFilter: BiPredicate<BuildContext, Path> = BiPredicate { _, _ -> true } /** * See {@link org.jetbrains.intellij.build.impl.PluginLayout.PluginLayoutSpec#zkmScriptStub} */ var zkmScriptStub: String? = null var pluginCompatibilityExactVersion = false var retainProductDescriptorForBundledPlugin = false internal val resourceGenerators: MutableList<BiFunction<Path, BuildContext, Path?>> = mutableListOf() internal val patchers: MutableList<BiConsumer<ModuleOutputPatcher, BuildContext>> = mutableListOf() fun getMainJarName() = mainJarName companion object { /** * Creates the plugin layout description. The default plugin layout is composed of a jar with name {@code mainModuleName}.jar containing * production output of {@code mainModuleName} module, and the module libraries of {@code mainModuleName} with scopes 'Compile' and 'Runtime' * placed under 'lib' directory in a directory with name {@code mainModuleName}. * If you need to include additional resources or modules into the plugin layout specify them in * {@code body} parameter. If you don't need to change the default layout there is no need to call this method at all, it's enough to * specify the plugin module in {@link org.jetbrains.intellij.build.ProductModulesLayout#bundledPluginModules bundledPluginModules/pluginModulesToPublish} list. * * <p>Note that project-level libraries on which the plugin modules depend, are automatically put to 'IDE_HOME/lib' directory for all IDEs * which are compatible with the plugin. If this isn't desired (e.g. a library is used in a single plugin only, or if plugins where * a library is used aren't bundled with IDEs, so we don't want to increase size of the distribution, you may invoke {@link PluginLayoutSpec#withProjectLibrary} * to include such a library to the plugin distribution.</p> * @param mainModuleName name of the module containing META-INF/plugin.xml file of the plugin */ @JvmStatic fun plugin(mainModuleName: String, body: Consumer<PluginLayoutSpec>): PluginLayout { if (mainModuleName.isEmpty()) { error("mainModuleName must be not empty") } val layout = PluginLayout(mainModuleName) val spec = PluginLayoutSpec(layout) body.accept(spec) layout.directoryName = spec.directoryName if (!layout.getIncludedModuleNames().contains(mainModuleName)) { layout.withModule(mainModuleName, layout.mainJarName) } if (spec.mainJarNameSetExplicitly) { layout.explicitlySetJarPaths.add(layout.mainJarName) } else { layout.explicitlySetJarPaths.remove(layout.mainJarName) } layout.directoryNameSetExplicitly = spec.directoryNameSetExplicitly layout.bundlingRestrictions = spec.bundlingRestrictions.build() return layout } @JvmStatic fun simplePlugin(mainModuleName: String): PluginLayout { if (mainModuleName.isEmpty()) { error("mainModuleName must be not empty") } val layout = PluginLayout(mainModuleName) layout.directoryName = convertModuleNameToFileName(layout.mainModule) layout.withModuleImpl(mainModuleName, layout.mainJarName) layout.bundlingRestrictions = PluginBundlingRestrictions.NONE return layout } } override fun toString() = "Plugin '$mainModule'" override fun withModule(moduleName: String) { if (moduleName.endsWith(".jps") || moduleName.endsWith(".rt")) { // must be in a separate JAR super.withModule(moduleName) } else { withModuleImpl(moduleName, mainJarName) } } fun withGeneratedResources(generator: BiConsumer<Path, BuildContext>) { resourceGenerators.add(BiFunction<Path, BuildContext, Path?> { targetDir, context -> generator.accept(targetDir, context) null }) } fun mergeServiceFiles() { patchers.add(BiConsumer { patcher, context -> val discoveredServiceFiles: MultiMap<String, Pair<String, Path>> = MultiMap.createLinkedSet() for (moduleName in moduleJars.get(mainJarName)) { val path = context.findFileInModuleSources(moduleName, "META-INF/services") ?: continue Files.list(path).use { stream -> stream .filter { Files.isRegularFile(it) } .forEach { serviceFile: Path -> discoveredServiceFiles.putValue(serviceFile.fileName.toString(), Pair(moduleName, serviceFile)) } } } discoveredServiceFiles.entrySet().forEach { entry: Map.Entry<String, Collection<Pair<String, Path>>> -> val serviceFileName = entry.key val serviceFiles: Collection<Pair<String, Path>> = entry.value if (serviceFiles.size <= 1) return@forEach val content = serviceFiles.joinToString("\n") { Files.readString(it.second) } context.messages.info("Merging service file " + serviceFileName + " (" + serviceFiles.joinToString(", ") { it.first } + ")") patcher.patchModuleOutput(serviceFiles.first().first, // first one wins "META-INF/services/$serviceFileName", content) } }) } class PluginLayoutSpec(private val layout: PluginLayout): BaseLayoutSpec(layout) { var directoryName: String = convertModuleNameToFileName(layout.mainModule) /** * Custom name of the directory (under 'plugins' directory) where the plugin should be placed. By default, the main module name is used * (with stripped {@code intellij} prefix and dots replaced by dashes). * <strong>Don't set this property for new plugins</strong>; it is temporary added to keep layout of old plugins unchanged. */ set(value) { field = value directoryNameSetExplicitly = true } var mainJarNameSetExplicitly: Boolean = false private set var directoryNameSetExplicitly: Boolean = false private set val mainModule get() = layout.mainModule /** * Returns {@link PluginBundlingRestrictions} instance which can be used to exclude the plugin from some distributions. */ val bundlingRestrictions: PluginBundlingRestrictionBuilder = PluginBundlingRestrictionBuilder() class PluginBundlingRestrictionBuilder { /** * Change this value if the plugin works in some OS only and therefore don't need to be bundled with distributions for other OS. */ var supportedOs: PersistentList<OsFamily> = OsFamily.ALL /** * Change this value if the plugin works on some architectures only and * therefore don't need to be bundled with distributions for other architectures. */ var supportedArch: List<JvmArchitecture> = JvmArchitecture.ALL /** * Set to {@code true} if the plugin should be included in distribution for EAP builds only. */ var includeInEapOnly: Boolean = false internal fun build(): PluginBundlingRestrictions { return PluginBundlingRestrictions(supportedOs, supportedArch, includeInEapOnly) } } var mainJarName: String get() = layout.mainJarName /** * Custom name of the main plugin JAR file. By default, the main module name with 'jar' extension is used (with stripped {@code intellij} * prefix and dots replaced by dashes). * <strong>Don't set this property for new plugins</strong>; it is temporary added to keep layout of old plugins unchanged. */ set(value) { layout.mainJarName = value mainJarNameSetExplicitly = true } /** * @param binPathRelativeToCommunity path to resource file or directory relative to the intellij-community repo root * @param outputPath target path relative to the plugin root directory */ @JvmOverloads fun withBin(binPathRelativeToCommunity: String, outputPath: String, skipIfDoesntExist: Boolean = false) { withGeneratedResources(BiConsumer { targetDir, context -> val source = context.paths.communityHomeDir.communityRoot.resolve(binPathRelativeToCommunity).normalize() if (Files.notExists(source)) { if (skipIfDoesntExist) { return@BiConsumer } error("'$source' doesn't exist") } if (Files.isRegularFile(source)) { copyFileToDir(source, targetDir.resolve(outputPath)) } else { copyDir(source, targetDir.resolve(outputPath)) } }) } /** * @param resourcePath path to resource file or directory relative to the plugin's main module content root * @param relativeOutputPath target path relative to the plugin root directory */ fun withResource(resourcePath: String, relativeOutputPath: String) { withResourceFromModule(layout.mainModule, resourcePath, relativeOutputPath) } /** * @param resourcePath path to resource file or directory relative to {@code moduleName} module content root * @param relativeOutputPath target path relative to the plugin root directory */ fun withResourceFromModule(moduleName: String, resourcePath: String, relativeOutputPath: String) { layout.resourcePaths.add(ModuleResourceData(moduleName = moduleName, resourcePath = resourcePath, relativeOutputPath = relativeOutputPath, packToZip = false)) } /** * @param resourcePath path to resource file or directory relative to the plugin's main module content root * @param relativeOutputFile target path relative to the plugin root directory */ fun withResourceArchive(resourcePath: String, relativeOutputFile: String) { withResourceArchiveFromModule(layout.mainModule, resourcePath, relativeOutputFile) } /** * @param resourcePath path to resource file or directory relative to {@code moduleName} module content root * @param relativeOutputFile target path relative to the plugin root directory */ fun withResourceArchiveFromModule(moduleName: String, resourcePath: String, relativeOutputFile: String) { layout.resourcePaths.add(ModuleResourceData(moduleName, resourcePath, relativeOutputFile, true)) } fun withPatch(patcher: BiConsumer<ModuleOutputPatcher, BuildContext> ) { layout.patchers.add(patcher) } fun withGeneratedResources(generator: BiConsumer<Path, BuildContext>) { layout.withGeneratedResources(generator) } /** * By default, version of a plugin is equal to the build number of the IDE it's built with. This method allows to specify custom version evaluator. */ fun withCustomVersion(versionEvaluator: VersionEvaluator) { layout.versionEvaluator = versionEvaluator } fun withPluginXmlPatcher(pluginXmlPatcher: UnaryOperator<String>) { layout.pluginXmlPatcher = pluginXmlPatcher } @Deprecated(message = "localizable resources are always put to the module JAR, so there is no need to call this method anymore") fun doNotCreateSeparateJarForLocalizableResources() { } /** * This plugin will be compatible only with exactly the same IDE version. * See {@link org.jetbrains.intellij.build.CompatibleBuildRange#EXACT} */ fun pluginCompatibilityExactVersion() { layout.pluginCompatibilityExactVersion = true } /** * <product-description> is usually removed for bundled plugins. * Call this method to retain it in plugin.xml */ fun retainProductDescriptorForBundledPlugin() { layout.retainProductDescriptorForBundledPlugin = true } /** * Do not automatically include module libraries from {@code moduleNames} * <strong>Do not use this for new plugins, this method is temporary added to keep layout of old plugins</strong>. */ fun doNotCopyModuleLibrariesAutomatically(moduleNames: List<String>) { layout.modulesWithExcludedModuleLibraries.addAll(moduleNames) } /** * Specifies a relative path to a plugin jar that should be scrambled. * Scrambling is performed by the {@link org.jetbrains.intellij.build.ProprietaryBuildTools#scrambleTool} * If scramble tool is not defined, scrambling will not be performed * Multiple invocations of this method will add corresponding paths to a list of paths to be scrambled * * @param relativePath - a path to a jar file relative to plugin root directory */ fun scramble(relativePath: String) { layout.pathsToScramble.add(relativePath) } /** * Specifies a relative to {@link org.jetbrains.intellij.build.BuildPaths#communityHome} path to a zkm script stub file. * If scramble tool is not defined, scramble toot will expect to find the script stub file at "{@link org.jetbrains.intellij.build.BuildPaths#projectHome}/plugins/{@code pluginName}/build/script.zkm.stub". * Project home cannot be used since it is not constant (for example for Rider). * * @param communityRelativePath - a path to a jar file relative to community project home directory */ fun zkmScriptStub(communityRelativePath: String) { layout.zkmScriptStub = communityRelativePath } /** * Specifies a dependent plugin name to be added to scrambled classpath * Scrambling is performed by the {@link org.jetbrains.intellij.build.ProprietaryBuildTools#scrambleTool} * If scramble tool is not defined, scrambling will not be performed * Multiple invocations of this method will add corresponding plugin names to a list of name to be added to scramble classpath * * @param pluginName - a name of dependent plugin, whose jars should be added to scramble classpath * @param relativePath - a directory where jars should be searched (relative to plugin home directory, "lib" by default) */ @JvmOverloads fun scrambleClasspathPlugin(pluginName: String, relativePath: String = "lib") { layout.scrambleClasspathPlugins.add(Pair(pluginName, relativePath)) } /** * Allows control over classpath entries that will be used by the scrambler to resolve references from jars being scrambled. * By default, all platform jars are added to the 'scramble classpath' */ fun filterScrambleClasspath(filter: BiPredicate<BuildContext, Path>) { layout.scrambleClasspathFilter = filter } /** * Concatenates `META-INF/services` files with the same name from different modules together. * By default, the first service file silently wins. */ fun mergeServiceFiles() { layout.mergeServiceFiles() } } interface VersionEvaluator { fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext): String } }
apache-2.0
1641c552259471b69c8f72d1b6532cc5
42.930295
209
0.708758
5.136364
false
false
false
false
JStege1206/AdventOfCode
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day16.kt
1
4806
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoc2018.days.instructionset.Instruction.OpCodeInstruction import nl.jstege.adventofcode.aoc2018.days.instructionset.Op import nl.jstege.adventofcode.aoc2018.days.instructionset.RegisterBank import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.substringBetween class Day16 : Day(title = "Chronal Classification") { override fun first(input: Sequence<String>): Any = input .parseSamples() .count { (instr, before, after) -> Op.values().count { op -> op(instr.op1, instr.op2, instr.op3, before) == after } >= 3 } override fun second(input: Sequence<String>): Any = input .parseSamples() .determineOpCodes() .let { opCodes -> input .parseProgram() .fold(RegisterBank(0, 0, 0, 0)) { rs, (opCode, ra, rb, rc) -> opCodes[opCode]!!(ra, rb, rc, rs) }[0] } private fun Sequence<String>.parseProgram(): List<OpCodeInstruction> = this .joinToString("\n") .split("\n\n\n")[1] .split("\n") .filter { it.isNotEmpty() } .map { it.split(" ") } .map { it.map(String::toInt) } .map { (opCode, op1, op2, op3) -> OpCodeInstruction(opCode, op1, op2, op3) } private fun Sequence<String>.parseSamples() = this .chunked(4) .filter { it.first().startsWith("Before") } .map { (beforeLine, opLine, afterLine, _) -> val before = RegisterBank(beforeLine .substringBetween('[', ']') .split(", ") .map { it.toInt() }) val opCode = opLine .split(" ") .map { it.toInt() } .let { (code, op1, op2, op3) -> OpCodeInstruction(code, op1, op2, op3) } val after = RegisterBank(afterLine .substringBetween('[', ']') .split(", ") .map { it.toInt() }) Sample(opCode, before, after) } private fun Sequence<Sample>.determineOpCodes(): Map<Int, Op> { tailrec fun Iterator<Sample>.determinePossibles( possibilities: Map<Int, Set<Op>> ): Map<Int, Set<Op>> = if (!hasNext()) possibilities else { val (instr, beforeRegs, afterRegs) = next() determinePossibles( //Update the possible opcode-to-op entry with the information of the given //sample. This means that the entry will contain only the entries for which //the entry, given the instruction and "before" registers, produces the "after" //registers. possibilities + (instr.opCode to possibilities[instr.opCode]!!.filter { op -> op(instr.op1, instr.op2, instr.op3, beforeRegs) == afterRegs }.toSet()) ) } tailrec fun Map<Int, Set<Op>>.reduceToSingleEntries( definites: Map<Int, Op> = mapOf() ): Map<Int, Op> = if (definites.size == Op.values().size) definites else { //newDefinites contains all possibles which have been reduced to a single //possibility. Therefore, those entries are considered to be final. "remaining" //contains all entries which do not have a single entry left and should be further //reduced. val (newDefinites, remaining) = entries .partition { (opCode, ops) -> opCode !in definites && ops.size == 1 } //Since there may be new definite determined opCodes, remove these ops from the //remaining undetermined opcodes and recursively restart the process with the //remaining ops. remaining .associate { (opCode, remainingOps) -> opCode to (remainingOps - newDefinites.map { (_, op) -> op.first() }) } .reduceToSingleEntries( definites + newDefinites.map { (opCode, op) -> opCode to op.first() } ) } return this.iterator() //Initialise the possibles as a map of an opCode to all ops that fit. At this point no //samples have been processed thus all ops are possible. .determinePossibles((0 until Op.values().size).associate { it to Op.values().toSet() }) .reduceToSingleEntries() } data class Sample( val instruction: OpCodeInstruction, val before: RegisterBank, val after: RegisterBank ) }
mit
292c4d6dea694a5cf96f27399ea83f69
41.910714
99
0.550562
4.365123
false
false
false
false
ChristopherGittner/OSMBugs
app/src/main/java/org/gittner/osmbugs/mapdust/MapdustParser.kt
1
3298
package org.gittner.osmbugs.mapdust import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.joda.time.format.ISODateTimeFormat import org.json.JSONObject import org.osmdroid.util.GeoPoint class MapdustParser { companion object { suspend fun parse(data: String): ArrayList<MapdustError> = withContext(Dispatchers.Default) { val errors = ArrayList<MapdustError>() val json = JSONObject(data) val bugArray = json.getJSONArray("features") for (i in 0 until bugArray.length()) { val error = bugArray.getJSONObject(i) errors.add(parseError(error)) } errors } suspend fun parseError(data: String): MapdustError = withContext(Dispatchers.Default) { parseError(JSONObject(data)) } private fun parseError(error: JSONObject): MapdustError { val formatter = ISODateTimeFormat.dateTimeParser() val id = error.getLong("id") val geometry = error.getJSONObject("geometry") val lon = geometry.getJSONArray("coordinates").getDouble(0) val lat = geometry.getJSONArray("coordinates").getDouble(1) val properties = error.getJSONObject("properties") val user = properties.getString("nickname") val state = when (properties.getInt("status")) { 2 -> MapdustError.STATE.CLOSED 3 -> MapdustError.STATE.IGNORED else -> MapdustError.STATE.OPEN } val comments: ArrayList<MapdustError.MapdustComment> = ArrayList() val commentArray = properties.getJSONArray("comments") for (n in 0 until commentArray.length()) { comments.add( MapdustError.MapdustComment( commentArray.getJSONObject(n).getString("comment"), commentArray.getJSONObject(n).getString("nickname") ) ) } val description = properties.getString("description") val type_const = properties.getString("type") val creationDate = formatter.parseDateTime(properties.getString("date_created")) val type = when (type_const) { "wrong_turn" -> MapdustError.ERROR_TYPE.WRONG_TURN "bad_routing" -> MapdustError.ERROR_TYPE.BAD_ROUTING "oneway_road" -> MapdustError.ERROR_TYPE.ONEWAY_ROAD "blocked_street" -> MapdustError.ERROR_TYPE.BLOCKED_STREET "missing_street" -> MapdustError.ERROR_TYPE.MISSING_STREET "wrong_roundabout" -> MapdustError.ERROR_TYPE.ROUNDABOUT_ISSUE "missing_speedlimit" -> MapdustError.ERROR_TYPE.MISSING_SPEED_INFO else -> MapdustError.ERROR_TYPE.OTHER } val mapdustError = MapdustError(GeoPoint(lat, lon), id, creationDate, user, type, description, state) mapdustError.Comments = comments return mapdustError } suspend fun parseAddBug(data: String): Long = withContext(Dispatchers.Default) { val json = JSONObject(data) json.getLong("id") } } }
mit
65a81f89623f66367ae3a37dfdc8bb22
35.644444
113
0.600364
4.793605
false
false
false
false
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/hid/state/ButtonTimedState.kt
1
1257
package org.snakeskin.hid.state import org.snakeskin.hid.listener.ButtonHoldListener import org.snakeskin.executor.ExceptionHandlingRunnable /** * @author Cameron Earle * @version 12/12/2018 * */ class ButtonTimedState(val listener: ButtonHoldListener): IControlSurfaceState { private var risingEdgeTimestamp = 0.0 private var eventFired = false override fun update(timestamp: Double): Boolean { if (listener.surface.read()) { //Button is held if (risingEdgeTimestamp == 0.0) risingEdgeTimestamp = timestamp //Register timestamp if it's not already set if (timestamp - risingEdgeTimestamp >= listener.holdDurationS) { //Measure dt, if it's greater than the duration we have an event //We only want to fire the event once per hold, so this ensures that if (!eventFired) { //If we haven't fired the event eventFired = true //Now we have return true } } } else { //Button is released, reset everything risingEdgeTimestamp = 0.0 eventFired = false } return false } override val action = ExceptionHandlingRunnable { listener.action(true) } }
gpl-3.0
b076c8604c99b729c30e3f339260bf81
33.944444
141
0.639618
4.587591
false
false
false
false