path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/trees/BaseTree.kt
spbu-coding-2023
772,807,981
false
{"Kotlin": 161460}
package src.trees import src.trees.nodes.BaseNode abstract class BaseTree<T : Comparable<T>, N : BaseNode<T, N>> { open var root: N? = null abstract fun createNode(key: T, data:Any): N abstract fun add(key: T, data: Any): N? abstract fun find(key: T): N? abstract fun delete(key: T): N? abstract fun iter(): MutableList<Pair<T,Any>> }
1
Kotlin
0
0
dcfd05818e957c66613e1cd93bc9845efc7243cf
367
trees-14
MIT License
app/src/main/java/com/masterplus/notex/roomdb/repos/concrete/BookRepo.kt
Ramazan713
458,716,624
false
null
package com.masterplus.notex.roomdb.repos.concrete import androidx.lifecycle.LiveData import com.masterplus.notex.models.copymove.CopyMoveItem import com.masterplus.notex.roomdb.entities.Book import com.masterplus.notex.roomdb.repos.abstraction.IBookRepo import com.masterplus.notex.roomdb.services.BookDao import com.masterplus.notex.roomdb.views.BookCountView import javax.inject.Inject class BookRepo @Inject constructor(private val bookDao: BookDao):IBookRepo { override fun getLiveBookCountViews(): LiveData<List<BookCountView>> { return bookDao.getLiveBookCountViews() } override suspend fun getBookCountView(bookId: Long): BookCountView { return bookDao.getBookCountView(bookId) } override suspend fun insertBook(book: Book):Long{ return bookDao.insertBook(book) } override suspend fun updateNoteBookId(noteId: Long, bookId: Long) { bookDao.updateNoteBookId(bookId, noteId) } override suspend fun getBook(bookId: Long): Book { return bookDao.getBook(bookId) } override suspend fun renameBook(newName: String, bookId: Long) { bookDao.renameBook(newName, bookId) } override suspend fun deleteBookWithId(bookId: Long) { bookDao.deleteBookWithId(bookId) bookDao.deleteBookIdFromNote(bookId) } override suspend fun changeBookAttrVisibility(bookId: Long, isAllTypeVisible: Boolean) { bookDao.changeBookAttrVisibility(bookId, isAllTypeVisible) bookDao.changeBookAttrVisibilityForNote(bookId, isAllTypeVisible) } override suspend fun getUnSelectedNoteForBook(): Int { return bookDao.getUnSelectedNoteForBook() } override fun getAllLiveCopyMoveItemsFromBooks(): LiveData<List<CopyMoveItem>> { return bookDao.getAllLiveCopyMoveItemsFromBooks() } override fun getNullableLiveBook(bookId: Long): LiveData<Book?> { return bookDao.getNullableLiveBook(bookId) } }
0
Kotlin
0
0
886e40f402573bb2af517432bec48fa5628a5a0d
1,960
Note-X
Apache License 2.0
constraintlayout/compose/src/androidTest/java/androidx/constraintlayout/compose/MotionLayoutTest.kt
androidx
212,409,034
false
null
/* * Copyright (C) 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.constraintlayout.compose import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.LocalTextStyle import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Person import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.size import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.test.R import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import kotlin.test.assertEquals import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalMotionApi::class) @MediumTest @RunWith(AndroidJUnit4::class) internal class MotionLayoutTest { @get:Rule val rule = createComposeRule() /** * Tests that [MotionLayoutScope.motionFontSize] works as expected. * * See custom_text_size_scene.json5 */ @Test fun testCustomTextSize() { var animateToEnd by mutableStateOf(false) rule.setContent { val progress by animateFloatAsState(targetValue = if (animateToEnd) 1.0f else 0f) CustomTextSize( modifier = Modifier.size(200.dp), progress = progress ) } rule.waitForIdle() var usernameSize = rule.onNodeWithTag("username").getUnclippedBoundsInRoot().size // TextSize is 18sp at the start. Since getting the resulting dimensions of the text is not // straightforward, the values were obtained by running the test assertEquals(55.dp.value, usernameSize.width.value, absoluteTolerance = 0.5f) assertEquals(25.dp.value, usernameSize.height.value, absoluteTolerance = 0.5f) animateToEnd = true rule.waitForIdle() usernameSize = rule.onNodeWithTag("username").getUnclippedBoundsInRoot().size // TextSize is 12sp at the end. Results in approx. 66% of the original text height assertEquals(35.dp.value, usernameSize.width.value, absoluteTolerance = 0.5f) assertEquals(17.dp.value, usernameSize.height.value, absoluteTolerance = 0.5f) } @Test fun testCustomKeyFrameAttributes() { val progress: MutableState<Float> = mutableStateOf(0f) rule.setContent { MotionLayout( motionScene = MotionScene { val element = createRefFor("element") defaultTransition( from = constraintSet { constrain(element) { customColor("color", Color.White) customDistance("distance", 0.dp) customFontSize("fontSize", 0.sp) customInt("int", 0) } }, to = constraintSet { constrain(element) { customColor("color", Color.Black) customDistance("distance", 10.dp) customFontSize("fontSize", 20.sp) customInt("int", 30) } } ) { keyAttributes(element) { frame(50) { customColor("color", Color.Red) customDistance("distance", 20.dp) customFontSize("fontSize", 30.sp) customInt("int", 40) } } } }, progress = progress.value, modifier = Modifier.size(200.dp) ) { val props by motionProperties(id = "element") Column(Modifier.layoutId("element")) { Text( text = "Color: #${props.color("color").toArgb().toUInt().toString(16)}" ) Text( text = "Distance: ${props.distance("distance")}" ) Text( text = "FontSize: ${props.fontSize("fontSize")}" ) Text( text = "Int: ${props.int("int")}" ) } } } rule.waitForIdle() progress.value = 0.25f rule.waitForIdle() rule.onNodeWithText("Color: #ffffbaba").assertExists() rule.onNodeWithText("Distance: 10.0.dp").assertExists() rule.onNodeWithText("FontSize: 15.0.sp").assertExists() rule.onNodeWithText("Int: 20").assertExists() progress.value = 0.75f rule.waitForIdle() rule.onNodeWithText("Color: #ffba0000").assertExists() rule.onNodeWithText("Distance: 15.0.dp").assertExists() rule.onNodeWithText("FontSize: 25.0.sp").assertExists() rule.onNodeWithText("Int: 35").assertExists() } } @OptIn(ExperimentalMotionApi::class) @Composable private fun CustomTextSize(modifier: Modifier, progress: Float) { val context = LocalContext.current CompositionLocalProvider( LocalDensity provides Density(1f, 1f), LocalTextStyle provides TextStyle( fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Normal ) ) { MotionLayout( motionScene = MotionScene( content = context .resources .openRawResource(R.raw.custom_text_size_scene) .readBytes() .decodeToString() ), progress = progress, modifier = modifier ) { val profilePicProperties = motionProperties(id = "profile_pic") Box( modifier = Modifier .layoutTestId("box") .background(Color.DarkGray) ) Image( imageVector = Icons.Default.Person, contentDescription = null, modifier = Modifier .clip(CircleShape) .border( width = 2.dp, color = profilePicProperties.value.color("background"), shape = CircleShape ) .layoutTestId("profile_pic") ) Text( text = "Hello", fontSize = motionFontSize("username", "textSize"), modifier = Modifier.layoutTestId("username"), color = profilePicProperties.value.color("background") ) } } }
83
null
164
986
de916779a3065bd23e21f9180bf6af62468b5518
8,718
constraintlayout
Apache License 2.0
app/src/main/java/com/vaibhav/assignmenthub/data/repo/PreferencesRepo.kt
Vaibhav2002
363,311,426
false
null
package com.vaibhav.assignmenthub.data.repo import android.content.SharedPreferences import com.vaibhav.assignmenthub.data.models.User import com.vaibhav.assignmenthub.utils.ON_BOARDING_SAVE_KEY import com.vaibhav.assignmenthub.utils.USER_SAVE_KEY import com.vaibhav.assignmenthub.utils.getUserDataFromString import com.vaibhav.assignmenthub.utils.getUserStringForSaving import javax.inject.Inject class PreferencesRepo @Inject constructor(private val sharedPref: SharedPreferences) { fun isUserLoggedIn() = sharedPref.contains(USER_SAVE_KEY) fun isFirstTime() = sharedPref.getBoolean(ON_BOARDING_SAVE_KEY, true) fun setOnBoardingComplete() = sharedPref.edit().putBoolean(ON_BOARDING_SAVE_KEY, false).apply() fun getUserData(): User? { val userData = sharedPref.getString(USER_SAVE_KEY, null) return userData?.let { getUserDataFromString(userData) } } fun saveUserData(user: User) { val userData = getUserStringForSaving(user) sharedPref.edit().putString(USER_SAVE_KEY, userData).apply() } fun removeUserDate() = sharedPref.edit().remove(USER_SAVE_KEY).apply() }
0
Kotlin
0
2
a2a2a29a64bc32fb5b0f81f9fd1389ddbc1e9147
1,155
AssignmentHub
Apache License 2.0
app/src/main/java/com/by_syk/onetapcdutnet/util/C.kt
by-syk
93,934,091
false
null
/* * Copyright 2017 By_syk * * 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.by_syk.onetapcdutnet.util import android.os.Build /** * Created by By_syk on 2017-06-09. */ object C { val SDK = Build.VERSION.SDK_INT val LOG_TAG = "ONE_TAP_CDUT_NET" // 校园网登录地址 val CAMPUS_NET_URL = "http://172.20.255.252" // 多组备用登录帐号、密码 val ACCOUNTS = arrayOf( "", "", "", "", "", "", "", "" ) }
0
Kotlin
1
7
ea6c5dbd32147f3daa91e8bd83f0a45209485d5e
983
OneTapCdutNet
Apache License 2.0
kotlin-typescript/src/main/generated/typescript/raw/isTypeAssertionExpression.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("typescript") package typescript.raw import typescript.Node internal external fun isTypeAssertionExpression(node: Node): Boolean /* node is TypeAssertion */
10
Kotlin
7
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
220
kotlin-wrappers
Apache License 2.0
petJournal/app/src/main/java/com/soujunior/petjournal/ui/screens_app/screens_pets/introRegisterPetScreen/IntroRegisterPetViewModel.kt
PetJournal
597,478,245
false
{"Kotlin": 592691}
package com.soujunior.petjournal.ui.screens_app.screens_pets.introRegisterPetScreen import androidx.lifecycle.ViewModel import com.soujunior.petjournal.ui.states.TaskState import com.soujunior.petjournal.ui.util.ValidationEvent import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.receiveAsFlow abstract class IntroRegisterPetViewModel : ViewModel() { abstract val name: StateFlow<String?> abstract val visualizedScreen: StateFlow<Boolean> abstract val message: StateFlow<String> abstract val validationEventChannel: Channel<ValidationEvent> open val validationEvents: Flow<ValidationEvent> get() = validationEventChannel.receiveAsFlow() abstract val taskState: StateFlow<TaskState> abstract fun success() abstract fun failed(exception: Throwable?) abstract fun setWasViewed() abstract fun getName() abstract fun getWasViewed() }
5
Kotlin
5
9
3be9bf2c8f730f9a87299aa0a6bc913cfe9d915b
984
petjournal.android
MIT License
src/main/kotlin/example/com/model/OrderModel.kt
SajalDevX
824,813,053
false
{"Kotlin": 244501}
package example.com.model import example.com.dao.order.entity.OrderEntity import example.com.dao.order.entity.OrderItems import kotlinx.serialization.Serializable @Serializable data class AddOrder( val quantity: Int, val subTotal: Float, val total: Float, val shippingCharge: Float, val orderStatus: String?="pending", val orderItems: MutableList<OrderItems> ) @Serializable data class OrderData( val order: OrderEntity? = null, val orders: List<OrderEntity> = emptyList() ) @Serializable data class OrderResponse( val success: Boolean, val message: String, val data: OrderData? = null )
0
Kotlin
0
1
1d168bcfc856d890ee536686e669e92750fde153
635
E-CommerceBackend
curl License
kds/src/commonTest/kotlin/com/soywiz/kds/extensions/MapWhileTest.kt
korlibs
110,368,329
false
null
package com.soywiz.kds.extensions import com.soywiz.kds.* import kotlin.test.* class MapWhileTest { @Test fun test() { assertEquals(listOf(0, 1, 2, 3), mapWhile({ it < 4 }) { it }) assertEquals(listOf(0, 1, 2, 3), mapWhileArray({ it < 4 }) { it }.toList()) assertEquals(intArrayOf(0, 1, 2, 3).toList(), mapWhileInt({ it < 4 }) { it }.toList()) assertEquals(floatArrayOf(0f, 1f, 2f, 3f).toList(), mapWhileFloat({ it < 4 }) { it.toFloat() }.toList()) assertEquals(doubleArrayOf(0.0, 1.0, 2.0, 3.0).toList(), mapWhileDouble({ it < 4 }) { it.toDouble() }.toList()) } @Test fun test2() { val iterator = listOf(1, 2, 3).iterator() assertEquals(listOf(1, 2, 3), mapWhile({ iterator.hasNext() }) { iterator.next()}) } }
1
Kotlin
8
50
cc2397e7a575412dfa6e3850317c59b168356b76
794
kds
Creative Commons Zero v1.0 Universal
ecommerce-cart/src/main/kotlin/com/kotato/context/ecommerce/modules/cart/infrastructure/CartRepositoryConfiguration.kt
kotato
110,930,032
false
null
package com.kotato.context.ecommerce.modules.cart.infrastructure import com.kotato.context.ecommerce.modules.cart.domain.Cart import org.axonframework.commandhandling.model.Repository import org.axonframework.common.caching.Cache import org.axonframework.eventsourcing.AggregateFactory import org.axonframework.eventsourcing.CachingEventSourcingRepository import org.axonframework.eventsourcing.Snapshotter import org.axonframework.eventsourcing.eventstore.EventStore import org.axonframework.spring.eventsourcing.SpringPrototypeAggregateFactory import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration open class CartRepositoryConfiguration { @Bean open fun cartAggregateFactory(): AggregateFactory<Cart> = SpringPrototypeAggregateFactory<Cart>().also { it.setPrototypeBeanName(Cart::class.simpleName!!.toLowerCase()) } @Bean open fun cartRepository(snapshotter: Snapshotter, eventStore: EventStore, cache: Cache): Repository<Cart> = CachingEventSourcingRepository(cartAggregateFactory(), eventStore, cache) }
2
Kotlin
26
25
15db3d036f273de1bf4bb603398a0d24bc3c6ade
1,207
axon-examples
MIT License
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/Mappings.kt
ech0s7r
103,114,220
true
{"Kotlin": 3453319, "C++": 723301, "C": 158624, "Groovy": 43736, "Protocol Buffer": 11804, "JavaScript": 6561, "Batchfile": 6131, "Shell": 6111, "Objective-C++": 4076, "Pascal": 1698, "Objective-C": 1391, "Makefile": 1341, "Python": 1086, "Java": 782, "HTML": 185}
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.indexer.* interface DeclarationMapper { fun getKotlinNameForPointed(structDecl: StructDecl): String fun isMappedToStrict(enumDef: EnumDef): Boolean fun getKotlinNameForValue(enumDef: EnumDef): String } val PrimitiveType.kotlinType: String get() = when (this) { is CharType -> "kotlin.Byte" is BoolType -> "kotlin.Boolean" // TODO: C primitive types should probably be generated as type aliases for Kotlin types. is IntegerType -> when (this.size) { 1 -> "kotlin.Byte" 2 -> "kotlin.Short" 4 -> "kotlin.Int" 8 -> "kotlin.Long" else -> TODO(this.toString()) } is FloatingType -> when (this.size) { 4 -> "kotlin.Float" 8 -> "kotlin.Double" else -> TODO(this.toString()) } else -> throw NotImplementedError() } private val PrimitiveType.bridgedType: BridgedType get() { val kotlinType = this.kotlinType return BridgedType.values().single { it.kotlinType == kotlinType } } private val ObjCPointer.isNullable: Boolean get() = this.nullability != ObjCPointer.Nullability.NonNull /** * Describes the Kotlin types used to represent some C type. */ sealed class TypeMirror(val pointedTypeName: String, val info: TypeInfo) { /** * Type to be used in bindings for argument or return value. */ abstract val argType: String /** * Mirror for C type to be represented in Kotlin as by-value type. */ class ByValue(pointedTypeName: String, info: TypeInfo, val valueTypeName: String) : TypeMirror(pointedTypeName, info) { override val argType: String get() = valueTypeName + if (info is TypeInfo.Pointer || (info is TypeInfo.ObjCPointerInfo && info.type.isNullable)) "?" else "" } /** * Mirror for C type to be represented in Kotlin as by-ref type. */ class ByRef(pointedTypeName: String, info: TypeInfo) : TypeMirror(pointedTypeName, info) { override val argType: String get() = "CValue<$pointedTypeName>" } } /** * Describes various type conversions for [TypeMirror]. */ sealed class TypeInfo { /** * The conversion from [TypeMirror.argType] to [bridgedType]. */ abstract fun argToBridged(name: String): String /** * The conversion from [bridgedType] to [TypeMirror.argType]. */ abstract fun argFromBridged(name: String): String abstract val bridgedType: BridgedType open fun cFromBridged(name: String): String = name open fun cToBridged(name: String): String = name /** * If this info is for [TypeMirror.ByValue], then this method describes how to * construct pointed-type from value type. */ abstract fun constructPointedType(valueType: String): String class Primitive(override val bridgedType: BridgedType, val varTypeName: String) : TypeInfo() { override fun argToBridged(name: String) = name override fun argFromBridged(name: String) = name override fun constructPointedType(valueType: String) = "${varTypeName}Of<$valueType>" } class Boolean : TypeInfo() { override fun argToBridged(name: String) = "$name.toByte()" override fun argFromBridged(name: String) = "$name.toBoolean()" override val bridgedType: BridgedType get() = BridgedType.BYTE override fun cFromBridged(name: String) = "($name) ? 1 : 0" override fun cToBridged(name: String) = "($name) ? 1 : 0" override fun constructPointedType(valueType: String) = "BooleanVarOf<$valueType>" } class Enum(val className: String, override val bridgedType: BridgedType) : TypeInfo() { override fun argToBridged(name: String) = "$name.value" override fun argFromBridged(name: String) = "$className.byValue($name)" override fun constructPointedType(valueType: String) = "$className.Var" // TODO: improve } class Pointer(val pointee: String) : TypeInfo() { override fun argToBridged(name: String) = "$name.rawValue" override fun argFromBridged(name: String) = "interpretCPointer<$pointee>($name)" override val bridgedType: BridgedType get() = BridgedType.NATIVE_PTR override fun cFromBridged(name: String) = "(void*)$name" // Note: required for JVM override fun constructPointedType(valueType: String) = "CPointerVarOf<$valueType>" } class ObjCPointerInfo(val typeName: String, val type: ObjCPointer) : TypeInfo() { override fun argToBridged(name: String) = "$name.rawPtr" override fun argFromBridged(name: String) = "interpretObjCPointerOrNull<$typeName>($name)" + if (type.isNullable) "" else "!!" override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER override fun constructPointedType(valueType: String) = "ObjCObjectVar<$valueType>" } class NSString(val type: ObjCPointer) : TypeInfo() { override fun argToBridged(name: String) = "CreateNSStringFromKString($name)" override fun argFromBridged(name: String) = "CreateKStringFromNSString($name)" + if (type.isNullable) "" else "!!" override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER override fun constructPointedType(valueType: String): String { return "ObjCStringVarOf<$valueType>" } } class ByRef(val pointed: String) : TypeInfo() { override fun argToBridged(name: String) = error(pointed) override fun argFromBridged(name: String) = error(pointed) override val bridgedType: BridgedType get() = error(pointed) override fun cFromBridged(name: String) = error(pointed) override fun cToBridged(name: String) = error(pointed) // TODO: this method must not exist override fun constructPointedType(valueType: String): String = error(pointed) } } fun mirrorPrimitiveType(type: PrimitiveType): TypeMirror.ByValue { val varTypeName = when (type) { is CharType -> "ByteVar" is BoolType -> "BooleanVar" is IntegerType -> when (type.size) { 1 -> "ByteVar" 2 -> "ShortVar" 4 -> "IntVar" 8 -> "LongVar" else -> TODO(type.toString()) } is FloatingType -> when (type.size) { 4 -> "FloatVar" 8 -> "DoubleVar" else -> TODO(type.toString()) } else -> TODO(type.toString()) } val info = if (type == BoolType) { TypeInfo.Boolean() } else { TypeInfo.Primitive(type.bridgedType, varTypeName) } return TypeMirror.ByValue(varTypeName, info, type.kotlinType) } private fun byRefTypeMirror(pointedTypeName: String) : TypeMirror.ByRef { val info = TypeInfo.ByRef(pointedTypeName) return TypeMirror.ByRef(pointedTypeName, info) } fun mirror(declarationMapper: DeclarationMapper, type: Type): TypeMirror = when (type) { is PrimitiveType -> mirrorPrimitiveType(type) is RecordType -> byRefTypeMirror(declarationMapper.getKotlinNameForPointed(type.decl).asSimpleName()) is EnumType -> { val kotlinName = declarationMapper.getKotlinNameForValue(type.def) when { declarationMapper.isMappedToStrict(type.def) -> { val classSimpleName = kotlinName.asSimpleName() val bridgedType = (type.def.baseType.unwrapTypedefs() as PrimitiveType).bridgedType val info = TypeInfo.Enum(classSimpleName, bridgedType) TypeMirror.ByValue("$classSimpleName.Var", info, classSimpleName) } !type.def.isAnonymous -> { val baseTypeMirror = mirror(declarationMapper, type.def.baseType) TypeMirror.ByValue("${kotlinName}Var", baseTypeMirror.info, kotlinName.asSimpleName()) } else -> mirror(declarationMapper, type.def.baseType) } } is PointerType -> { val pointeeType = type.pointeeType val unwrappedPointeeType = pointeeType.unwrapTypedefs() if (unwrappedPointeeType is VoidType) { val info = TypeInfo.Pointer("COpaque") TypeMirror.ByValue("COpaquePointerVar", info, "COpaquePointer") } else if (unwrappedPointeeType is ArrayType) { mirror(declarationMapper, pointeeType) } else { val pointeeMirror = mirror(declarationMapper, pointeeType) val info = TypeInfo.Pointer(pointeeMirror.pointedTypeName) TypeMirror.ByValue("CPointerVar<${pointeeMirror.pointedTypeName}>", info, "CPointer<${pointeeMirror.pointedTypeName}>") } } is ArrayType -> { // TODO: array type doesn't exactly correspond neither to pointer nor to value. val elemTypeMirror = mirror(declarationMapper, type.elemType) if (type.elemType.unwrapTypedefs() is ArrayType) { elemTypeMirror } else { val info = TypeInfo.Pointer(elemTypeMirror.pointedTypeName) TypeMirror.ByValue("CArrayPointerVar<${elemTypeMirror.pointedTypeName}>", info, "CArrayPointer<${elemTypeMirror.pointedTypeName}>") } } is FunctionType -> byRefTypeMirror("CFunction<${getKotlinFunctionType(declarationMapper, type)}>") is Typedef -> { val baseType = mirror(declarationMapper, type.def.aliased) val name = type.def.name when (baseType) { is TypeMirror.ByValue -> TypeMirror.ByValue("${name}Var", baseType.info, name.asSimpleName()) is TypeMirror.ByRef -> TypeMirror.ByRef(name.asSimpleName(), baseType.info) } } is ObjCPointer -> objCPointerMirror(type) else -> TODO(type.toString()) } private fun objCPointerMirror(type: ObjCPointer): TypeMirror.ByValue { if (type is ObjCObjectPointer && type.def.name == "NSString") { val info = TypeInfo.NSString(type) val valueType = if (type.isNullable) "String?" else "String" return TypeMirror.ByValue(info.constructPointedType(valueType), info, valueType) } val typeName = when (type) { is ObjCIdType -> type.protocols.firstOrNull()?.kotlinName ?: "ObjCObject" is ObjCClassPointer -> "ObjCClass" is ObjCObjectPointer -> type.def.name is ObjCInstanceType -> TODO(type.toString()) // Must have already been handled. } return objCPointerMirror(typeName.asSimpleName(), type) } private fun objCPointerMirror(typeName: String, type: ObjCPointer): TypeMirror.ByValue { val valueType = if (type.isNullable) "$typeName?" else typeName return TypeMirror.ByValue("ObjCObjectVar<$valueType>", TypeInfo.ObjCPointerInfo(typeName, type), typeName) } fun getKotlinFunctionType(declarationMapper: DeclarationMapper, type: FunctionType): String { val returnType = if (type.returnType.unwrapTypedefs() is VoidType) { "Unit" } else { mirror(declarationMapper, type.returnType).argType } return "(" + type.parameterTypes.map { mirror(declarationMapper, it).argType }.joinToString(", ") + ") -> " + returnType }
0
Kotlin
0
0
1186bc22b442023f1a5c367438cda64e57e2a36c
12,041
kotlin-native
Apache License 2.0
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/Mappings.kt
ech0s7r
103,114,220
true
{"Kotlin": 3453319, "C++": 723301, "C": 158624, "Groovy": 43736, "Protocol Buffer": 11804, "JavaScript": 6561, "Batchfile": 6131, "Shell": 6111, "Objective-C++": 4076, "Pascal": 1698, "Objective-C": 1391, "Makefile": 1341, "Python": 1086, "Java": 782, "HTML": 185}
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.indexer.* interface DeclarationMapper { fun getKotlinNameForPointed(structDecl: StructDecl): String fun isMappedToStrict(enumDef: EnumDef): Boolean fun getKotlinNameForValue(enumDef: EnumDef): String } val PrimitiveType.kotlinType: String get() = when (this) { is CharType -> "kotlin.Byte" is BoolType -> "kotlin.Boolean" // TODO: C primitive types should probably be generated as type aliases for Kotlin types. is IntegerType -> when (this.size) { 1 -> "kotlin.Byte" 2 -> "kotlin.Short" 4 -> "kotlin.Int" 8 -> "kotlin.Long" else -> TODO(this.toString()) } is FloatingType -> when (this.size) { 4 -> "kotlin.Float" 8 -> "kotlin.Double" else -> TODO(this.toString()) } else -> throw NotImplementedError() } private val PrimitiveType.bridgedType: BridgedType get() { val kotlinType = this.kotlinType return BridgedType.values().single { it.kotlinType == kotlinType } } private val ObjCPointer.isNullable: Boolean get() = this.nullability != ObjCPointer.Nullability.NonNull /** * Describes the Kotlin types used to represent some C type. */ sealed class TypeMirror(val pointedTypeName: String, val info: TypeInfo) { /** * Type to be used in bindings for argument or return value. */ abstract val argType: String /** * Mirror for C type to be represented in Kotlin as by-value type. */ class ByValue(pointedTypeName: String, info: TypeInfo, val valueTypeName: String) : TypeMirror(pointedTypeName, info) { override val argType: String get() = valueTypeName + if (info is TypeInfo.Pointer || (info is TypeInfo.ObjCPointerInfo && info.type.isNullable)) "?" else "" } /** * Mirror for C type to be represented in Kotlin as by-ref type. */ class ByRef(pointedTypeName: String, info: TypeInfo) : TypeMirror(pointedTypeName, info) { override val argType: String get() = "CValue<$pointedTypeName>" } } /** * Describes various type conversions for [TypeMirror]. */ sealed class TypeInfo { /** * The conversion from [TypeMirror.argType] to [bridgedType]. */ abstract fun argToBridged(name: String): String /** * The conversion from [bridgedType] to [TypeMirror.argType]. */ abstract fun argFromBridged(name: String): String abstract val bridgedType: BridgedType open fun cFromBridged(name: String): String = name open fun cToBridged(name: String): String = name /** * If this info is for [TypeMirror.ByValue], then this method describes how to * construct pointed-type from value type. */ abstract fun constructPointedType(valueType: String): String class Primitive(override val bridgedType: BridgedType, val varTypeName: String) : TypeInfo() { override fun argToBridged(name: String) = name override fun argFromBridged(name: String) = name override fun constructPointedType(valueType: String) = "${varTypeName}Of<$valueType>" } class Boolean : TypeInfo() { override fun argToBridged(name: String) = "$name.toByte()" override fun argFromBridged(name: String) = "$name.toBoolean()" override val bridgedType: BridgedType get() = BridgedType.BYTE override fun cFromBridged(name: String) = "($name) ? 1 : 0" override fun cToBridged(name: String) = "($name) ? 1 : 0" override fun constructPointedType(valueType: String) = "BooleanVarOf<$valueType>" } class Enum(val className: String, override val bridgedType: BridgedType) : TypeInfo() { override fun argToBridged(name: String) = "$name.value" override fun argFromBridged(name: String) = "$className.byValue($name)" override fun constructPointedType(valueType: String) = "$className.Var" // TODO: improve } class Pointer(val pointee: String) : TypeInfo() { override fun argToBridged(name: String) = "$name.rawValue" override fun argFromBridged(name: String) = "interpretCPointer<$pointee>($name)" override val bridgedType: BridgedType get() = BridgedType.NATIVE_PTR override fun cFromBridged(name: String) = "(void*)$name" // Note: required for JVM override fun constructPointedType(valueType: String) = "CPointerVarOf<$valueType>" } class ObjCPointerInfo(val typeName: String, val type: ObjCPointer) : TypeInfo() { override fun argToBridged(name: String) = "$name.rawPtr" override fun argFromBridged(name: String) = "interpretObjCPointerOrNull<$typeName>($name)" + if (type.isNullable) "" else "!!" override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER override fun constructPointedType(valueType: String) = "ObjCObjectVar<$valueType>" } class NSString(val type: ObjCPointer) : TypeInfo() { override fun argToBridged(name: String) = "CreateNSStringFromKString($name)" override fun argFromBridged(name: String) = "CreateKStringFromNSString($name)" + if (type.isNullable) "" else "!!" override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER override fun constructPointedType(valueType: String): String { return "ObjCStringVarOf<$valueType>" } } class ByRef(val pointed: String) : TypeInfo() { override fun argToBridged(name: String) = error(pointed) override fun argFromBridged(name: String) = error(pointed) override val bridgedType: BridgedType get() = error(pointed) override fun cFromBridged(name: String) = error(pointed) override fun cToBridged(name: String) = error(pointed) // TODO: this method must not exist override fun constructPointedType(valueType: String): String = error(pointed) } } fun mirrorPrimitiveType(type: PrimitiveType): TypeMirror.ByValue { val varTypeName = when (type) { is CharType -> "ByteVar" is BoolType -> "BooleanVar" is IntegerType -> when (type.size) { 1 -> "ByteVar" 2 -> "ShortVar" 4 -> "IntVar" 8 -> "LongVar" else -> TODO(type.toString()) } is FloatingType -> when (type.size) { 4 -> "FloatVar" 8 -> "DoubleVar" else -> TODO(type.toString()) } else -> TODO(type.toString()) } val info = if (type == BoolType) { TypeInfo.Boolean() } else { TypeInfo.Primitive(type.bridgedType, varTypeName) } return TypeMirror.ByValue(varTypeName, info, type.kotlinType) } private fun byRefTypeMirror(pointedTypeName: String) : TypeMirror.ByRef { val info = TypeInfo.ByRef(pointedTypeName) return TypeMirror.ByRef(pointedTypeName, info) } fun mirror(declarationMapper: DeclarationMapper, type: Type): TypeMirror = when (type) { is PrimitiveType -> mirrorPrimitiveType(type) is RecordType -> byRefTypeMirror(declarationMapper.getKotlinNameForPointed(type.decl).asSimpleName()) is EnumType -> { val kotlinName = declarationMapper.getKotlinNameForValue(type.def) when { declarationMapper.isMappedToStrict(type.def) -> { val classSimpleName = kotlinName.asSimpleName() val bridgedType = (type.def.baseType.unwrapTypedefs() as PrimitiveType).bridgedType val info = TypeInfo.Enum(classSimpleName, bridgedType) TypeMirror.ByValue("$classSimpleName.Var", info, classSimpleName) } !type.def.isAnonymous -> { val baseTypeMirror = mirror(declarationMapper, type.def.baseType) TypeMirror.ByValue("${kotlinName}Var", baseTypeMirror.info, kotlinName.asSimpleName()) } else -> mirror(declarationMapper, type.def.baseType) } } is PointerType -> { val pointeeType = type.pointeeType val unwrappedPointeeType = pointeeType.unwrapTypedefs() if (unwrappedPointeeType is VoidType) { val info = TypeInfo.Pointer("COpaque") TypeMirror.ByValue("COpaquePointerVar", info, "COpaquePointer") } else if (unwrappedPointeeType is ArrayType) { mirror(declarationMapper, pointeeType) } else { val pointeeMirror = mirror(declarationMapper, pointeeType) val info = TypeInfo.Pointer(pointeeMirror.pointedTypeName) TypeMirror.ByValue("CPointerVar<${pointeeMirror.pointedTypeName}>", info, "CPointer<${pointeeMirror.pointedTypeName}>") } } is ArrayType -> { // TODO: array type doesn't exactly correspond neither to pointer nor to value. val elemTypeMirror = mirror(declarationMapper, type.elemType) if (type.elemType.unwrapTypedefs() is ArrayType) { elemTypeMirror } else { val info = TypeInfo.Pointer(elemTypeMirror.pointedTypeName) TypeMirror.ByValue("CArrayPointerVar<${elemTypeMirror.pointedTypeName}>", info, "CArrayPointer<${elemTypeMirror.pointedTypeName}>") } } is FunctionType -> byRefTypeMirror("CFunction<${getKotlinFunctionType(declarationMapper, type)}>") is Typedef -> { val baseType = mirror(declarationMapper, type.def.aliased) val name = type.def.name when (baseType) { is TypeMirror.ByValue -> TypeMirror.ByValue("${name}Var", baseType.info, name.asSimpleName()) is TypeMirror.ByRef -> TypeMirror.ByRef(name.asSimpleName(), baseType.info) } } is ObjCPointer -> objCPointerMirror(type) else -> TODO(type.toString()) } private fun objCPointerMirror(type: ObjCPointer): TypeMirror.ByValue { if (type is ObjCObjectPointer && type.def.name == "NSString") { val info = TypeInfo.NSString(type) val valueType = if (type.isNullable) "String?" else "String" return TypeMirror.ByValue(info.constructPointedType(valueType), info, valueType) } val typeName = when (type) { is ObjCIdType -> type.protocols.firstOrNull()?.kotlinName ?: "ObjCObject" is ObjCClassPointer -> "ObjCClass" is ObjCObjectPointer -> type.def.name is ObjCInstanceType -> TODO(type.toString()) // Must have already been handled. } return objCPointerMirror(typeName.asSimpleName(), type) } private fun objCPointerMirror(typeName: String, type: ObjCPointer): TypeMirror.ByValue { val valueType = if (type.isNullable) "$typeName?" else typeName return TypeMirror.ByValue("ObjCObjectVar<$valueType>", TypeInfo.ObjCPointerInfo(typeName, type), typeName) } fun getKotlinFunctionType(declarationMapper: DeclarationMapper, type: FunctionType): String { val returnType = if (type.returnType.unwrapTypedefs() is VoidType) { "Unit" } else { mirror(declarationMapper, type.returnType).argType } return "(" + type.parameterTypes.map { mirror(declarationMapper, it).argType }.joinToString(", ") + ") -> " + returnType }
0
Kotlin
0
0
1186bc22b442023f1a5c367438cda64e57e2a36c
12,041
kotlin-native
Apache License 2.0
app/src/main/java/com/lianyi/paimonsnotebook/ui/widgets/core/BaseAppWidget.kt
QooLianyi
435,314,581
false
{"Kotlin": 1942953}
package com.lianyi.paimonsnotebook.ui.widgets.core import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.RemoteViews import com.lianyi.paimonsnotebook.common.application.PaimonsNotebookApplication import com.lianyi.paimonsnotebook.common.database.PaimonsNotebookDatabase import com.lianyi.paimonsnotebook.common.view.HoyolabWebActivity import com.lianyi.paimonsnotebook.ui.screen.app_widget.view.AppWidgetConfigurationScreen import com.lianyi.paimonsnotebook.ui.screen.home.util.HomeHelper import com.lianyi.paimonsnotebook.ui.widgets.remoteviews.state.NoBindingRemoteViews import com.lianyi.paimonsnotebook.ui.widgets.util.AppWidgetHelper import com.lianyi.paimonsnotebook.ui.widgets.util.AppWidgetRemoViewsHelper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /* * 小组件基类 * */ open class BaseAppWidget : AppWidgetProvider() { private val dao by lazy { PaimonsNotebookDatabase.database.appWidgetBindingDao } private val context by lazy { PaimonsNotebookApplication.context } override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?, ) { appWidgetIds?.forEach { updateAppWidget(it, null) } } override fun onDeleted(context: Context?, appWidgetIds: IntArray?) { CoroutineScope(Dispatchers.IO).launch { appWidgetIds?.forEach { dao.deleteByAppWidgetId(it) } } super.onDeleted(context, appWidgetIds) } override fun onAppWidgetOptionsChanged( context: Context?, appWidgetManager: AppWidgetManager?, appWidgetId: Int, newOptions: Bundle? ) { updateAppWidget(appWidgetId, null) } override fun onReceive(context: Context, intent: Intent?) { val appWidgetId = intent?.getIntExtra(AppWidgetHelper.PARAM_APPWIDGET_ID, -1) ?: -1 when (intent?.action) { //由用户调用的刷新 AppWidgetHelper.ACTION_UPDATE_WIDGET -> { if (appWidgetId != -1) { updateAppWidget(appWidgetId, intent, true) } } //前往配置界面 AppWidgetHelper.ACTION_GO_CONFIGURATION -> { goAppWidgetConfigurationScreen(context, appWidgetId) } //前往验证界面 AppWidgetHelper.ACTION_GO_VALIDATE -> { val mid = intent.getStringExtra("mid") ?: "" goValidateScreen(context, mid) } } super.onReceive(context, intent) } /* * 更新组件 * * appWidgetId:组件id * intent:意图 * onlyUpdateStyle:是否只更新样式 * */ private fun updateAppWidget( appWidgetId: Int, intent: Intent?, notify: Boolean = false, ) { CoroutineScope(Dispatchers.IO).launch { val appWidgetBinding = dao.getAppWidgetBindingByAppWidgetId(appWidgetId) //如果获取的userMid不为空则获取组件绑定的用户 val user = if (appWidgetBinding?.userEntityMid?.isEmpty() == false) { appWidgetBinding.getUserEntity() } else { null } val views = if (appWidgetBinding == null) { NoBindingRemoteViews(appWidgetId, this@BaseAppWidget::class.java) } else { AppWidgetRemoViewsHelper.getRemoteViews( appWidgetBinding, user, intent ) } updateAppWidget(appWidgetId, views) } } //携带id与当前组件类名前往桌面组件配置界面 private fun goAppWidgetConfigurationScreen(context: Context, appWidgetId: Int) { val intent = Intent(context, AppWidgetConfigurationScreen::class.java).apply { putExtra(AppWidgetHelper.PARAM_APPWIDGET_ID, appWidgetId) putExtra( AppWidgetHelper.PARAM_APPWIDGET_CLASS_NAME, this@BaseAppWidget::class.java.name ) flags = Intent.FLAG_ACTIVITY_NEW_TASK } context.startActivity(intent) } private fun goValidateScreen(context: Context, mid: String) { HomeHelper.goActivityByIntentNewTask { component = ComponentName(context, HoyolabWebActivity::class.java) putExtra("mid", mid) } } //更新组件 private fun updateAppWidget(appWidgetId: Int, views: RemoteViews) { AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, views) } }
1
Kotlin
2
36
692b93b7e712903c795e1a2ce79859af14e2c197
4,734
PaimonsNotebook
MIT License
fearless-utils/src/main/java/jp/co/soramitsu/fearless_utils/encrypt/keypair/ethereum/EthereumKeypairFactory.kt
soramitsu
278,060,389
false
{"Kotlin": 620535, "Rust": 10891, "Java": 4260}
package jp.co.soramitsu.fearless_utils.encrypt.keypair.ethereum import jp.co.soramitsu.fearless_utils.encrypt.junction.Junction import jp.co.soramitsu.fearless_utils.encrypt.keypair.ECDSAUtils import jp.co.soramitsu.fearless_utils.encrypt.keypair.Keypair import jp.co.soramitsu.fearless_utils.encrypt.keypair.derivePublicKey import jp.co.soramitsu.fearless_utils.encrypt.keypair.generate import jp.co.soramitsu.fearless_utils.encrypt.keypair.substrate.KeypairWithSeed object EthereumKeypairFactory { fun generate(seed: ByteArray, junctions: List<Junction>): Keypair { return Bip32KeypairFactory.generate(seed, junctions) } fun createWithPrivateKey(privateKeyBytes: ByteArray): Keypair { return KeypairWithSeed( seed = privateKeyBytes, privateKey = privateKeyBytes, publicKey = ECDSAUtils.derivePublicKey(privateKeyOrSeed = privateKeyBytes) ) } }
4
Kotlin
9
18
7d5a4fc95c1f3cc227805fa8ee99be91abfe059a
926
fearless-utils-Android
Apache License 2.0
android/navigation/core/src/main/java/com/santukis/navigation/destination/Destination.kt
santukis
541,433,358
false
null
package com.santukis.navigation.destination import androidx.compose.runtime.Composable import androidx.navigation.* import com.santukis.viewmodels.core.events.OnUiEvent interface Destination { val template: String fun getArguments(): List<NamedNavArgument> = listOf() fun getDeepLinks(): List<NavDeepLink> = listOf() @Composable fun DestinationScreen( navController: NavController, backStackEntry: NavBackStackEntry, onUiEvent: (OnUiEvent) -> Unit ) fun navigate( navController: NavController, builder: NavOptionsBuilder.() -> Unit = {} ) }
0
Kotlin
0
2
686152e2bbf1a66072068dfb079d71409133684e
619
CleanArchitectureKMM
Apache License 2.0
tmp/arrays/youTrackTests/2323.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-31276 inline class A(val id: Int) { fun generate() { foo() } companion object { private val bar = "" private inline fun foo() { bar } } }
1
null
8
1
602285ec60b01eee473dcb0b08ce497b1c254983
220
bbfgradle
Apache License 2.0
tree-leaf/src/main/kotlin/org/hchery/treeleaf/service/authentication/login/GenerateResponse.kt
hchery
799,787,264
false
{"Kotlin": 60401, "Java": 11448}
package org.hchery.treeleaf.service.authentication.login import org.hchery.treeleaf.http.login.LoginResponse import org.hchery.treeleaf.service.authentication.token.AccessTokenService import org.hchery.treeleaf.service.authentication.token.RefreshTokenService import org.springframework.stereotype.Service /** * DATE: 2024/5/31 * AUTHOR: hchery * URL: https://github.com/hchery * EMAIL: <EMAIL> */ @Service class LoginResponseGenerator( private val accessTokenService: AccessTokenService, private val refreshTokenService: RefreshTokenService, ) { fun make(userId: String): LoginResponse { val response = LoginResponse() response.accessToken = accessTokenService.new(userId) response.refreshToken = refreshTokenService.new(userId) return response } }
0
Kotlin
0
0
5a1467c90ac14937a8f3cdbcb5403c264363daa7
806
TreeLeaf
MIT License
lib/src/commonMain/kotlin/dev/mpr/grpc/ProtoDsl.kt
mproberts
273,046,055
false
null
package dev.mpr.grpc @DslMarker annotation class ProtoDsl
0
Kotlin
0
0
90c55cbd7547610d7d4616a59f984fb41d3b2b82
59
grpc-kotlin-multiplatform
MIT License
lib/logical-types/src/main/kotlin/bankaccount/conversions/MoneyLogicalType.kt
holixon
713,986,002
false
null
package bankaccount.conversions import io.toolisticon.kotlin.avro.logical.StringLogicalType import io.toolisticon.kotlin.avro.logical.StringLogicalTypeFactory import io.toolisticon.kotlin.avro.logical.conversion.StringLogicalTypeConversion import io.toolisticon.kotlin.avro.logical.conversion.TypeConverter import io.toolisticon.kotlin.avro.serialization.serializer.StringLogicalTypeSerializer import io.toolisticon.kotlin.avro.serialization.spi.AvroSerializerModuleFactory import io.toolisticon.kotlin.avro.value.LogicalTypeName.Companion.toLogicalTypeName import kotlinx.serialization.modules.SerializersModule import org.javamoney.moneta.Money import java.util.* import javax.money.format.AmountFormatQuery import javax.money.format.MonetaryFormats object MoneyLogicalType : StringLogicalType("money".toLogicalTypeName()) { val convertedType = Money::class val conversion = MoneyConversion() val converter = object : TypeConverter<String, Money> { private val format = MonetaryFormats.getAmountFormat(AmountFormatQuery.of(Locale.GERMAN)) override fun fromAvro(value: String): Money { return Money.from(format.parse(value)) } override fun toAvro(value: Money): String { return format.format(value) } } class MoneyLogicalTypeFactory : StringLogicalTypeFactory<MoneyLogicalType>(logicalType = MoneyLogicalType) class MoneyConversion : StringLogicalTypeConversion<MoneyLogicalType, Money>( logicalType = MoneyLogicalType, convertedType = convertedType ) { override fun fromAvro(value: String): Money = converter.fromAvro(value) override fun toAvro(value: Money): String = converter.toAvro(value) } class MoneySerializer : StringLogicalTypeSerializer<MoneyLogicalType, Money>(conversion) class MoneySerializerModuleFactory : AvroSerializerModuleFactory { override fun invoke(): SerializersModule = SerializersModule { contextual(convertedType, MoneySerializer()) } } }
18
null
0
6
3fe8c0db966752edec13735c7043ef77d6478cc2
1,962
axon-avro
Apache License 2.0
app/src/main/kotlin/com.jdamcd.sudoku/scoreboard/LevelGraphView.kt
jdamcd
258,881,552
false
null
package com.jdamcd.sudoku.scoreboard import android.animation.ObjectAnimator import android.animation.PropertyValuesHolder import android.animation.ValueAnimator import android.animation.ValueAnimator.AnimatorUpdateListener import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import androidx.annotation.Keep import com.jdamcd.sudoku.R import java.util.Arrays class LevelGraphView(context: Context, attrs: AttributeSet) : View(context, attrs), AnimatorUpdateListener { private var counts: IntArray = IntArray(NUM_BARS) private val barWidths: IntArray = IntArray(NUM_BARS) private var graphWidth: Int = 0 private var barHeight: Int = 0 private val barColours: IntArray private val barPaint: Paint private var pendingAnimation: Boolean = false init { Arrays.fill(barWidths, MIN_WIDTH) barPaint = Paint() barColours = resources.getIntArray(R.array.level_colours) } fun setCounts(counts: IntArray) { this.counts = counts if (graphWidth == 0) { pendingAnimation = true } else { startBarAnimations() } } private fun startBarAnimations() { val animator = ObjectAnimator.ofPropertyValuesHolder( this, PropertyValuesHolder.ofInt("easyWidth", MIN_WIDTH, getBarWidth(0)), PropertyValuesHolder.ofInt("normalWidth", MIN_WIDTH, getBarWidth(1)), PropertyValuesHolder.ofInt("hardWidth", MIN_WIDTH, getBarWidth(2)), PropertyValuesHolder.ofInt("extremeWidth", MIN_WIDTH, getBarWidth(3)) ) animator.startDelay = ANIM_DELAY.toLong() animator.duration = ANIM_TIME.toLong() animator.interpolator = AccelerateDecelerateInterpolator() animator.addUpdateListener(this) animator.start() } override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { super.onSizeChanged(width, height, oldWidth, oldHeight) this.graphWidth = width barHeight = height / NUM_BARS if (pendingAnimation) { pendingAnimation = false startBarAnimations() } } public override fun onDraw(canvas: Canvas) { for (i in counts.indices) { drawBar(canvas, i) } } private fun drawBar(canvas: Canvas, i: Int) { barPaint.color = barColours[i % barColours.size] canvas.drawRect(0f, (i * barHeight).toFloat(), barWidths[i].toFloat(), ((i + 1) * barHeight).toFloat(), barPaint) } private fun getBarWidth(i: Int): Int { val max = counts.max() ?: 0 if (max > 0) { val barWidth = (counts[i].toFloat() / max.toFloat() * width).toInt() return if (barWidth > MIN_WIDTH) barWidth else MIN_WIDTH } return MIN_WIDTH } override fun onAnimationUpdate(animation: ValueAnimator) { invalidate() } /* * Setters required for ObjectAnimator to update widths */ @Keep fun setEasyWidth(width: Int) { barWidths[0] = width } @Keep fun setNormalWidth(width: Int) { barWidths[1] = width } @Keep fun setHardWidth(width: Int) { barWidths[2] = width } @Keep fun setExtremeWidth(width: Int) { barWidths[3] = width } companion object { private const val NUM_BARS = 4 private const val MIN_WIDTH = 10 private const val ANIM_DELAY = 500 private const val ANIM_TIME = 500 } }
2
Kotlin
19
62
a7d02c69d0ff4667ff56a83ef943d94d2838c3cc
3,679
material-sudoku
Apache License 2.0
app/src/main/java/io/aethibo/kart/features/product/presentation/ProductViewModel.kt
primepixel
626,035,115
false
null
package io.aethibo.kart.features.product.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import io.aethibo.kart.core.functional.onFailure import io.aethibo.kart.core.functional.onSuccess import io.aethibo.kart.features.product.domain.usecase.DeleteProductByIdUseCase import io.aethibo.kart.features.product.domain.usecase.GetProductByIdUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ProductViewModel @Inject constructor( private val getProductByIdUseCase: GetProductByIdUseCase, private val deleteProductByIdUseCase: DeleteProductByIdUseCase ) : ViewModel() { private val _state: MutableStateFlow<ProductUiState> = MutableStateFlow(ProductUiState()) val state: StateFlow<ProductUiState> = _state.asStateFlow() fun onIntent(productIntents: ProductIntents) { when (productIntents) { is ProductIntents.GetProductById -> getProductById(productIntents.id) is ProductIntents.DeleteProductById -> deleteProductById(productIntents.id) } } private fun getProductById(id: Int) { _state.update { oldValue -> oldValue.copy(isLoading = true, isError = false) } viewModelScope.launch { getProductByIdUseCase(id) .onSuccess { product -> _state.update { oldValue -> oldValue.copy( isLoading = false, product = product, isError = false ) } } .onFailure { _state.update { oldValue -> oldValue.copy( isLoading = false, product = null, isError = true ) } } } } private fun deleteProductById(id: Int) { _state.update { oldValue -> oldValue.copy(isLoading = true, isError = false) } viewModelScope.launch { deleteProductByIdUseCase(id) .onSuccess { product -> _state.update { oldValue -> oldValue.copy( isLoading = false, product = product, isError = false ) } } .onFailure { _state.update { oldValue -> oldValue.copy( isLoading = false, product = null, isError = true ) } } } } }
0
Kotlin
0
0
e4a6bc4c1c00d8e681c1172dbd864a2984ac1547
2,797
Kart
Apache License 2.0
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/ProjectCustomDataHost.kt
Zod-
117,608,814
true
{"C#": 1143106, "Kotlin": 115605, "ShaderLab": 69846, "Lex": 17789, "HLSL": 7370, "GLSL": 7015, "Java": 5283, "PowerShell": 2115, "CSS": 1370, "Batchfile": 216, "Shell": 100, "JavaScript": 68}
package com.jetbrains.rider.plugins.unity import com.intellij.ide.impl.ProjectUtil import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.jetbrains.rider.projectView.solution import com.jetbrains.rider.util.idea.LifetimedProjectComponent import com.jetbrains.rider.util.reactive.Property import com.jetbrains.rider.util.reactive.Signal import org.codehaus.jettison.json.JSONObject class ProjectCustomDataHost(project: Project) : LifetimedProjectComponent(project) { val logger = Logger.getInstance(ProjectCustomDataHost::class.java) val isConnected = Property<Boolean>(false) val logSignal = Signal<RdLogEvent>() val play = Property<Boolean>(false) val pause = Property<Boolean>(false) init { project.solution.customData.data.advise(componentLifetime) { item -> if (item.key == "UNITY_ActivateRider" && item.newValueOpt == "true") { logger.info(item.key+" "+ item.newValueOpt) ProjectUtil.focusProjectWindow(project, true) project.solution.customData.data["UNITY_ActivateRider"] = "false"; } } project.solution.customData.data.advise(componentLifetime) { item -> if (item.key == "UNITY_Play" && item.newValueOpt!=null) { play.set(item.newValueOpt!!.toBoolean()) } } project.solution.customData.data.advise(componentLifetime) { item -> if (item.key == "UNITY_Pause" && item.newValueOpt!=null) { pause.set(item.newValueOpt!!.toBoolean()) } } project.solution.customData.data.advise(componentLifetime) { item -> if (item.key == "UNITY_SessionInitialized" && item.newValueOpt!=null) { isConnected.set(item.newValueOpt!!.toBoolean()) } } project.solution.customData.data.advise(componentLifetime) { item -> if (item.key == "UNITY_LogEntry" && item.newValueOpt!=null) { logger.info(item.key+" "+ item.newValueOpt) val jsonObj = JSONObject(item.newValueOpt) val type = RdLogEventType.values().get(jsonObj.getInt("Type")) val mode = RdLogEventMode.values().get(jsonObj.getInt("Mode")) logSignal.fire(RdLogEvent(type, mode, jsonObj.getString("Message"), jsonObj.getString("StackTrace"))) } } } companion object { fun CallBackendRefresh(project: Project) { CallBackend(project, "UNITY_Refresh", "true") } fun CallBackendPlay(project: Project, value:Boolean) { CallBackend(project, "UNITY_Play", value.toString().toLowerCase()) } fun CallBackendPause(project: Project, value:Boolean) { CallBackend(project, "UNITY_Pause", value.toString().toLowerCase()) } fun CallBackendStep(project: Project) { CallBackend(project, "UNITY_Step", "true") } private fun CallBackend(project: Project, key : String, value:String) { project.solution.customData.data.remove(key) project.solution.customData.data[key] = value } } }
0
C#
0
0
de1288720d56740a8ff13eb3489488beb9c53517
3,154
resharper-unity
Apache License 2.0
data/RF03455/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF03455" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 11 to 14 62 to 65 } value = "#62f2b1" } color { location { 16 to 18 59 to 61 } value = "#7f59ae" } color { location { 20 to 21 56 to 57 } value = "#b50887" } color { location { 23 to 28 48 to 53 } value = "#2ecae4" } color { location { 31 to 35 41 to 45 } value = "#50ba10" } color { location { 15 to 15 62 to 61 } value = "#84c70a" } color { location { 19 to 19 58 to 58 } value = "#2c1647" } color { location { 22 to 22 54 to 55 } value = "#983dbd" } color { location { 29 to 30 46 to 47 } value = "#982f39" } color { location { 36 to 40 } value = "#0acace" } color { location { 1 to 10 } value = "#522b90" } color { location { 66 to 75 } value = "#06ecc9" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
1,943
Rfam-for-RNArtist
MIT License
app/src/main/java/com/hamzaazman/finalspace/data/repo/CharacterRepository.kt
hamzaazman
572,226,620
false
{"Kotlin": 62216}
package com.hamzaazman.finalspace.data.repo import com.hamzaazman.finalspace.data.database.CharacterDao import com.hamzaazman.finalspace.data.network.ConnectivityObserver import com.hamzaazman.finalspace.data.network.SpaceApi import com.hamzaazman.finalspace.util.fromCharacterToModel import com.hamzaazman.finalspace.util.networkBoundResource import javax.inject.Inject class CharacterRepository @Inject constructor( private val characterDao: CharacterDao, private val api: SpaceApi, private val networkObserverRepository: ConnectivityObserver, ) { fun getCharacters() = networkBoundResource( query = { characterDao.getAll() }, fetch = { api.getAllCharacters() }, saveFetchResult = { characterDao.deleteAll() val list = it.let { listCharacter -> listCharacter.map { character -> fromCharacterToModel(character) } } characterDao.insertAll(list) }, shouldFetch = { characters -> characters.isEmpty() }, networkObserverRepository ) }
0
Kotlin
1
6
d1a346f494078c61333f249274559721134cf2cd
1,225
FinalSpace
Apache License 2.0
app/src/main/kotlin/net/yuzumone/bergamio/di/AppModule.kt
yuzumone
81,647,607
false
null
package net.yuzumone.bergamio.di import android.app.Application import android.content.Context import dagger.Module import dagger.Provides import io.reactivex.disposables.CompositeDisposable import okhttp3.Cache import okhttp3.OkHttpClient import java.io.File import javax.inject.Singleton @Module class AppModule(private val application: Application) { companion object { val CACHE_FILE_NAME = "okhttp.cache" val MAX_CACHE_SIZE = (4 * 1024 * 1024).toLong() } @Provides fun provideApplicationContext(): Context { return application } @Singleton @Provides fun provideHttpClient(context: Context): OkHttpClient { val cacheDir = File(context.cacheDir, CACHE_FILE_NAME) val cache = Cache(cacheDir, MAX_CACHE_SIZE) val client = OkHttpClient.Builder() .cache(cache) return client.build() } @Provides fun provideCompositeDisposable(): CompositeDisposable { return CompositeDisposable() } }
0
Kotlin
0
0
a2335b62dfdc5e182616e9a13c722c138708cfda
1,016
bergamio
Apache License 2.0
templates/src/main/java/com/cyrillrx/templates/model/Header.kt
cyrillrx
23,188,810
false
null
package com.cyrillrx.templates.model /** * @author Cyril Leroux * Created on 01/03/2019. */ class Header(val title: String?)
1
null
1
1
06b5e82cded7fc550a7710b33350a0ef15fab246
136
android-libraries
MIT License
buildscripts/booster/src/main/kotlin/Booster.kt
johnsonlee
497,290,583
false
{"Kotlin": 55139, "Mustache": 157}
fun booster(module: String) = "com.didiglobal.booster:${module}:4.10.0" fun codegen(module: String) = "io.johnsonlee.codegen:${module}:1.1.0"
0
Kotlin
1
12
47a4e69a4a06db32db5dca788d277fe450c46101
141
initializr
Apache License 2.0
src/main/kotlin/io/gladed/watchable/Period.kt
gladed
171,806,576
false
null
/* * (c) Copyright 2019 Glade Diviney. * * 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 io.gladed.watchable /** * Defines special values for watcher timing. * * When period is >0, changes are collected and delivered no more frequently than that many milliseconds. */ object Period { /** * A watcher with this period run very soon after the change is made. This is the default for all * watching operations. */ const val IMMEDIATE = 0L /** * A watcher that runs before the change is fully applied. If it throws the change will be rolled * back and the exception re-thrown at the site of the change. */ const val INLINE = -1L }
4
Kotlin
2
3
0c06cee9600c550a6b3d4bbaa4e1f00f61f18958
1,202
watchable
Apache License 2.0
app/src/main/java/com/linecy/dilidili/ui/cartoon/CartoonWeekFragment.kt
linecyc
138,257,601
false
null
package com.linecy.dilidili.ui.cartoon import android.databinding.ViewDataBinding import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.view.View import android.view.View.OnClickListener import com.linecy.dilidili.R import com.linecy.dilidili.data.model.Cartoon import com.linecy.dilidili.data.presenter.cartoonWeek.CartoonWeekPresenter import com.linecy.dilidili.data.presenter.cartoonWeek.CartoonWeekView import com.linecy.dilidili.ui.BaseFragment import com.linecy.dilidili.ui.cartoon.adapter.CartoonWeekAdapter import com.linecy.dilidili.ui.misc.ViewContainer.OnReloadCallBack import kotlinx.android.synthetic.main.fragment_cartoon_week.recyclerView import kotlinx.android.synthetic.main.fragment_cartoon_week.viewContainer import kotlinx.android.synthetic.main.fragment_cartoon_week.weekday1 import kotlinx.android.synthetic.main.fragment_cartoon_week.weekday2 import kotlinx.android.synthetic.main.fragment_cartoon_week.weekday3 import kotlinx.android.synthetic.main.fragment_cartoon_week.weekday4 import kotlinx.android.synthetic.main.fragment_cartoon_week.weekday5 import kotlinx.android.synthetic.main.fragment_cartoon_week.weekday6 import kotlinx.android.synthetic.main.fragment_cartoon_week.weekday7 import java.util.Calendar import java.util.Locale import javax.inject.Inject /** * @author by linecy. */ class CartoonWeekFragment : BaseFragment<ViewDataBinding>(), CartoonWeekView, OnClickListener, OnReloadCallBack { private var current: Int//默认加载"今天" init { val c = Calendar.getInstance(Locale.CHINA) current = formatDay(c.get(Calendar.DAY_OF_WEEK)) } @Inject lateinit var cartoonWeekPresenter: CartoonWeekPresenter private var weekAdapter: CartoonWeekAdapter? = null override fun layoutResId(): Int { return R.layout.fragment_cartoon_week } override fun onInitView(savedInstanceState: Bundle?) { delegatePresenter(cartoonWeekPresenter, this) viewContainer.setOnReloadCallBack(this) val manager = GridLayoutManager(context, 3) recyclerView.layoutManager = manager weekAdapter = CartoonWeekAdapter(context!!) recyclerView.adapter = weekAdapter setListener(weekday1, weekday2, weekday3, weekday4, weekday5, weekday6, weekday7) cartoonWeekPresenter.getWeekCartoon() } private fun setListener(vararg views: View) { for (i in 0 until views.size) { views[i].setOnClickListener(this) views[i].isSelected = i == current } } private fun setSelector(view: View) { if (!view.isSelected) { listOf(weekday7, weekday1, weekday2, weekday3, weekday4, weekday5, weekday6).forEach { it.isSelected = it == view } } } override fun onDestroy() { super.onDestroy() cartoonWeekPresenter.detach() } override fun showLoading() { showLoadingDialog() } override fun hideLoading() { hideLoadingDialog() } override fun onReload() { cartoonWeekPresenter.getWeekCartoon() } override fun onClick(v: View?) { when (v?.id) { R.id.weekday7 -> { weekAdapter?.refreshData(1) setSelector(weekday7) } R.id.weekday1 -> { weekAdapter?.refreshData(2) setSelector(weekday1) } R.id.weekday2 -> { weekAdapter?.refreshData(3) setSelector(weekday2) } R.id.weekday3 -> { weekAdapter?.refreshData(4) setSelector(weekday3) } R.id.weekday4 -> { weekAdapter?.refreshData(5) setSelector(weekday4) } R.id.weekday5 -> { weekAdapter?.refreshData(6) setSelector(weekday5) } R.id.weekday6 -> { weekAdapter?.refreshData(7) setSelector(weekday6) } } } override fun showWeekList(list: ArrayList<ArrayList<Cartoon>>) { viewContainer.setDisplayedChildId(R.id.content) weekAdapter?.refreshData(list, current) } override fun showError() { viewContainer.setDisplayedChildId(R.id.error) } /** * 转换时间 */ private fun formatDay(position: Int): Int { if (position > 7 || position < 0) { throw IllegalArgumentException("The week day must be start 1 to 7,and ") } return when (position) { 1 -> 6 else -> position - 2 } } }
1
null
1
1
b80dde7a69282816701b48e8010930f57b1d82cb
4,299
Dilidili
Apache License 2.0
zoomimage-core-glide/src/main/kotlin/com/github/panpf/zoomimage/glide/internal/glide_other_utils.kt
panpf
647,222,866
false
{"Kotlin": 4053977, "Shell": 1447}
package com.github.panpf.zoomimage.glide.internal import android.graphics.Bitmap /** * Convert the object to a hexadecimal string * * @see com.github.panpf.zoomimage.core.glide.test.internal.GlideOtherUtilsTest.testToHexString */ internal fun Any.toHexString(): String = this.hashCode().toString(16) /** * Get the log string description of Bitmap, it additionally contains the hexadecimal string representation of the Bitmap memory address. * * @see com.github.panpf.zoomimage.core.glide.test.internal.GlideOtherUtilsTest.testToLogString */ internal fun Bitmap.toLogString(): String = "Bitmap@${toHexString()}(${width}x${height},$config)"
1
Kotlin
12
272
c4ba543392b966ef55a77de584d44967821e2f0e
650
zoomimage
Apache License 2.0
googleauth/android/app/src/main/kotlin/com/example/googleauth/MainActivity.kt
CharmiGoswami
409,149,083
false
{"Rich Text Format": 14026518, "Dart": 526054, "HTML": 98365, "Swift": 25174, "Kotlin": 3473, "Ruby": 2684, "Objective-C": 1026}
package com.example.googleauth import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Rich Text Format
2
0
8c50126943ebfe858cb321be727cbc46ea686f3d
127
Flutter
MIT License
wakatimeclient/src/main/java/is/hth/wakatimeclient/core/data/net/Mime.kt
hrafnthor
352,711,485
false
null
package `is`.hth.wakatimeclient.core.data.net internal sealed class Mime(private val value: String) { object ApplicationJson : Mime("application/json") override fun toString(): String = value }
0
Kotlin
0
0
5e919c9bffd1da3357503090ca7ad69dbedb669f
204
wakatime-client
MIT License
core/src/commonMain/kotlin/com/solana/signer/Signer.kt
solana-mobile
719,706,022
false
{"Kotlin": 49831}
package com.solana.signer interface Signer { val publicKey: ByteArray val ownerLength: Number val signatureLength: Number suspend fun signPayload(payload: ByteArray): ByteArray }
2
Kotlin
1
0
cbbe18f72dcafd6a2ed5a90611cc02229a809e3a
195
web3-core
Apache License 2.0
buildSrc/src/main/java/lt/markmerkk/export/icons/IconScriptProvider.kt
marius-m
67,072,115
false
null
package lt.markmerkk.export.icons interface IconScriptProvider { /** * Prints out debug data */ fun debugPrint() /** * Generated command to execute */ fun scriptCommand(): List<String> }
1
Kotlin
1
26
6632d6bfd53de4760dbc3764c361f2dcd5b5ebce
226
wt4
Apache License 2.0
src/test/kotlin/com/github/vhromada/catalog/repository/EpisodeRepositorySpringTest.kt
vhromada
597,308,377
false
null
package com.github.vhromada.catalog.repository import com.github.vhromada.catalog.TestConfiguration import com.github.vhromada.catalog.utils.AuditUtils import com.github.vhromada.catalog.utils.EpisodeUtils import com.github.vhromada.catalog.utils.SeasonUtils import com.github.vhromada.catalog.utils.ShowUtils import com.github.vhromada.catalog.utils.TestConstants import com.github.vhromada.catalog.utils.fillAudit import com.github.vhromada.catalog.utils.updated import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.SoftAssertions.assertSoftly import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.PageRequest import org.springframework.data.domain.Pageable import org.springframework.test.annotation.DirtiesContext import org.springframework.test.annotation.Rollback import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.transaction.annotation.Transactional import javax.persistence.EntityManager import javax.persistence.PersistenceContext /** * A class represents test for class [EpisodeRepository]. * * @author Vladimir Hromada */ @ExtendWith(SpringExtension::class) @ContextConfiguration(classes = [TestConfiguration::class]) @Transactional @Rollback class EpisodeRepositorySpringTest { /** * Instance of [EntityManager] */ @PersistenceContext private lateinit var entityManager: EntityManager /** * Instance of [EpisodeRepository] */ @Autowired private lateinit var repository: EpisodeRepository /** * Test method for get episode. */ @Test fun getEpisode() { for (i in 1..ShowUtils.SHOWS_COUNT) { for (j in 1..SeasonUtils.SEASONS_PER_SHOW_COUNT) { for (k in 1..EpisodeUtils.EPISODES_PER_SEASON_COUNT) { val id = (i - 1) * EpisodeUtils.EPISODES_PER_SHOW_COUNT + (j - 1) * EpisodeUtils.EPISODES_PER_SEASON_COUNT + k val episode = repository.findById(id).orElse(null) EpisodeUtils.assertEpisodeDeepEquals(expected = ShowUtils.getDomainShow(index = i).seasons[j - 1].episodes[k - 1], actual = episode) } } } assertThat(repository.findById(Int.MAX_VALUE)).isNotPresent assertSoftly { it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT) it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT) it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT) } } /** * Test method for add episode. */ @Test @DirtiesContext fun add() { val episode = EpisodeUtils.newDomainEpisode(id = null) .copy(position = EpisodeUtils.EPISODES_COUNT) episode.season = SeasonUtils.getDomainSeason(entityManager = entityManager, id = 1) val expectedEpisode = EpisodeUtils.newDomainEpisode(id = EpisodeUtils.EPISODES_COUNT + 1) .fillAudit(audit = AuditUtils.newAudit()) expectedEpisode.season = SeasonUtils.getDomainSeason(entityManager = entityManager, id = 1) repository.saveAndFlush(episode) assertSoftly { it.assertThat(episode.id).isEqualTo(EpisodeUtils.EPISODES_COUNT + 1) it.assertThat(episode.createdUser).isEqualTo(TestConstants.ACCOUNT.uuid) it.assertThat(episode.createdTime).isEqualTo(TestConstants.TIME) it.assertThat(episode.updatedUser).isEqualTo(TestConstants.ACCOUNT.uuid) it.assertThat(episode.updatedTime).isEqualTo(TestConstants.TIME) } EpisodeUtils.assertEpisodeDeepEquals(expected = expectedEpisode, actual = EpisodeUtils.getDomainEpisode(entityManager = entityManager, id = EpisodeUtils.EPISODES_COUNT + 1)) assertSoftly { it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT + 1) it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT) it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT) } } /** * Test method for update episode. */ @Test fun update() { val episode = EpisodeUtils.getDomainEpisode(entityManager = entityManager, id = 1)!! .updated() val expectedEpisode = ShowUtils.getDomainShow(index = 1).seasons.first().episodes.first() .updated() .fillAudit(audit = AuditUtils.updatedAudit()) repository.saveAndFlush(episode) EpisodeUtils.assertEpisodeDeepEquals(expected = expectedEpisode, actual = EpisodeUtils.getDomainEpisode(entityManager = entityManager, id = 1)) assertSoftly { it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT) it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT) it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT) } } /** * Test method for get episodes by season ID. */ @Test fun findAllBySeasonId() { for (i in 1..ShowUtils.SHOWS_COUNT) { val show = ShowUtils.getDomainShow(index = i) for (season in show.seasons) { val episodes = repository.findAllBySeasonId(id = season.id!!, pageable = Pageable.ofSize(EpisodeUtils.EPISODES_PER_SEASON_COUNT)) assertSoftly { it.assertThat(episodes.number).isEqualTo(0) it.assertThat(episodes.totalPages).isEqualTo(1) it.assertThat(episodes.totalElements).isEqualTo(EpisodeUtils.EPISODES_PER_SEASON_COUNT.toLong()) } EpisodeUtils.assertDomainEpisodesDeepEquals(expected = season.episodes, actual = episodes.content) } } assertSoftly { it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT) it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT) it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT) } } /** * Test method for get episodes by season ID with invalid paging. */ @Test fun findAllBySeasonIdInvalidPaging() { for (i in 1..ShowUtils.SHOWS_COUNT) { val show = ShowUtils.getDomainShow(index = i) for (season in show.seasons) { val episodes = repository.findAllBySeasonId(id = season.id!!, pageable = PageRequest.of(2, EpisodeUtils.EPISODES_PER_SEASON_COUNT)) assertSoftly { it.assertThat(episodes.content).isEmpty() it.assertThat(episodes.number).isEqualTo(2) it.assertThat(episodes.totalPages).isEqualTo(1) it.assertThat(episodes.totalElements).isEqualTo(EpisodeUtils.EPISODES_PER_SEASON_COUNT.toLong()) } } } assertSoftly { it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT) it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT) it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT) } } /** * Test method for get episodes by season ID with not existing season ID. */ @Test fun findAllBySeasonIdNotExistingSeasonId() { val episodes = repository.findAllBySeasonId(id = Int.MAX_VALUE, pageable = Pageable.ofSize(EpisodeUtils.EPISODES_PER_SEASON_COUNT)) assertSoftly { it.assertThat(episodes.content).isEmpty() it.assertThat(episodes.number).isEqualTo(0) it.assertThat(episodes.totalPages).isEqualTo(0) it.assertThat(episodes.totalElements).isEqualTo(0L) } assertSoftly { it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT) it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT) it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT) } } /** * Test method for find episode by UUID. */ @Test fun findByUuid() { for (i in 1..ShowUtils.SHOWS_COUNT) { val show = ShowUtils.getDomainShow(index = i) for (season in show.seasons) { for (episode in season.episodes) { val result = repository.findByUuid(uuid = episode.uuid).orElse(null) EpisodeUtils.assertEpisodeDeepEquals(expected = episode, actual = result) } } } assertThat(repository.findByUuid(uuid = TestConstants.UUID)).isNotPresent assertSoftly { it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT) it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT) it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT) } } /** * Test method for get statistics. */ @Test fun getStatistics() { val result = repository.getStatistics() EpisodeUtils.assertStatisticsDeepEquals(expected = EpisodeUtils.getStatistics(), actual = result) assertSoftly { it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT) it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT) it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT) } } }
0
Kotlin
0
0
e9358777ae3f6d94ed564f68e59126bbd639b325
10,568
Catalog
MIT License
app/src/main/kotlin/de/mario/camera/io/StorageAccess.kt
mario-s
94,930,304
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Kotlin": 85, "XML": 9, "Java": 1}
package de.mario.camera.io import android.os.Environment import java.io.File internal object StorageAccess: StorageAccessable { override fun getStorageState(): String { return Environment.getExternalStorageState() } override fun getStorageDirectory(): File { return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) } }
0
Kotlin
0
0
997af6bb839172f39083058ec78bb76205d02ed7
379
multishot-cam2
Apache License 2.0
socket/src/jvmMain/kotlin/mqtt/socket/nio/util/NetworkChannelExtensions.kt
thebehera
171,056,445
false
null
@file:Suppress("EXPERIMENTAL_API_USAGE") package mqtt.socket.nio.util import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import mqtt.socket.SocketOptions import java.net.SocketOption import java.net.StandardSocketOptions import java.nio.channels.AsynchronousSocketChannel import java.nio.channels.NetworkChannel import java.nio.channels.SocketChannel import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlin.time.ExperimentalTime suspend fun NetworkChannel.asyncSetOptions(options: SocketOptions?): SocketOptions { return withContext(Dispatchers.IO) { if (options != null) { if (options.tcpNoDelay != null && supportedOptions().contains(StandardSocketOptions.TCP_NODELAY)) { setOption(StandardSocketOptions.TCP_NODELAY, options.tcpNoDelay) } if (options.reuseAddress != null && supportedOptions().contains(StandardSocketOptions.SO_REUSEADDR)) { setOption(StandardSocketOptions.SO_REUSEADDR, options.reuseAddress) } if (options.keepAlive != null && supportedOptions().contains(StandardSocketOptions.SO_KEEPALIVE)) { setOption(StandardSocketOptions.SO_KEEPALIVE, options.keepAlive) } if (options.receiveBuffer != null && supportedOptions().contains(StandardSocketOptions.SO_RCVBUF)) { setOption(StandardSocketOptions.SO_RCVBUF, options.receiveBuffer.toInt()) } if (options.sendBuffer != null && supportedOptions().contains(StandardSocketOptions.SO_SNDBUF)) { setOption(StandardSocketOptions.SO_SNDBUF, options.sendBuffer.toInt()) } } SocketOptions( tryGettingOption(StandardSocketOptions.TCP_NODELAY), tryGettingOption(StandardSocketOptions.SO_REUSEADDR), tryGettingOption(StandardSocketOptions.SO_KEEPALIVE), tryGettingOption(StandardSocketOptions.SO_RCVBUF)?.toUInt(), tryGettingOption(StandardSocketOptions.SO_SNDBUF)?.toUInt() ) } } fun <T> NetworkChannel.tryGettingOption(option: SocketOption<T>) = if (supportedOptions().contains(option)) { getOption(option) } else { null } @ExperimentalTime suspend fun NetworkChannel.aClose() { suspendCoroutine<Unit> { cont -> blockingClose() cont.resume(Unit) } } @ExperimentalTime internal fun NetworkChannel.blockingClose() { try { if (this is SocketChannel) { shutdownInput() } else if (this is AsynchronousSocketChannel) { shutdownInput() } } catch (ex: Throwable) { } try { if (this is SocketChannel) { shutdownOutput() } else if (this is AsynchronousSocketChannel) { shutdownOutput() } } catch (ex: Throwable) { } try { close() } catch (ex: Throwable) { // Specification says that it is Ok to call it any time, but reality is different, // so we have just to ignore exception } }
2
Kotlin
1
32
2f2d176ca1d042f928fba3a9c49f4bc5ff39495f
3,078
mqtt
Apache License 2.0
app/src/main/java/me/shetj/mp3recorder/record/activity/mix/MyMixRecordPage.kt
SheTieJun
207,213,419
false
null
/* * MIT License * * Copyright (c) 2019 SheTieJun * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.shetj.mp3recorder.record.activity.mix import android.app.Activity import android.transition.Scene import android.transition.TransitionManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import android.widget.RelativeLayout import androidx.recyclerview.widget.RecyclerView import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.schedulers.Schedulers import me.shetj.base.tools.app.ArmsUtils import me.shetj.mp3recorder.R import me.shetj.mp3recorder.record.adapter.RecordAdapter import me.shetj.mp3recorder.record.bean.Record import me.shetj.mp3recorder.record.bean.RecordDbUtils import me.shetj.mp3recorder.record.utils.EventCallback import me.shetj.mp3recorder.record.view.RecordBottomSheetDialog import java.util.* /** */ class MyMixRecordPage( private val context: Activity, mRoot: ViewGroup, private var callback: EventCallback ) { private var root: RelativeLayout? = null val scene: Scene private var mRecyclerView: RecyclerView? = null private var mIvRecordState: ImageView? = null private lateinit var recordAdapter: RecordAdapter private var mRlRecordView: FrameLayout? = null /** * 得到当前选中的record */ val curRecord: Record? get() = if (recordAdapter.curPosition != -1) { recordAdapter.getItem(recordAdapter.curPosition) } else null init { root = LayoutInflater.from(context).inflate(R.layout.page_my_record, null) as RelativeLayout scene = Scene(mRoot, root as View) initView(root) initData() } private fun initData() { RecordDbUtils.getInstance().allRecord .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext { recordAdapter.setNewInstance(it.toMutableList()) checkShow(it) } .subscribe() } /** * 判断是不是存在录音 */ private fun checkShow(allRecord: List<Record>) { root?.let { TransitionManager.beginDelayedTransition(root) } if (allRecord.isNotEmpty()) { mRlRecordView!!.visibility = View.VISIBLE } else { mRlRecordView!!.visibility = View.GONE } } private fun initView(view: View?) { //绑定view mRecyclerView = view!!.findViewById(R.id.recycler_view) mIvRecordState = view.findViewById(R.id.iv_record_state) mRlRecordView = view.findViewById(R.id.rl_record_view) //设置界面 recordAdapter = RecordAdapter(ArrayList()) mRecyclerView?.adapter = recordAdapter //设置点击 recordAdapter.setOnItemClickListener { _, _, position -> recordAdapter.setPlayPosition( position ) } recordAdapter.setOnItemChildClickListener { adapter, view1, position -> when (view1.id) { R.id.tv_more -> { val dialog = showBottomDialog(position, adapter) dialog?.showBottomSheet() } } } recordAdapter.addChildClickViewIds(R.id.tv_more) recordAdapter.setOnItemLongClickListener { adapter, _, position -> val dialog = showBottomDialog(position, adapter) dialog?.showBottomSheet() true } //设置空界面 val emptyView = LayoutInflater.from(context).inflate(R.layout.empty_view, null) recordAdapter.setEmptyView(emptyView) //空界面点击开启 emptyView.findViewById<View>(R.id.cd_start_record).setOnClickListener { callback.onEvent(0) } //添加一个head val headView = View(context) headView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ArmsUtils.dp2px(35f)) recordAdapter.addHeaderView(headView) //去录音界面 mIvRecordState!!.setOnClickListener { recordAdapter.setPlayPosition(-1) callback.onEvent(0) } } private fun showBottomDialog( position: Int, adapter: BaseQuickAdapter<*, BaseViewHolder> ): RecordBottomSheetDialog? { recordAdapter.onPause() return recordAdapter.getItem(position).let { (mRecyclerView!!.findViewHolderForAdapterPosition(position + adapter.headerLayoutCount) as BaseViewHolder).let { it1 -> RecordBottomSheetDialog( context, position, it, callback ) } } } fun onDestroy() { recordAdapter.onDestroy() root = null } fun onPause() { recordAdapter.onPause() } }
0
Kotlin
2
12
395e6246a0387e4a87956fae79a61b8211650e42
6,070
Mp3Recorder
MIT License
src/main/kotlin/no/nav/syfo/application/ApplicationServer.kt
navikt
398,212,361
false
null
package no.nav.syfo.application import io.ktor.server.engine.ApplicationEngine import java.util.concurrent.TimeUnit class ApplicationServer(private val applicationServer: ApplicationEngine, private val applicationState: ApplicationState) { init { Runtime.getRuntime().addShutdownHook( Thread { applicationState.ready = false applicationState.alive = false this.applicationServer.stop(TimeUnit.SECONDS.toMillis(30), TimeUnit.SECONDS.toMillis(30)) } ) } fun start() { applicationServer.start(true) } }
1
Kotlin
0
0
d61ddaf180b74767ed84727fc05eb4aacd0eb957
615
narmesteleder-arbeidsforhold
MIT License
src/commonMain/kotlin/jdenticon/HashUtils.kt
WycliffeAssociates
125,108,884
false
null
package jdenticon // Mirrors the functionality at: // https://github.com/dmester/jdenticon/blob/54fb9c1d1d66d5eb6849583cca219ae6ab986ee5/src/common/hashUtils.js class HashUtils { companion object { // hash argument must be only hexadecimal characters, and minimum length of 11 characters private val MINIMUM_HEX_STRING_REGEX = "^[0-9a-fA-F]{11,}$".toRegex() /** * Inputs a value that might be a valid hash string for Jdenticon and returns it * if it is determined valid, otherwise a false value is returned. */ fun isValidHash(hashCandidate: String): Boolean { return MINIMUM_HEX_STRING_REGEX.matches(hashCandidate) } fun keepOrCreateHash(hashOrValue: String): String { return when (isValidHash(hashOrValue)) { true -> hashOrValue false -> computeHash(hashOrValue) } } } } expect fun computeHash(value: String): String
3
Kotlin
8
17
c18f04d0727c7e018d1cddd4f189b2da4348202c
986
jdenticon-kotlin
MIT License
ui/script/src/main/kotlin/me/gegenbauer/catspy/script/ui/ScriptTabPanel.kt
Gegenbauer
609,809,576
false
{"Kotlin": 1056932}
package me.gegenbauer.catspy.script.ui import com.malinskiy.adam.request.device.Device import com.malinskiy.adam.request.device.DeviceState import me.gegenbauer.catspy.context.Context import me.gegenbauer.catspy.context.ServiceManager import me.gegenbauer.catspy.ddmlib.device.AdamDeviceMonitor import me.gegenbauer.catspy.java.ext.Bundle import me.gegenbauer.catspy.java.ext.EMPTY_STRING import me.gegenbauer.catspy.script.model.Script import me.gegenbauer.catspy.script.model.ScriptType import me.gegenbauer.catspy.script.parser.DirectRule import me.gegenbauer.catspy.script.parser.RegexRule import me.gegenbauer.catspy.script.task.ScriptTaskManager import me.gegenbauer.catspy.view.tab.BaseTabPanel import java.awt.BorderLayout import javax.swing.JComponent class ScriptTabPanel : BaseTabPanel() { override val tag: String = "ScriptTabPanel" private val taskManager = ServiceManager.getContextService(ScriptTaskManager::class.java) private val cardContainer = ScriptCardContainer() private val focusedActivityParseRule = RegexRule("mCurrentFocus=Window\\{[0-9a-z]+ [0-9a-z]+ (.*)\\}", DirectRule()) private val getFocusedActivityScript = Script( "GetFocusedActivity", ScriptType.adb, "dumpsys activity activities" ) private val buildTimeScript = Script( "BuildTime", ScriptType.adb, "getprop ro.build.inside.id" ) private val windowSize = Script( "WindowSize", ScriptType.adb, "wm size" ) private val windowDensity = Script( "WindowDensity", ScriptType.adb, "wm density" ) private val windowOrientation = Script( "WindowOrientation", ScriptType.adb, "dumpsys input | grep 'SurfaceOrientation'" ) private val windowState = Script( "WindowState", ScriptType.adb, "dumpsys window | grep 'mCurrentFocus'" ) private val windowResolution = Script( "WindowResolution", ScriptType.adb, "dumpsys window | grep 'DisplayWidth'" ) private val focusedActivityCard = ScriptCard(taskManager, ScriptUIItem(getFocusedActivityScript, focusedActivityParseRule)) private val deviceInfoCard = DeviceInfoCard( listOf( ScriptUIItem(getFocusedActivityScript, focusedActivityParseRule), ScriptUIItem(windowSize), ScriptUIItem(buildTimeScript), ScriptUIItem(windowDensity), ScriptUIItem(windowOrientation), ScriptUIItem(windowState), ScriptUIItem(windowResolution) ), taskManager ) var currentDevice: Device = defaultDevice set(value) { field = value focusedActivityCard.device = value } override fun onSetup(bundle: Bundle?) { val deviceManager = ServiceManager.getContextService(AdamDeviceMonitor::class.java) deviceManager.tryStartMonitor() layout = BorderLayout() add(cardContainer.container, BorderLayout.NORTH) cardContainer.addCard(focusedActivityCard) cardContainer.addCard(deviceInfoCard) cardContainer.setAutomaticallyUpdate(true) } override fun configureContext(context: Context) { super.configureContext(context) focusedActivityCard.setParent(this) currentDevice = ServiceManager.getContextService(AdamDeviceMonitor::class.java) .getDevices().firstOrNull() ?: currentDevice } override fun onTabSelected() { taskManager.updatePauseState(false) } override fun onTabUnselected() { taskManager.updatePauseState(true) } override fun destroy() { super.destroy() taskManager.cancelAll() val deviceManager = ServiceManager.getContextService(AdamDeviceMonitor::class.java) deviceManager.tryStopMonitor() } override fun getTabContent(): JComponent { return this } private fun updateCardContent() { focusedActivityCard.updateContent() } companion object { val defaultDevice = Device(EMPTY_STRING, DeviceState.DEVICE) } }
3
Kotlin
4
23
a868d118c42a9ab0984bfd51ea845d3dcfd16449
4,148
CatSpy
Apache License 2.0
app/wear/src/main/java/com/victorrubia/tfg/data/model/gps_measure/GPSMeasure.kt
VictorRubia
597,809,981
false
null
package com.victorrubia.tfg.data.model.gps_measure import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import com.victorrubia.tfg.data.converters.Converters import com.victorrubia.tfg.data.model.ppg_measure.DateSerializer import kotlinx.serialization.* import java.util.* /** * Class that represents a PPG measure * * @property id The id of the measure * @property timestamp The timestamp of the measure * @property value The value of the measure */ @Entity(tableName = "gps_measures") @Serializable data class GPSMeasure( @PrimaryKey(autoGenerate = true) val id : Int = 0, val latitude: Double, val longitude: Double, @TypeConverters(Converters::class) @Serializable(with = DateSerializer::class) val date: Date, )
1
Kotlin
0
0
4d4d6de63c4ce5c9522d19ba0c80891cbe768507
795
TFM
Creative Commons Zero v1.0 Universal
graphglue/src/main/kotlin/io/github/graphglue/GraphiQLRouteConfiguration.kt
graphglue
436,856,727
false
{"Kotlin": 344000, "MDX": 27617, "CSS": 3406, "JavaScript": 3225, "HTML": 3030}
/* * Copyright 2021 Expedia, 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 * * 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. * This is a modified version */ package io.github.graphglue import com.expediagroup.graphql.server.spring.GraphQLConfigurationProperties import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.io.Resource import org.springframework.web.reactive.function.server.bodyValueAndAwait import org.springframework.web.reactive.function.server.coRouter import org.springframework.web.reactive.function.server.html /** * Configuration for exposing the GraphiQL on a specific HTTP path * * @param config GraphQL Kotlin config to obtain endpoints * @param graphglueConfig used to configure the endpoint of the GraphiQL instance * @param graphiQLHtml the HTML template to serve * @param contextPath base path to build endpoint URLs */ @ConditionalOnProperty(value = ["graphglue.graphiql.enabled"], havingValue = "true", matchIfMissing = true) @Configuration class GraphiQLRouteConfiguration( private val config: GraphQLConfigurationProperties, private val graphglueConfig: GraphglueConfigurationProperties, @Value("classpath:/graphiql.html") private val graphiQLHtml: Resource, @Value("\${spring.webflux.base-path:#{null}}") private val contextPath: String? ) { private val body = graphiQLHtml.inputStream.bufferedReader().use { reader -> val graphQLEndpoint = if (contextPath.isNullOrBlank()) config.endpoint else "$contextPath/${config.endpoint}" val subscriptionsEndpoint = if (contextPath.isNullOrBlank()) config.subscriptions.endpoint else "$contextPath/${config.subscriptions.endpoint}" reader.readText().replace("\${graphQLEndpoint}", graphQLEndpoint) .replace("\${subscriptionsEndpoint}", subscriptionsEndpoint) } /** * Route for the GraphIQL instance * @return the generated router serving the GraphiQL instance */ @Bean fun graphiQLRoute() = coRouter { GET(graphglueConfig.graphiql.endpoint) { ok().html().bodyValueAndAwait(body) } } }
0
Kotlin
2
2
19bdbcab27145e53f8de6f7b73f78f0e14eae101
2,802
graph-glue
Apache License 2.0
library/src/main/java/com/mirrorcf/materialedittext/validation/RegexpValidator.kt
MIRRORCF
360,745,805
false
{"Gradle": 4, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 14, "Kotlin": 11, "Java": 1, "Java Properties": 1}
package com.mirrorcf.materialedittext.validation import java.util.regex.Pattern /** * Custom validator for Regexes */ class RegexpValidator : METValidator { private var pattern: Pattern constructor(errorMessage: String, regex: String) : super(errorMessage) { pattern = Pattern.compile(regex) } constructor(errorMessage: String, pattern: Pattern) : super(errorMessage) { this.pattern = pattern } override fun isValid(text: CharSequence, isEmpty: Boolean): Boolean { return pattern.matcher(text).matches() } }
1
null
1
1
f9bfc89f6abb16adf5a4219902b6adb98606ce3b
566
MaterialEditText
Apache License 2.0
TomaRamosUandes/app/src/main/java/com/ifgarces/tomaramosuandes/adapters/SchedulePortraitAdapter.kt
ifgarces
281,504,652
false
null
package com.ifgarces.tomaramosuandes.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.ifgarces.tomaramosuandes.R import com.ifgarces.tomaramosuandes.activities.HomeActivity import com.ifgarces.tomaramosuandes.models.RamoEvent import com.ifgarces.tomaramosuandes.models.RamoEventType import com.ifgarces.tomaramosuandes.utils.DataMaster import com.ifgarces.tomaramosuandes.utils.SpanishToStringOf import com.ifgarces.tomaramosuandes.utils.infoDialog import java.util.concurrent.Executors /** * Adapter used to display events in the portrait schedule view. */ class SchedulePortraitAdapter(private var data :List<RamoEvent>) : RecyclerView.Adapter<SchedulePortraitAdapter.EventCardVH>() { override fun onCreateViewHolder(parent :ViewGroup, viewType :Int) :EventCardVH { return EventCardVH( LayoutInflater.from(parent.context).inflate( if (DataMaster.getUserStats().nightModeOn) R.layout.night_schedule_portrait_block else R.layout.schedule_portrait_block, parent, false ) ) } override fun getItemCount() = this.data.count() override fun onBindViewHolder(holder :EventCardVH, position :Int) = holder.bind(this.data[position], position) inner class EventCardVH(v :View) : RecyclerView.ViewHolder(v) { private val parentView :View = v private val ramoName :TextView = v.findViewById(R.id.schedulePblock_ramo) private val startTime :TextView = v.findViewById(R.id.schedulePblock_ti) private val endTime :TextView = v.findViewById(R.id.schedulePblock_tf) private val type :TextView = v.findViewById(R.id.schedulePblock_type) private val location :TextView = v.findViewById(R.id.schedulePblock_location) fun bind(event :RamoEvent, position :Int) { (this.parentView.context as HomeActivity).let { homeActivity :HomeActivity -> this.ramoName.text = DataMaster.findRamo( NRC = event.ramoNRC, searchInUserList = true )!!.nombre this.startTime.text = event.startTime.toString() this.endTime.text = event.endTime.toString() this.type.text = SpanishToStringOf.ramoEventType( eventType = event.type, shorten = true ) this.location.text = event.location val isNightModeOn :Boolean = (DataMaster.getUserStats().nightModeOn) // Colorizing event box according to theme and event type if (isNightModeOn) this.type.setTextColor( ContextCompat.getColor(homeActivity, R.color.nightDefaultForeground) ) this.type.setBackgroundColor( when (event.type) { RamoEventType.CLAS -> homeActivity.getColor( if (isNightModeOn) R.color.night_blockColor_clas else R.color.blockColor_clas ) RamoEventType.AYUD -> homeActivity.getColor( if (isNightModeOn) R.color.night_blockColor_ayud else R.color.blockColor_ayud ) RamoEventType.LABT, RamoEventType.TUTR -> homeActivity.getColor( if (isNightModeOn) R.color.night_blockColor_labt else R.color.blockColor_labt ) else -> throw Exception("Invalid/unexpected event type for %s".format(event)) // exception if invalid event or evaluation event, which should not go here (schedule) } ) // Colorizing hole card if the event is on conflict status, asyncronously, so UI // elements itself will load soon, as checking for conflicts may be a heavy task Executors.newSingleThreadExecutor().execute { if (DataMaster.getConflictsOf(event).count() > 0) { homeActivity.runOnUiThread { this.parentView.setBackgroundColor(homeActivity.getColor( if (isNightModeOn) R.color.night_conflict_background else R.color.conflict_background )) } } } // Displaying event details in simple dialog this.parentView.setOnClickListener { homeActivity.infoDialog( title = "Detalle de evento", message = event.toLargeString() ) } } } } }
6
Kotlin
0
0
8469adf3344084c4573c6ce9e820b53b4c72a387
4,988
TomaRamosUandes_android
MIT License
src/main/kotlin/ru/sadv1r/idea/plugin/ansible/vault/editor/Vault.kt
sadv1r
262,578,911
false
null
package ru.sadv1r.idea.plugin.ansible.vault.editor import com.intellij.openapi.fileTypes.FileType import ru.sadv1r.ansible.vault.VaultHandler import ru.sadv1r.ansible.vault.crypto.VaultInfo import ru.sadv1r.idea.plugin.ansible.vault.editor.ui.VaultEditorDialog import ru.sadv1r.idea.plugin.ansible.vault.editor.ui.VaultPasswordDialog import java.io.BufferedReader import java.io.File import java.io.IOException import java.io.InputStreamReader import java.util.concurrent.TimeUnit abstract class Vault { abstract fun setEncryptedData(data: String) abstract fun isEmpty(): Boolean abstract fun getDecryptedData(password: String): ByteArray abstract fun getKey(): String abstract fun getFileType(): FileType fun setEncryptedData(data: ByteArray, password: CharArray) { val vaultId = getVaultId() val encrypt = if (vaultId == null) { VaultHandler.encrypt(data, String(password)) } else { VaultHandler.encrypt(data, String(password), vaultId) } setEncryptedData(encrypt.toString(Charsets.UTF_8)) } private fun getVaultId(): String? { val valueText = getText() if (!valueText.startsWith(VaultInfo.MAGIC_PART_DATA)) { return null } val firstLineBreakIndex: Int = valueText.indexOf(VaultHandler.LINE_BREAK) if (firstLineBreakIndex == -1) { return null } val infoLinePart: String = valueText.substring(0, firstLineBreakIndex) val vaultInfo = VaultInfo(infoLinePart) return vaultInfo.vaultId } abstract fun getText(): String fun openEditor() { val password = getPassword(this) if (password != null) { try { tryOpen(password) } catch (e: IOException) { removePassword(this) tryWithDefaultOrAsk() } } else { tryWithDefaultOrAsk() } } private fun tryWithDefaultOrAsk() { val defaultPasswordFile = System.getenv("ANSIBLE_VAULT_PASSWORD_FILE") if (defaultPasswordFile != null) { val defaultPasswordFileWithoutTilda = expandTilda(defaultPasswordFile) try { val file = File(defaultPasswordFileWithoutTilda) val defaultPassword = if (file.canExecute()) { val vaultId = getVaultId() val process = if (vaultId == null) { Runtime.getRuntime().exec(file.absolutePath) } else { Runtime.getRuntime().exec(arrayOf(file.absolutePath, "--vault-id", vaultId)) } process.waitFor(10, TimeUnit.SECONDS) val reader = BufferedReader(InputStreamReader(process.inputStream, Charsets.UTF_8)) reader.readText() } else { file.readText(Charsets.UTF_8) } tryOpen(defaultPassword.trim()) } catch (e: Exception) { VaultPasswordDialog(this).showAndGet() } } else { VaultPasswordDialog(this).showAndGet() } } private fun expandTilda(path: String): String { if (path.startsWith("~" + File.separator)) { return System.getProperty("user.home") + path.substring(1) } return path } private fun tryOpen(password: String) { VaultEditorDialog( getDecryptedData(password), password.toCharArray(), this ).showAndGet() } }
9
Kotlin
2
28
f5c9e9053e86a61bc0de86a8de5e32849d7a5b27
3,629
ansible-vault-editor-idea-plugin
MIT License
app/src/main/kotlin/com/yizhenwind/keeper/data/database/dao/CharacterDao.kt
WangZhiYao
658,053,133
false
{"Kotlin": 91950}
package com.yizhenwind.keeper.data.database.dao import androidx.paging.PagingSource import androidx.room.Dao import androidx.room.Query import androidx.room.Transaction import com.yizhenwind.keeper.data.database.entity.CharacterEntity import com.yizhenwind.keeper.data.database.relation.CharacterWithAccount import kotlinx.coroutines.flow.Flow /** * * * @author WangZhiYao * @since 2023/6/21 */ @Dao interface CharacterDao : IDao<CharacterEntity> { @Transaction @Query("SELECT * FROM character ORDER BY create_time DESC") fun observeCharacterPagingList(): PagingSource<Int, CharacterWithAccount> @Transaction @Query("SELECT * FROM character WHERE id = :id LIMIT 1") suspend fun getCharacterById(id: Long): List<CharacterWithAccount> @Transaction @Query("SELECT * FROM character INNER JOIN account ON character.account_id = account.id WHERE zone LIKE '%' || :text || '%' OR server LIKE '%' || :text || '%' OR name LIKE '%' || :text || '%' OR sect LIKE '%' || :text || '%' OR internal LIKE '%' || :text || '%' OR remark LIKE '%' || :text || '%' OR account.username LIKE '%' || :text || '%'") fun searchCharacterList(text: String): Flow<List<CharacterWithAccount>> }
5
Kotlin
0
2
e80d12e507d1ffbc2d549d285640ec332114b649
1,209
Keeper
Apache License 2.0
scout/measures/jvm-benchmarks/src/main/kotlin/scout/benchmark/platform/ResultRepository.kt
yandex
698,181,481
false
{"Kotlin": 369096, "Shell": 1596}
/* * Copyright 2023 Yandex 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 scout.benchmark.platform import org.openjdk.jmh.results.RunResult import java.io.File internal fun fetchControlResults(): Map<String, Double> { val file = File(Environment.RESULT_FILE_PATH) if (file.exists()) { val lines = file.readLines() return lines.associate { line -> val (label, score) = line.split(",", ", ") label to score.toDouble() } } return emptyMap() } internal fun saveResults(results: Collection<RunResult>) { val formatted = formatResults(results) File(Environment.RESULT_DIR_PATH).mkdirs() File(Environment.RESULT_FILE_PATH).apply { createNewFile() writeText(formatted) } println() println("Control results was updated!") }
2
Kotlin
4
87
4a49d143be5d92184bf4bfc540f1e192344914d6
1,346
scout
Apache License 2.0
cogboard-app/src/main/kotlin/com/cognifide/cogboard/storage/VolumeStorageFactory.kt
wttech
199,830,591
false
null
package com.cognifide.cogboard.storage import com.cognifide.cogboard.config.ConfigType import com.cognifide.cogboard.config.ConfigType as CT object VolumeStorageFactory { fun admin(configFile: String = CT.ADMIN.configFilePath()) = create(CT.ADMIN, configFile) fun endpoints(configFile: String = CT.ENDPOINTS.configFilePath()) = create(CT.ENDPOINTS, configFile) fun credentials(configFile: String = CT.CREDENTIALS.configFilePath()) = create(CT.CREDENTIALS, configFile) fun boards(configFile: String = CT.BOARDS.configFilePath()) = create(CT.BOARDS, configFile) fun appConfig(configFile: String = CT.APP_CONFIG.configFilePath()) = create(CT.APP_CONFIG, configFile) private fun create(type: ConfigType, configFile: String): VolumeStorage { return VolumeStorage(type, configFile) } }
56
JavaScript
9
15
c20dd382558887def736483bd4c51b02bdcc11c4
820
cogboard
Apache License 2.0
telegraff-core/src/main/kotlin/me/ruslanys/telegraff/core/filter/FilterOrders.kt
Yakaboo
385,503,173
true
{"Kotlin": 77077, "Dockerfile": 122}
package me.ruslanys.telegraff.core.filter class FilterOrders { companion object { const val CALLBACK_QUERY_ANSWER_FILTER_ORDER = -2 const val DEEPLINK_FILTER_ORDER = -1 const val CANCEL_FILTER_ORDER = 0 const val HANDLERS_FILTER_ORDER = 1 const val UNRESOLVED_FILTER_ORDER = Integer.MAX_VALUE } }
0
Kotlin
0
0
ab18112a43acba6128c304c95279bb15a1e30df5
346
telegraff
Apache License 2.0
src/main/java/com/hea3ven/malleable/ModMetals.kt
hea3ven
60,520,915
false
null
package com.hea3ven.malleable import com.hea3ven.tools.bootstrap.Bootstrap import net.minecraft.block.Block import net.minecraft.item.Item import net.minecraft.util.ResourceLocation import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.common.event.FMLInitializationEvent import net.minecraftforge.fml.common.event.FMLMissingMappingsEvent import net.minecraftforge.fml.common.event.FMLPostInitializationEvent import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import net.minecraftforge.fml.common.registry.GameRegistry @Mod(modid = ModMetals.MODID, version = ModMetals.VERSION, dependencies = ModMetals.DEPENDENCIES) class ModMetals { @Mod.EventHandler fun OnPreInit(event: FMLPreInitializationEvent?) { proxy.onPreInitEvent(event) } @Mod.EventHandler fun OnInit(event: FMLInitializationEvent?) { proxy.onInitEvent(event) } @Mod.EventHandler fun OnPostInit(event: FMLPostInitializationEvent?) { proxy.onPostInitEvent(event) } @Mod.EventHandler fun OnMissingMappings(event: FMLMissingMappingsEvent) { event.all.filter { it.resourceLocation.resourceDomain == "metals" }.forEach { if (it.type == GameRegistry.Type.BLOCK) it.remap(Block.REGISTRY.getObject(ResourceLocation(MODID, it.resourceLocation.resourcePath))) else it.remap(Item.REGISTRY.getObject(ResourceLocation(MODID, it.resourceLocation.resourcePath))) } } companion object { const val MODID = "malleable" const val VERSION = "1.9-1.0.0" const val DEPENDENCIES = "required-after:Forge@[12.16.1.1894,)" const val guiIdMetalFurnace = 1; init { Bootstrap.init() } val proxy = ProxyModMetals() } }
0
Kotlin
0
1
524da50a6fcde820afd563b977bc8ef89f9beff3
1,651
Malleable
MIT License
simplified-viewer-preview/src/main/java/org/nypl/simplified/viewer/preview/BookPreviewEmbeddedFragment.kt
ray-lee
367,433,706
true
{"Kotlin": 3336431, "JavaScript": 853494, "Java": 403586, "HTML": 124378, "CSS": 65407, "Shell": 3071, "Ruby": 534}
package org.nypl.simplified.viewer.preview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebChromeClient import android.webkit.WebView import android.webkit.WebViewClient import android.widget.FrameLayout import androidx.appcompat.widget.Toolbar import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import androidx.core.view.isVisible import androidx.fragment.app.Fragment import org.nypl.simplified.webview.WebViewUtilities class BookPreviewEmbeddedFragment : Fragment() { companion object { private const val BUNDLE_EXTRA_URL = "org.nypl.simplified.viewer.preview.BookPreviewEmbeddedFragment.url" fun newInstance(url: String): BookPreviewEmbeddedFragment { return BookPreviewEmbeddedFragment().apply { arguments = Bundle().apply { putString(BUNDLE_EXTRA_URL, url) } } } } private lateinit var toolbar: Toolbar private lateinit var webView: WebView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_book_preview_embedded, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) this.webView = view.findViewById(R.id.web_view) this.toolbar = view.findViewById(R.id.toolbar) configureToolbar() configureWebView() } override fun onDestroyView() { if (::webView.isInitialized) { webView.destroy() } super.onDestroyView() } private fun configureToolbar() { this.toolbar.setNavigationOnClickListener { requireActivity().finish() } this.toolbar.setNavigationContentDescription(R.string.bookPreviewAccessibilityBack) } private fun configureWebView() { webView.apply { webViewClient = WebViewClient() webChromeClient = CustomWebChromeClient() settings.allowFileAccess = true settings.javaScriptEnabled = true settings.domStorageEnabled = true WebViewUtilities.setForcedDark(settings, resources.configuration) loadUrl(requireArguments().getString(BUNDLE_EXTRA_URL).orEmpty()) } } inner class CustomWebChromeClient : WebChromeClient() { private val window = requireActivity().window private val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView) private var fullscreenView: View? = null init { windowInsetsController?.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } override fun onHideCustomView() { fullscreenView?.isVisible = false webView.isVisible = true windowInsetsController?.show(WindowInsetsCompat.Type.systemBars()) } override fun onShowCustomView(view: View?, callback: CustomViewCallback?) { val decorView = requireActivity().window.decorView as? FrameLayout ?: return webView.isVisible = false if (fullscreenView != null) { decorView.removeView(fullscreenView) } fullscreenView = view decorView.addView( fullscreenView, FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT ) ) fullscreenView?.isVisible = true windowInsetsController?.hide(WindowInsetsCompat.Type.systemBars()) } } }
0
Kotlin
0
0
d40ee90d145152c758702df20b4b4f46d22d8d8d
3,592
palace-android-core
Apache License 2.0
app/src/main/java/com/tyganeutronics/myratecalculator/MyApplication.kt
tygalive
250,913,250
false
null
package com.tyganeutronics.myratecalculator import androidx.multidex.MultiDexApplication import com.android.volley.Cache import com.android.volley.Network import com.android.volley.RequestQueue import com.android.volley.toolbox.BasicNetwork import com.android.volley.toolbox.DiskBasedCache import com.android.volley.toolbox.HurlStack import com.google.android.gms.ads.MobileAds import org.jetbrains.annotations.Contract class MyApplication : MultiDexApplication() { override fun onCreate() { super.onCreate() // Instantiate the cache val cache: Cache = DiskBasedCache(cacheDir, 1024 * 1024) // 1MB cap // Set up the network to use HttpURLConnection as the HTTP client. val network: Network = BasicNetwork(HurlStack()) // Instantiate the RequestQueue with the cache and network. requestQueue = RequestQueue(cache, network) // Start the queue requestQueue.start() MobileAds.initialize(this) } companion object { @get:Contract(pure = true) lateinit var requestQueue: RequestQueue } }
0
Kotlin
0
0
c48940cd53536b8a74151eea91ac0928a55ad27b
1,100
ZimRate-Android
Apache License 2.0
app/src/main/java/com/shehuan/wanandroid/bean/article/DatasItem.kt
Youngfellows
451,733,217
false
null
package com.shehuan.wanandroid.bean.article /** * 文章列表数据实体 */ data class DatasItem( val superChapterName: String = "", val publishTime: Long = 0, val visible: Int = 0, val niceDate: String = "", val projectLink: String = "", val author: String = "", val zan: Int = 0, val origin: String = "", val originId: Int = 0, val chapterName: String = "", val link: String = "", val title: String = "", val type: Int = 0, val userId: Int = 0, val tags: List<TagsItem>, val apkLink: String = "", val envelopePic: String = "", val chapterId: Int = 0, val superChapterId: Int = 0, val id: Int = 0, val fresh: Boolean = false, var collect: Boolean = false, val courseId: Int = 0, val desc: String = "" )
1
null
1
1
75dd34feec9d89c7d1f4ece3021fda0507b0caf0
788
WanAndroid-MVVM-Kotlin
Apache License 2.0
Xmusic/src/main/java/com/nct/xmusicstation/data/remote/ApiResponse.kt
ToanMobile
584,599,884
false
null
package com.nct.xmusicstation.data.remote import com.orhanobut.logger.Logger import retrofit2.Response import java.io.IOException import java.util.regex.Pattern /** * Created by Toan.IT on 10/19/17. * Email:<EMAIL> */ /* @SerializedName("3") ACCESS_DENIED, @SerializedName("102") TOKEN_INVALID, @SerializedName("104") TOKEN_EXPIRED, @SerializedName("110") LOGIN_CODE_EXPIRED, @SerializedName("111") LOGIN_CODE_NOT_ASSIGNED, @SerializedName("112") LOGIN_CODE_INVALID, @SerializedName("200") USER_NOT_EXISTS, @SerializedName("204") USER_STOP_WORKING*/ class ApiResponse<T> { val code: Int val body: T? val errorMessage: String? val links: MutableMap<String, String> val isSuccessful: Boolean get() = code in 200..299 val nextPage: Int? get() { val next = links[NEXT_LINK] ?: return null val matcher = PAGE_PATTERN.matcher(next) if (!matcher.find() || matcher.groupCount() != 1) { return null } try { return Integer.parseInt(matcher.group(1)) } catch (ex: NumberFormatException) { Logger.w("cannot parse next page from %s", next) return null } } constructor(error: Throwable) { code = 500 body = null errorMessage = error.message links = mutableMapOf() } constructor(response: Response<T>) { code = response.code() if (response.isSuccessful) { body = response.body() errorMessage = null } else { var message: String? = null if (response.errorBody() != null) { try { message = response.errorBody()!!.string() } catch (ignored: IOException) { Logger.d(ignored.message +"\n error while parsing response") } } if (message == null || message.trim { it <= ' ' }.isEmpty()) { message = response.message() } errorMessage = message body = null } val linkHeader = response.headers().get("link") if (linkHeader == null) { links = mutableMapOf() } else { links = androidx.collection.ArrayMap() val matcher = LINK_PATTERN.matcher(linkHeader) while (matcher.find()) { val count = matcher.groupCount() if (count == 2) { links[matcher.group(2)] = matcher.group(1) } } } } companion object { private val LINK_PATTERN = Pattern .compile("<([^>]*)>[\\s]*;[\\s]*rel=\"([a-zA-Z0-9]+)\"") private val PAGE_PATTERN = Pattern.compile("\\bpage=(\\d+)") private val NEXT_LINK = "next" } override fun toString(): String { return "ApiResponse(code=$code, body=$body, errorMessage=$errorMessage, links=$links)" } }
0
Kotlin
0
0
8dd243dbd3d849260988b3887dcf5d14ea462b39
3,010
skymusic.xms.box.app
Apache License 2.0
app/src/main/java/ds/meterscanner/mvvm/view/DetailsActivity.kt
mykola-dev
80,344,682
false
null
package ds.meterscanner.mvvm.view import com.bumptech.glide.load.engine.DiskCacheStrategy import com.github.salomonbrys.kodein.kodein import ds.bindingtools.arg import ds.bindingtools.withBindable import ds.meterscanner.R import ds.meterscanner.mvvm.BindableActivity import ds.meterscanner.mvvm.DetailsView import ds.meterscanner.mvvm.viewModelOf import ds.meterscanner.mvvm.viewmodel.DetailsViewModel import ds.meterscanner.ui.DatePickers import kotlinx.android.synthetic.main.activity_details.* import kotlinx.android.synthetic.main.toolbar.* class DetailsActivity : BindableActivity<DetailsViewModel>(), DetailsView { companion object { val REQUEST_DETAILS = 1 } val snapshotId by arg<String>() override fun provideViewModel(): DetailsViewModel = viewModelOf { DetailsViewModel(kodein().value, snapshotId) } override fun getLayoutId(): Int = R.layout.activity_details override fun pickDate() = DatePickers.pickDateTime(this, viewModel.truncDate(), viewModel::onDatePicked) override fun bindView() { super.bindView() dateField.keyListener = null datePickButton.setOnClickListener { viewModel.onDatePick(this) } saveButton.setOnClickListener { viewModel.onSave(this) } withBindable(viewModel) { bind(::imageUrl, { glide .load(it) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imageView) }) bind(::value, valueField) bind(valueError::error, valueLayout::setError) bind(::date, dateField) bind(::outsideTemp, outsideTempField) bind(::boilerTemp, boilerTempField) bind(::toolbarTitle, toolbar::setTitle, toolbar::getTitle) } } }
1
Kotlin
6
31
7e2a6e15721a7d52a98ca753a462645d6cee41ff
1,798
energy-meter-scanner
MIT License
flank-scripts/src/main/kotlin/flank/scripts/utils/Env.kt
piotradamczyk5
287,469,011
false
null
package flank.scripts.utils fun getEnv(key: String): String = System.getenv(key) ?: throw RuntimeException("Environment variable '$key' not found!") val isWindows: Boolean = System.getProperty("os.name").startsWith("Windows")
2
null
1
1
41c27e2bdb0fae1a6d8a0aa7242a36c4fe32dcc3
232
flank
Apache License 2.0
skiko/buildSrc/src/main/kotlin/utils.kt
JetBrains
282,864,178
false
null
import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.file.Directory import org.gradle.api.provider.Provider import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider import org.gradle.kotlin.dsl.register import java.util.* // Utils, that are not needed in scripts can be placed to internal/utils inline fun <reified T : Task> TaskContainer.registerOrGetTask( name: String, crossinline fn: T.() -> Unit ): Provider<T> { val taskProvider = if (name in names) named(name) else register(name, T::class) { fn(this) } return taskProvider.map { it as T } } inline fun <reified T : Task> Project.registerSkikoTask( taskName: String, crossinline fn: T.() -> Unit ): TaskProvider<T> = tasks.register(taskName, T::class) { fn() } inline fun <reified T : Task> Project.registerSkikoTask( actionName: String, targetOs: OS, targetArch: Arch, crossinline fn: T.() -> Unit ): TaskProvider<T> { val taskName = actionName + joinToTitleCamelCase(targetOs.id, targetArch.id) return registerSkikoTask(taskName, fn) } fun joinToTitleCamelCase(vararg parts: String): String = parts.joinToString(separator = "") { toTitleCase(it) } fun toTitleCase(s: String): String = s.capitalize(Locale.ROOT) fun Task.projectDirs(vararg relativePaths: String): List<Directory> { val projectDir = project.layout.projectDirectory return relativePaths.map { path -> projectDir.dir(path) } }
42
null
86
840
cf67c819f15ffcd8b6ecee3edb29ae2cdce1f2fe
1,484
skiko
Apache License 2.0
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/video/methods/VideoAddAlbum.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
@file:Suppress("unused", "MemberVisibilityCanBePrivate", "SpellCheckingInspection") package name.anton3.vkapi.generated.video.methods import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import name.anton3.vkapi.generated.video.objects.AddAlbumResponse import name.anton3.vkapi.generated.video.objects.AlbumPrivacy import name.anton3.vkapi.method.UserMethod import name.anton3.vkapi.method.VkMethod /** * [https://vk.com/dev/video.addAlbum] * * Creates an empty album for videos. * * @property groupId Community ID (if the album will be created in a community). * @property title Album title. * @property privacy new access permissions for the album. Possible values: , *'0' - all users,, *'1' - friends only,, *'2' - friends and friends of friends,, *'3' - "only me". */ data class VideoAddAlbum( var groupId: Long? = null, var title: String? = null, var privacy: List<AlbumPrivacy>? = null ) : VkMethod<AddAlbumResponse, UserMethod>("video.addAlbum", jacksonTypeRef())
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
999
kotlin-vk-api
MIT License
livemap/src/commonMain/kotlin/jetbrains/livemap/mapengine/camera/Components.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.livemap.mapengine.camera import jetbrains.livemap.core.ecs.EcsComponent class ZoomFractionChangedComponent : EcsComponent // Zoom changed to a value and fraction part is zero, e.g. 1.4 -> 2.0, or 1.3 -> 1.0 class ZoomLevelChangedComponent : EcsComponent class CenterChangedComponent : EcsComponent class CameraListenerComponent : EcsComponent class CameraComponent(private val myCamera: Camera) : EcsComponent { val zoom get() = myCamera.zoom val position get() = myCamera.position }
98
Kotlin
46
886
30f147b2ab81c2b4f6bb29ba7a5e41ad3245cdfd
660
lets-plot
MIT License
telegram/src/main/kotlin/me/ivmg/telegram/Poll.kt
seik
260,198,511
true
null
package me.ivmg.telegram import com.google.gson.annotations.SerializedName as Name import me.ivmg.telegram.entities.PollOption data class Poll( val id: Long, val question: String, val options: List<PollOption>, @Name("is_closed") val isClosed: Boolean )
0
null
0
1
6c33ea157af3001c8e75d860f6cdaa395a46945e
272
kotlin-telegram-bot
Apache License 2.0
app/src/main/java/com/testwther/ui/map/MapViewModel.kt
Pawlo210286
274,120,293
false
null
package com.testwther.ui.map import androidx.lifecycle.ViewModel import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.maps.android.ktx.addMarker import com.testwther.common.utils.PermissionChecker import com.testwther.domain.useCase.WeatherUseCase import com.testwther.ui.map.common.MarkerAdapter import kotlinx.coroutines.* class MapViewModel( private val permissionChecker: PermissionChecker, private val weatherUseCase: WeatherUseCase, private val markerAdapter: MarkerAdapter ) : ViewModel(), OnMapReadyCallback, GoogleMap.OnMapClickListener { private val job = Job() private val scope = CoroutineScope(Dispatchers.IO + job) private var map: GoogleMap? = null private var currentMarker: Marker? = null override fun onMapReady(map: GoogleMap?) { this.map = map map?.apply { uiSettings?.isZoomControlsEnabled = true uiSettings?.isZoomGesturesEnabled = true scope.launch { if (permissionChecker.checkLocationPermission()) { withContext(Dispatchers.Main) { isMyLocationEnabled = true } } } setOnMapClickListener(this@MapViewModel) setInfoWindowAdapter(markerAdapter) } } override fun onCleared() { map = null job.cancel() super.onCleared() } override fun onMapClick(location: LatLng?) { scope.launch { location?.let { weatherUseCase.getWeather(it.latitude, it.longitude) }?.let { it.current }?.let { withContext(Dispatchers.Main) { currentMarker?.remove() currentMarker = map?.addMarker { snippet(it.toString()) position(location) } currentMarker?.showInfoWindow() } } } } }
0
Kotlin
0
0
a8e2c2a7eb2ce6fc8e9f4d2d6218229de7d2dc24
2,168
testWther
MIT License
src/test/kotlin/com/tenkiv/tekdaqc/communication/ascii/message/parsing/DataMessageSpec.kt
Tenkiv
52,028,396
false
null
package com.tenkiv.tekdaqc.communication.ascii.message.parsing import com.tenkiv.tekdaqc.* import io.kotlintest.matchers.shouldBe import io.kotlintest.matchers.shouldNotBe import io.kotlintest.matchers.shouldThrow import io.kotlintest.specs.ShouldSpec /** * Class to test DataMessage generation. */ class DataMessageSpec : ShouldSpec({ "Analog Input Data Message Spec"{ val message = getAnalogTestMessage() should("Generate values correctly") { message.mNumber shouldBe 0 message.mTimestamps shouldBe "967711311300" message.mReadings shouldBe -512 } should("Serialize correctly") { val obj = serializeToAny(message) (obj is ASCIIAnalogInputDataMessage) shouldBe true (obj as ASCIIAnalogInputDataMessage).mNumber shouldBe 0 (obj).mTimestamps shouldBe "967711311300" (obj).mReadings shouldBe -512 } should("Reset value") { message.reset() message.mName shouldBe null message.mNumber shouldBe 0 message.mReadings shouldBe 0 message.mTimestamps shouldBe null } should("Fail in parsing") { shouldThrow<IllegalArgumentException> { ASCIIAnalogInputDataMessage("RANDOMDATA") } shouldThrow<IllegalArgumentException> { ASCIIAnalogInputDataMessage("Analog Input ASDFSD") } } } "Digital Input Data Message Spec"{ val message = getDigitalTestMessage() should("Generate values correctly") { message.mNumber shouldBe 0 message.mTimestamps shouldBe "967711311300" message.mReadings shouldBe false } should("Serialize correctly") { val obj = serializeToAny(message) (obj is ASCIIDigitalInputDataMessage) shouldBe true (obj as ASCIIDigitalInputDataMessage).mNumber shouldBe 0 (obj).mTimestamps shouldBe "967711311300" (obj).mReadings shouldBe false } should("Reset value") { message.reset() message.mName shouldBe null message.mNumber shouldBe 0 message.mReadings shouldBe false message.mTimestamps shouldBe null } should("Fail in parsing") { shouldThrow<IllegalArgumentException> { ASCIIDigitalInputDataMessage("RANDOMDATA") } shouldThrow<IllegalArgumentException> { ASCIIDigitalInputDataMessage("Digital Input ASDFSD") } } } "Command Message Spec"{ val message = getCommandTestMessage() should("Generate values correctly") { message.mMessageString shouldNotBe null message.type shouldBe ASCIIMessageUtils.MESSAGE_TYPE.COMMAND_DATA } should("Serialize correctly") { val obj = serializeToAny(message) (obj is ASCIICommandMessage) shouldBe true (obj as ASCIICommandMessage).mMessageString shouldNotBe null } should("Reset value") { message.reset() message.mMessageString shouldBe null } } "Debug Message Spec"{ val message = getDebugTestMessage() should("Generate values correctly") { message.mMessageString shouldNotBe null message.type shouldBe ASCIIMessageUtils.MESSAGE_TYPE.DEBUG } should("Serialize correctly") { val obj = serializeToAny(message) (obj is ASCIIDebugMessage) shouldBe true (obj as ASCIIDebugMessage).mMessageString shouldNotBe null } should("Reset value") { message.reset() message.mMessageString shouldBe null } } "Error Message Spec"{ val message = getErrorTestMessage() should("Generate values correctly") { message.mMessageString shouldNotBe null message.type shouldBe ASCIIMessageUtils.MESSAGE_TYPE.ERROR } should("Serialize correctly") { val obj = serializeToAny(message) (obj is ASCIIErrorMessage) shouldBe true (obj as ASCIIErrorMessage).mMessageString shouldNotBe null } should("Reset value") { message.reset() message.mMessageString shouldBe null } } "Status Message Spec"{ val message = getStatusTestMessage() should("Generate values correctly") { message.mMessageString shouldNotBe null } should("Serialize correctly") { val obj = serializeToAny(message) (obj is ASCIIStatusMessage) shouldBe true (obj as ASCIIStatusMessage).mMessageString shouldNotBe null } should("Reset value") { message.reset() message.mMessageString shouldBe null } } }) /** * Function to get fake AnalogMessage * * @return A fake message */ fun getAnalogTestMessage(): ASCIIAnalogInputDataMessage = ASCIIAnalogInputDataMessage(TEST_ANALOG_INPUT_DATA) /** * Function to get fake DigitalMessage * * @return A fake message */ fun getDigitalTestMessage(): ASCIIDigitalInputDataMessage = ASCIIDigitalInputDataMessage(TEST_DIGITAL_INPUT_DATA) /** * Function to get fake CommandMessage * * @return A fake message */ fun getCommandTestMessage(): ASCIICommandMessage = ASCIICommandMessage( TEST_COMMAND_MESSAGE_DATA) /** * Function to get fake DebugMessage * * @return A fake message */ fun getDebugTestMessage(): ASCIIDebugMessage = ASCIIDebugMessage( TEST_DEBUG_MESSAGE_DATA) /** * Function to get fake ErrorMessage * * @return A fake message */ fun getErrorTestMessage(): ASCIIErrorMessage = ASCIIErrorMessage( TEST_ERROR_MESSAGE_DATA) /** * Function to get fake StatusMessage * * @return A fake message */ fun getStatusTestMessage(): ASCIIStatusMessage = ASCIIStatusMessage( TEST_STATUS_MESSAGE_DATA)
7
Kotlin
0
0
b4164670ab815a248103816aaf1397b0a9bd6a38
5,979
Tekdaqc-JVM-Library
Apache License 2.0
OnlinePK-Android/lib-modularity/src/main/java/com/netease/yunxin/nertc/module/base/ApplicationLifecycleMgr.kt
netease-george
377,830,443
true
{"Objective-C": 1325069, "Kotlin": 611041, "Java": 270376, "Swift": 124836, "C": 6974, "Python": 2874, "Ruby": 797}
/* * Copyright (c) 2021 NetEase, Inc. All rights reserved. * Use of this source code is governed by a MIT license that can be found in the LICENSE file */ package com.netease.yunxin.nertc.module.base import android.app.Application import java.util.* /** * 单例,管理application 生命周期以及回调触发 */ class ApplicationLifecycleMgr private constructor() { private val lifecycleMap: MutableMap<Class<out AbsApplicationLifecycle>, AbsApplicationLifecycle> = HashMap() companion object { val instance = Holder.holder } private object Holder { val holder = ApplicationLifecycleMgr() } //------------------------------------------------------------------------------------ /** * 生命周期注册 */ fun registerLifecycle(lifecycle: AbsApplicationLifecycle?): ApplicationLifecycleMgr { if (lifecycle == null) { return this } if (lifecycleMap.containsKey(lifecycle.javaClass) || lifecycleMap.containsValue(lifecycle)) { return this } lifecycleMap[lifecycle.javaClass] = lifecycle return this } /** * @param commonRunner 各个模块通用初始化信息 */ @JvmOverloads fun notifyOnCreate(application: Application, commonRunner: Runnable? = null) { commonRunner?.run() for (lifecycle in lifecycleMap.values) { lifecycle.onModuleCreate(application) } } fun <T : AbsApplicationLifecycle?> getLifecycle(tClass: Class<T>): T? { val lifecycle: Any? = lifecycleMap[tClass] return if (tClass.isInstance(lifecycle)) lifecycle as T? else null } }
0
Objective-C
0
0
9ba2e45734d24bcc287a08288e25b6d27856744d
1,627
OnlinePK
MIT License
app/src/main/java/com/apptive/linkit/data/network/model/response/UserResponse.kt
Cotidie
448,929,843
false
null
package com.apptive.linkit.data.network.model.response import com.google.gson.annotations.SerializedName /** 구글 로그인 요청 시 서버로부터 반환받을 자료형 */ data class GoogleLoginResponse( @SerializedName("access_token") val accessToken: String, val email: String, val name: String ) data class UserResponse( val userId: Int, val Id: Int, val title: String, val completed: Boolean )
10
Kotlin
1
3
9396b6dcf0d92cb46722b3fc4ba76c2d2007f2ae
399
Linkit-App
Apache License 2.0
delta-coverage-core/src/main/kotlin/io/github/surpsg/deltacoverage/report/CoverageViolationsPropagator.kt
gw-kit
614,080,411
false
{"Kotlin": 368842, "Java": 3158}
package io.github.surpsg.deltacoverage.report import io.github.surpsg.deltacoverage.exception.CoverageViolatedException import org.slf4j.Logger import org.slf4j.LoggerFactory import java.lang.invoke.MethodHandles internal class CoverageViolationsPropagator { fun propagateAll( verificationResults: Iterable<CoverageVerificationResult>, ) { val exceptionMsg: String = verificationResults.asSequence() .mapNotNull { result -> filterOutSoftViolations(result) } .flatMap { result -> result.contextualViolations().asSequence() } .joinToString(";\n") if (exceptionMsg.isNotBlank()) { throw CoverageViolatedException(exceptionMsg) } } private fun filterOutSoftViolations( verificationResult: CoverageVerificationResult, ): CoverageVerificationResult? { log.info( "[{}] Fail on violations: {}. Found violations: {}.", verificationResult.view, verificationResult.coverageRulesConfig.failOnViolation, verificationResult.violations.size, ) return if (verificationResult.coverageRulesConfig.failOnViolation) { verificationResult } else { verificationResult.violations.forEach { violation -> log.warn(violation) } null } } companion object { private val log: Logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()) } }
8
Kotlin
6
22
86ebb4745714e71d96747a6554b8d82e2d9869e1
1,507
delta-coverage-plugin
MIT License
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/WrenchSolid.kt
DevSrSouza
311,134,756
false
null
package compose.icons.lineawesomeicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.LineAwesomeIcons public val LineAwesomeIcons.WrenchSolid: ImageVector get() { if (_wrenchSolid != null) { return _wrenchSolid!! } _wrenchSolid = Builder(name = "WrenchSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.0f, 4.0f) curveTo(17.1445f, 4.0f, 14.0f, 7.1445f, 14.0f, 11.0f) curveTo(14.0f, 11.7148f, 14.2148f, 12.3633f, 14.4141f, 13.0156f) lineTo(4.9453f, 22.4844f) curveTo(3.6875f, 23.7383f, 3.6875f, 25.8008f, 4.9453f, 27.0586f) curveTo(6.1992f, 28.3125f, 8.2617f, 28.3125f, 9.5156f, 27.0586f) lineTo(18.9844f, 17.5898f) curveTo(19.6328f, 17.7891f, 20.2852f, 18.0f, 21.0f, 18.0f) curveTo(24.8555f, 18.0f, 28.0f, 14.8555f, 28.0f, 11.0f) curveTo(28.0f, 9.9727f, 27.7734f, 9.0f, 27.375f, 8.125f) lineTo(26.7813f, 6.8047f) lineTo(25.7617f, 7.8281f) lineTo(22.5859f, 11.0f) lineTo(21.0f, 11.0f) lineTo(21.0f, 9.4141f) lineTo(25.1953f, 5.2188f) lineTo(23.875f, 4.625f) curveTo(23.0f, 4.2266f, 22.0273f, 4.0f, 21.0f, 4.0f) close() moveTo(21.0f, 6.0f) curveTo(21.1719f, 6.0f, 21.3164f, 6.0859f, 21.4844f, 6.1016f) lineTo(19.0f, 8.5859f) lineTo(19.0f, 13.0f) lineTo(23.4141f, 13.0f) lineTo(25.8945f, 10.5156f) curveTo(25.9141f, 10.6836f, 26.0f, 10.8281f, 26.0f, 11.0f) curveTo(26.0f, 13.7734f, 23.7734f, 16.0f, 21.0f, 16.0f) curveTo(20.3008f, 16.0f, 19.6367f, 15.8555f, 19.0313f, 15.5977f) lineTo(18.4102f, 15.332f) lineTo(8.1016f, 25.6406f) curveTo(7.6211f, 26.125f, 6.8398f, 26.125f, 6.3594f, 25.6406f) curveTo(5.875f, 25.1602f, 5.875f, 24.3789f, 6.3594f, 23.8945f) lineTo(16.668f, 13.5898f) lineTo(16.4023f, 12.9648f) curveTo(16.1445f, 12.3594f, 16.0f, 11.6992f, 16.0f, 11.0f) curveTo(16.0f, 8.2266f, 18.2266f, 6.0f, 21.0f, 6.0f) close() } } .build() return _wrenchSolid!! } private var _wrenchSolid: ImageVector? = null
15
null
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
3,227
compose-icons
MIT License
course/src/main/java/de/hpi/android/course/presentation/detail/CourseDetailViewModel.kt
HPI-de
168,352,832
false
null
package de.hpi.android.course.presentation.detail import de.hpi.android.core.data.Id import de.hpi.android.core.presentation.base.BaseViewModel import de.hpi.android.core.utils.appendLine import de.hpi.android.core.utils.asLiveData import de.hpi.android.core.utils.data import de.hpi.android.core.utils.map import de.hpi.android.course.data.CourseDetailDto import de.hpi.android.course.data.CourseDto import de.hpi.android.course.domain.GetCourseDetailUseCase import de.hpi.android.course.domain.GetCourseUseCase class CourseDetailViewModel : BaseViewModel() { private val courseId = Id<CourseDto>("2019ss-www") // TODO: use navigation arguments private val courseResult = GetCourseUseCase(courseId).asLiveData() val course = courseResult.data @Suppress("UNCHECKED_CAST") private val courseDetailResult = GetCourseDetailUseCase(courseId as Id<CourseDetailDto>).asLiveData() val courseDetail = courseDetailResult.data val assistants = course.map { it?.assistants?.joinToString() } val modules = courseDetail.map { courseDetail -> if (courseDetail == null) return@map null buildString { for ((program, moduleList) in courseDetail.modules) { appendLine(program) for (module in moduleList) appendLine("\t\t$module") } } } }
48
Kotlin
1
7
65c00f511f2eff3e1c08fe67fda1bc2dac85daba
1,362
hpi-android
Apache License 2.0
app/src/main/java/com/github/cyc/wanandroid/http/model/Navigation.kt
chongyucaiyan
163,415,227
false
{"Kotlin": 119681}
package com.github.cyc.wanandroid.http.model import com.github.cyc.wanandroid.app.NoProguard data class Navigation( val cid: Int, val name: String, val articles: List<Article> ) : NoProguard
1
Kotlin
1
1
1d015bf4254dfce133093127ad4f87a925eac8c8
216
WanAndroid-Kotlin
Apache License 2.0
data/src/main/java/com/example/data/cloud/source/questions/QuestionsCloudDataSource.kt
yusuf0405
484,801,816
false
null
package com.example.data.cloud.source.questions interface QuestionsCloudDataSource { suspend fun fetchAllQuestionsPosters(): List<String> }
1
Kotlin
1
3
067abb34f0348b0dda1f05470a32ecbed59cfb19
144
BookLoverFinalApp
Apache License 1.1
android/navigation_module_compose/src/main/java/com/example/sdk/sample/ui/home/HomeScreen.kt
citymapper
346,046,671
false
null
package com.example.sdk.sample.ui.home import android.content.Context import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.AlertDialog import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStore import androidx.lifecycle.viewmodel.compose.viewModel import com.citymapper.sdk.core.ApiResult import com.citymapper.sdk.directions.CitymapperDirections import com.citymapper.sdk.navigation.CitymapperNavigationTracking import com.citymapper.sdk.navigation.StartNavigationResult.Failure import com.citymapper.sdk.navigation.StartNavigationResult.FailureReason.RouteNotSupported import com.citymapper.sdk.navigation.StartNavigationResult.FailureReason.UserTooFarFromRoute import com.example.sdk.sample.ui.common.SampleLoading import com.example.sdk.sample.ui.common.demoColors import com.example.sdk.sample.ui.map.MapView import com.example.sdk.sample.ui.map.renderMarker import com.example.sdk.sample.ui.map.renderRoute import com.example.sdk.sample.utils.ViewModelCreator import com.example.sdk.sample.utils.asCoords import com.example.sdk.sample.utils.asLatLng import com.example.sdk.sample.utils.checkLocationPermission import com.example.sdk.sample.utils.getLastLocation import com.example.sdk.sample.utils.toPx import com.google.android.gms.maps.model.BitmapDescriptorFactory private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") @Composable fun HomeScreen() { val context = LocalContext.current val viewModel = viewModel<HomeViewModel>( factory = ViewModelCreator { HomeViewModel( navigation = CitymapperNavigationTracking.getInstance(context), directions = CitymapperDirections.getInstance(context), dataStore = context.dataStore ) } ) val state = viewModel.viewState val scope = rememberCoroutineScope() viewModel.setLocationPermission(checkLocationPermission(context)) SettingsDrawer( state = viewModel.viewState, profileCallback = { viewModel.setProfile(it) }, apiCallCallback = { viewModel.setAvailableApi(it) }, brandIdCallback = { viewModel.setBrandId(it) }, removeCustomVehicleCallback = { viewModel.setCustomVehicleLocation(null) } ) { MapView( position = state.getCameraPosition(), mapContent = state, onMapClick = { endLocation -> if (!state.isNavigationActive) { getLastLocation(scope, context) { userLocation -> if (userLocation != null) { viewModel.setStart(userLocation.asCoords()) viewModel.setEnd(endLocation.asCoords()) } } } }, onMapLongClick = { viewModel.setCustomVehicleLocation(it.asCoords()) }, setupMap = { isMyLocationEnabled = state.hasLocationPermission == true uiSettings.isMyLocationButtonEnabled = true uiSettings.isMapToolbarEnabled = false }, renderContent = { context, viewState -> val bottomPadding = when { viewState.isNavigationActive -> 234.toPx(context) viewState.directions is ApiResult.Success -> 112.toPx(context) else -> 0 } setPadding(0, 0, 0, bottomPadding) renderRoute(context, viewState.routePathSegments, demoColors) renderMarker(viewState.end?.asLatLng(), BitmapDescriptorFactory.HUE_BLUE) if (AvailableApi.useCustomVehicle.contains(viewState.availableApi)) { renderMarker( viewState.customVehicleLocation?.asLatLng(), BitmapDescriptorFactory.HUE_GREEN ) } } ) if (state.hasLocationPermission != null && !state.hasLocationPermission) { EnableLocationSnackBar { hasPermission -> viewModel.setLocationPermission(hasPermission) } } when { state.isLoading -> SampleLoading() state.isNavigationActive -> GuidanceContainer( viewState = state, endGo = { viewModel.endGo() }, vehicleLockState = { viewModel.setVehicleLockState(it) } ) state.directions is ApiResult.Failure -> ErrorDialog("Oh noes") { viewModel.consumeApiError() } state.directions is ApiResult.Success && state.route != null -> PreviewContainer(state.route) { viewModel.startGo() } } if (state.startNavigationFailure != null) { StartNavigationFailureDialog( startNavigationFailure = state.startNavigationFailure, onDismiss = viewModel::dismissStartNavigationFailure ) } } } @Composable private fun StartNavigationFailureDialog( startNavigationFailure: Failure, onDismiss: () -> Unit ) { AlertDialog( onDismissRequest = onDismiss, buttons = { Column( modifier = Modifier .fillMaxWidth() .padding(4.dp) ) { TextButton( onClick = onDismiss, modifier = Modifier.align(Alignment.End) ) { Text(text = "Dismiss") } } }, text = { val message = when (startNavigationFailure.reason) { RouteNotSupported -> "Route not supported" UserTooFarFromRoute -> "User too far from route" } Text(text = message) } ) }
1
null
2
4
87d37d87de5ef26c21779f4c5d2856a3413c71cb
5,740
sdk-samples
MIT License
sdk/src/main/java/io/portone/sdk/android/type/Installment.kt
portone-io
835,174,061
false
{"Kotlin": 197769, "HTML": 1179}
package io.portone.sdk.android.type import android.os.Parcelable import kotlinx.parcelize.Parcelize import kotlinx.serialization.Serializable @Serializable @Parcelize data class Installment( val monthOption: MonthOption?, val freeInstallmentPlans: List<FreeInstallmentPlan>? ) : Parcelable { @Serializable @Parcelize sealed interface MonthOption : Parcelable { @Serializable @Parcelize data class FixedMonth(val month: Int) : MonthOption @Serializable @Parcelize data class AvailableMonths(val months: List<Int>) : MonthOption } @Serializable @Parcelize data class FreeInstallmentPlan( val months: List<Int>, val cardCompany: CardCompany ) : Parcelable }
0
Kotlin
0
2
07509908b066a19fc5e0e96afca415816687d2f4
763
android-sdk
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/apigatewayv2/ThrottleSettingsDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.apigatewayv2 import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.Number import software.amazon.awscdk.services.apigatewayv2.ThrottleSettings /** * Container for defining throttling parameters to API stages. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.apigatewayv2.*; * ThrottleSettings throttleSettings = ThrottleSettings.builder() * .burstLimit(123) * .rateLimit(123) * .build(); * ``` */ @CdkDslMarker public class ThrottleSettingsDsl { private val cdkBuilder: ThrottleSettings.Builder = ThrottleSettings.builder() /** * @param burstLimit The maximum API request rate limit over a time ranging from one to a few * seconds. */ public fun burstLimit(burstLimit: Number) { cdkBuilder.burstLimit(burstLimit) } /** * @param rateLimit The API request steady-state rate limit (average requests per second over an * extended period of time). */ public fun rateLimit(rateLimit: Number) { cdkBuilder.rateLimit(rateLimit) } public fun build(): ThrottleSettings = cdkBuilder.build() }
0
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
1,491
awscdk-dsl-kotlin
Apache License 2.0
src/poker/src/test/kotlin/com/github/jensbarthel/nnpoker/domain/game/hand/HighCardRank_When_comparing.kt
jensbarthel
175,876,618
false
null
package com.github.jensbarthel.nnpoker.domain.game.hand import com.github.jensbarthel.nnpoker.domain.game.deck.Face.* import com.github.jensbarthel.nnpoker.domain.game.deck.Suit.* import com.github.jensbarthel.nnpoker.domain.game.deck.of import com.github.jensbarthel.nnpoker.domain.game.hand.HandRank.Opinion.NONE import com.github.jensbarthel.nnpoker.domain.game.hand.HandRank.Opinion.PAIR import io.mockk.every import io.mockk.mockk import org.amshove.kluent.`should be equal to` import org.amshove.kluent.`should throw` import org.amshove.kluent.invoking import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestFactory import util.parameterizedTest internal class HighCardRank_When_comparing { @TestFactory fun `If opinions are different Then they are compared`() = parameterizedTest( Pair(NONE, 1), Pair(PAIR, -1) ) { (otherOpinion, expectedComparison) -> // Arrange val otherRank = BasicRank(otherOpinion, emptySet()) // Act val comparison = HighCardRank(mockk()).compareTo(otherRank) // Assert comparison `should be equal to` expectedComparison } @TestFactory fun `If opinions are same Then compare highest cards`() = parameterizedTest( Triple( setOf( ACE of HEARTS ), setOf( ACE of DIAMONDS ), 0 ), Triple( setOf( EIGHT of SPADES, ACE of HEARTS ), setOf( SEVEN of CLUBS, ACE of DIAMONDS ), 1 ), Triple( setOf( SIX of SPADES, ACE of HEARTS ), setOf( SEVEN of CLUBS, ACE of DIAMONDS ), -1 ) ) { (cards, otherCards, expectedComparison) -> // Arrange val highCardRank = HighCardRank(cards) val otherRank = HighCardRank(otherCards) // Act val comparison = highCardRank.compareTo(otherRank) // Assert comparison `should be equal to` expectedComparison } @Test fun `If opinions are same but matching card sizes differ Then throw`() { // Arrange val highCardRank = HighCardRank(setOf(ACE of SPADES)) val otherRank = HighCardRank(emptySet()) // Act & Assert invoking { highCardRank.compareTo(otherRank) } `should throw` IllegalArgumentException::class } }
0
Kotlin
0
0
861fa1d750106ab38ad217848bb305e29292e89b
2,495
nnpoker
MIT License
grovlin-compiler/src/main/kotlin/io/gitlab/arturbosch/grovlin/compiler/java/JavaToBytecodeTransformer.kt
arturbosch
80,819,243
false
null
package io.gitlab.arturbosch.grovlin.compiler.java import io.gitlab.arturbosch.grovlin.compiler.backend.CPackage import io.gitlab.arturbosch.grovlin.compiler.java.inmemory.JavaStringCompiler import java.io.File /** * @author <NAME> */ private val compiler = JavaStringCompiler() fun writeToDisk(file: File, cPackage: CPackage) { val javaFiles = cPackage.all() .map { it.javaFileName to it.unit.toString() } .toMap() val nameToBytes = compiler.compile(javaFiles) for ((fileName, content) in nameToBytes) { file.resolve(fileName + ".class").writeBytes(content) } } fun CPackage.interpret() { val javaFiles = all().map { it.javaFileName to it.unit.toString() }.toMap() val map = compiler.compile(javaFiles) compiler.run(main.fileName, map) }
8
Kotlin
1
6
3bfd23cc6fd91864611e785cf2c990b3a9d83e63
761
grovlin
Apache License 2.0
app/src/main/java/com/kongjak/koreatechboard/MainActivity.kt
kongwoojin
507,629,548
false
{"Kotlin": 52710}
package com.kongjak.koreatechboard import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import com.google.android.material.navigation.NavigationView import com.kongjak.koreatechboard.activity.SettingsActivity import com.kongjak.koreatechboard.fragment.* class MainActivity : AppCompatActivity() { lateinit var defaultFragment: Fragment lateinit var fragment: Fragment lateinit var drawerLayout: DrawerLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) val navView: NavigationView = findViewById(R.id.nav_view) drawerLayout = findViewById(R.id.drawer_layout) setSupportActionBar(toolbar) supportActionBar!!.apply { setDisplayHomeAsUpEnabled(true) setHomeAsUpIndicator(R.drawable.ic_nav_menu) } toolbar.setNavigationOnClickListener { drawerLayout.open() } val schoolFragment = SchoolFragment() val cseFragment = CseFragment() val mechanicalFragment = MechanicalFragment() val mechatronicsFragment = MechatronicsFragment() val iteFragment = IteFragment() val ideFragment = IdeFragment() val archFragment = ArchFragment() val emcFragment = EmcFragment() val simFragment = SimFragment() val dormFragment = DormFragment() val prefs = PreferenceManager.getDefaultSharedPreferences(this) when (prefs.getString("default_board", "school")) { "school" -> { defaultFragment = schoolFragment navView.setCheckedItem(R.id.nav_drawer_school) } "cse" -> { defaultFragment = cseFragment navView.setCheckedItem(R.id.nav_drawer_cse) } "dorm" -> { defaultFragment = dormFragment navView.setCheckedItem(R.id.nav_drawer_dorm) } "mechanical" -> { defaultFragment = mechanicalFragment navView.setCheckedItem(R.id.nav_drawer_mechanical) } "mechatronics" -> { defaultFragment = mechatronicsFragment navView.setCheckedItem(R.id.nav_drawer_mechatronics) } "ite" -> { defaultFragment = iteFragment navView.setCheckedItem(R.id.nav_drawer_ite) } "ide" -> { defaultFragment = ideFragment navView.setCheckedItem(R.id.nav_drawer_ide) } "arch" -> { defaultFragment = archFragment navView.setCheckedItem(R.id.nav_drawer_arch) } "emc" -> { defaultFragment = emcFragment navView.setCheckedItem(R.id.nav_drawer_emc) } "sim" -> { defaultFragment = simFragment navView.setCheckedItem(R.id.nav_drawer_sim) } else -> { defaultFragment = schoolFragment navView.setCheckedItem(R.id.nav_drawer_school) } } fragment = if (savedInstanceState == null) { defaultFragment } else { supportFragmentManager.getFragment(savedInstanceState, "fragment")!! } loadFragment() navView.setNavigationItemSelectedListener { menuItem -> menuItem.isChecked = true drawerLayout.close() when (menuItem.itemId) { R.id.nav_drawer_school -> { fragment = schoolFragment loadFragment() } R.id.nav_drawer_dorm -> { fragment = dormFragment loadFragment() } R.id.nav_drawer_cse -> { fragment = cseFragment loadFragment() } R.id.nav_drawer_mechanical -> { fragment = mechanicalFragment loadFragment() } R.id.nav_drawer_mechatronics -> { fragment = mechatronicsFragment loadFragment() } R.id.nav_drawer_ite -> { fragment = iteFragment loadFragment() } R.id.nav_drawer_ide -> { fragment = ideFragment loadFragment() } R.id.nav_drawer_arch -> { fragment = archFragment loadFragment() } R.id.nav_drawer_emc -> { fragment = emcFragment loadFragment() } R.id.nav_drawer_sim -> { fragment = simFragment loadFragment() } R.id.nav_drawer_settings -> { val intent = Intent(this, SettingsActivity::class.java) startActivity(intent) } } true } } private fun loadFragment() { supportFragmentManager .beginTransaction() .replace(R.id.main_frame_layout, fragment) .commit() } override fun onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) supportFragmentManager.putFragment(outState, "fragment", fragment) } }
2
Kotlin
0
0
3808c284acb0de7498600e8d36053dff7b9229ad
6,131
koreatech-board-android
MIT License
app/src/main/java/org/wikipedia/util/DeviceUtil.kt
dbrant
28,157,306
true
{"Java": 2472470, "Kotlin": 315335, "Python": 20806, "Shell": 1800, "HTML": 1233}
package org.wikipedia.util import android.app.Activity import android.content.Context import android.graphics.Color import android.net.ConnectivityManager import android.os.Build import android.view.KeyCharacterMap import android.view.KeyEvent import android.view.View import android.view.WindowManager import android.view.accessibility.AccessibilityManager import android.view.inputmethod.InputMethodManager import androidx.appcompat.widget.Toolbar import androidx.core.graphics.BlendModeColorFilterCompat import androidx.core.graphics.BlendModeCompat import org.wikipedia.R import org.wikipedia.WikipediaApp object DeviceUtil { /** * Attempt to display the Android keyboard. * * FIXME: This should not need to exist. * Android should always show the keyboard at the appropriate time. This method allows you to display the keyboard * when Android fails to do so. * * @param view The currently focused view that will receive the keyboard input */ @JvmStatic fun showSoftKeyboard(view: View) { val keyboard = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager keyboard.toggleSoftInput(0, 0) } /** * Attempt to hide the Android Keyboard. * * FIXME: This should not need to exist. * I do not know why Android does not handle this automatically. * * @param activity The current activity */ @JvmStatic fun hideSoftKeyboard(activity: Activity) { hideSoftKeyboard(activity.window.decorView) } @JvmStatic fun hideSoftKeyboard(view: View) { val keyboard = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager // Not using getCurrentFocus as that sometimes is null, but the keyboard is still up. keyboard.hideSoftInputFromWindow(view.windowToken, 0) } @JvmStatic fun setWindowSoftInputModeResizable(activity: Activity) { activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) } fun setLightSystemUiVisibility(activity: Activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!WikipediaApp.getInstance().currentTheme.isDark) { // this make the system recognizes the status bar is light and will make status bar icons become visible activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { resetSystemUiVisibility(activity) } } } private fun resetSystemUiVisibility(activity: Activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.window.decorView.systemUiVisibility = 0 } } @JvmStatic fun updateStatusBarTheme(activity: Activity, toolbar: Toolbar?, reset: Boolean) { if (reset) { resetSystemUiVisibility(activity) } else { setLightSystemUiVisibility(activity) } toolbar?.navigationIcon!!.colorFilter = BlendModeColorFilterCompat .createBlendModeColorFilterCompat(if (reset) Color.WHITE else ResourceUtil.getThemedColor(activity, R.attr.toolbar_icon_color), BlendModeCompat.SRC_IN) } @JvmStatic fun setContextClickAsLongClick(vararg views: View) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { views.forEach { it.setOnContextClickListener { obj: View -> obj.performLongClick() } } } } @JvmStatic fun isOnWiFi(): Boolean { val info = (WikipediaApp.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager) .getNetworkInfo(ConnectivityManager.TYPE_WIFI) return info != null && info.isConnected } // TODO: revisit this if there's no more navigation bar by default. @JvmStatic val isNavigationBarShowing: Boolean get() = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK) && KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME) @JvmStatic val isAccessibilityEnabled: Boolean get() { val am = WikipediaApp.getInstance().getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager // TODO: add more logic if other accessibility tools have different settings. return am.isEnabled && am.isTouchExplorationEnabled } }
0
Java
0
2
33d4c162b0847ef4814d9ae7a6229d4877d8eb80
4,440
apps-android-wikipedia
Apache License 2.0
domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/AnalyticsControllerTest.kt
oppia
148,093,817
false
null
package org.oppia.android.domain.oppialogger.analytics import android.app.Application import android.content.Context import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import dagger.BindsInstance import dagger.Component import dagger.Module import dagger.Provides import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.oppia.android.domain.oppialogger.EventLogStorageCacheSize import org.oppia.android.domain.oppialogger.LoggingIdentifierModule import org.oppia.android.domain.oppialogger.OppiaLogger import org.oppia.android.domain.platformparameter.PlatformParameterModule import org.oppia.android.domain.platformparameter.PlatformParameterSingletonModule import org.oppia.android.testing.FakeAnalyticsEventLogger import org.oppia.android.testing.TestLogReportingModule import org.oppia.android.testing.data.DataProviderTestMonitor import org.oppia.android.testing.logging.EventLogSubject.Companion.assertThat import org.oppia.android.testing.logging.FakeSyncStatusManager import org.oppia.android.testing.logging.SyncStatusTestModule import org.oppia.android.testing.robolectric.RobolectricModule import org.oppia.android.testing.threading.TestDispatcherModule import org.oppia.android.testing.time.FakeOppiaClockModule import org.oppia.android.util.data.DataProviders import org.oppia.android.util.data.DataProvidersInjector import org.oppia.android.util.data.DataProvidersInjectorProvider import org.oppia.android.util.locale.LocaleProdModule import org.oppia.android.util.logging.EnableConsoleLog import org.oppia.android.util.logging.EnableFileLog import org.oppia.android.util.logging.GlobalLogLevel import org.oppia.android.util.logging.LogLevel import org.oppia.android.util.logging.SyncStatusManager.SyncStatus.DATA_UPLOADED import org.oppia.android.util.logging.SyncStatusManager.SyncStatus.DATA_UPLOADING import org.oppia.android.util.logging.SyncStatusManager.SyncStatus.NO_CONNECTIVITY import org.oppia.android.util.networking.NetworkConnectionDebugUtil import org.oppia.android.util.networking.NetworkConnectionUtil.ProdConnectionStatus.NONE import org.oppia.android.util.networking.NetworkConnectionUtilDebugModule import org.robolectric.annotation.Config import org.robolectric.annotation.LooperMode import javax.inject.Inject import javax.inject.Singleton private const val TEST_TIMESTAMP = 1556094120000 private const val TEST_TOPIC_ID = "test_topicId" private const val TEST_STORY_ID = "test_storyId" private const val TEST_EXPLORATION_ID = "test_explorationId" private const val TEST_QUESTION_ID = "test_questionId" private const val TEST_SKILL_ID = "test_skillId" private const val TEST_SKILL_LIST_ID = "test_skillListId" private const val TEST_SUB_TOPIC_ID = 1 /** Tests for [AnalyticsController]. */ // FunctionName: test names are conventionally named with underscores. @Suppress("FunctionName") @RunWith(AndroidJUnit4::class) @LooperMode(LooperMode.Mode.PAUSED) @Config(application = AnalyticsControllerTest.TestApplication::class) class AnalyticsControllerTest { @Inject lateinit var analyticsController: AnalyticsController @Inject lateinit var oppiaLogger: OppiaLogger @Inject lateinit var networkConnectionUtil: NetworkConnectionDebugUtil @Inject lateinit var fakeAnalyticsEventLogger: FakeAnalyticsEventLogger @Inject lateinit var dataProviders: DataProviders @Inject lateinit var monitorFactory: DataProviderTestMonitor.Factory @Inject lateinit var fakeSyncStatusManager: FakeSyncStatusManager @Before fun setUp() { setUpTestApplicationComponent() } @Test fun testController_logImportantEvent_withQuestionContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenQuestionPlayerContext() } @Test fun testController_logImportantEvent_withExplorationContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenExplorationActivityContext( TEST_TOPIC_ID, TEST_STORY_ID, TEST_EXPLORATION_ID ) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenExplorationActivityContext() } @Test fun testController_logImportantEvent_withOpenInfoTabContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenInfoTabContext(TEST_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenInfoTabContext() } @Test fun testController_logImportantEvent_withOpenPracticeTabContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenPracticeTabContext(TEST_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenPracticeTabContext() } @Test fun testController_logImportantEvent_withOpenLessonsTabContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenLessonsTabContext(TEST_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenLessonsTabContext() } @Test fun testController_logImportantEvent_withOpenRevisionTabContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenRevisionTabContext(TEST_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenRevisionTabContext() } @Test fun testController_logImportantEvent_withStoryContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenStoryActivityContext(TEST_TOPIC_ID, TEST_STORY_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenStoryActivityContext() } @Test fun testController_logImportantEvent_withRevisionContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenRevisionCardContext(TEST_TOPIC_ID, TEST_SUB_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenRevisionCardContext() } @Test fun testController_logImportantEvent_withConceptCardContext_checkLogsEvent() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenConceptCardContext(TEST_SKILL_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenConceptCardContext() } @Test fun testController_logLowPriorityEvent_withQuestionContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenQuestionPlayerContext() } @Test fun testController_logLowPriorityEvent_withExplorationContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenExplorationActivityContext( TEST_TOPIC_ID, TEST_STORY_ID, TEST_EXPLORATION_ID ) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenExplorationActivityContext() } @Test fun testController_logLowPriorityEvent_withOpenInfoTabContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenInfoTabContext(TEST_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenInfoTabContext() } @Test fun testController_logLowPriorityEvent_withOpenPracticeTabContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenPracticeTabContext(TEST_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenPracticeTabContext() } @Test fun testController_logLowPriorityEvent_withOpenLessonsTabContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenLessonsTabContext(TEST_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenLessonsTabContext() } @Test fun testController_logLowPriorityEvent_withOpenRevisionTabContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenRevisionTabContext(TEST_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenRevisionTabContext() } @Test fun testController_logLowPriorityEvent_withStoryContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenStoryActivityContext(TEST_TOPIC_ID, TEST_STORY_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenStoryActivityContext() } @Test fun testController_logLowPriorityEvent_withRevisionContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenRevisionCardContext(TEST_TOPIC_ID, TEST_SUB_TOPIC_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenRevisionCardContext() } @Test fun testController_logLowPriorityEvent_withConceptCardContext_checkLogsEvent() { analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenConceptCardContext(TEST_SKILL_ID) ) val eventLog = fakeAnalyticsEventLogger.getMostRecentEvent() assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenConceptCardContext() } // TODO(#3621): Addition of tests tracking behaviour of the controller after uploading of logs to // the remote service. @Test fun testController_logImportantEvent_withNoNetwork_checkLogsEventToStore() { networkConnectionUtil.setCurrentConnectionStatus(NONE) analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) val eventLogsProvider = analyticsController.getEventLogStore() val eventLog = monitorFactory.waitForNextSuccessfulResult(eventLogsProvider).getEventLog(0) assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isEssentialPriority() assertThat(eventLog).hasOpenQuestionPlayerContext() } @Test fun testController_logLowPriorityEvent_withNoNetwork_checkLogsEventToStore() { networkConnectionUtil.setCurrentConnectionStatus(NONE) analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) val eventLogsProvider = analyticsController.getEventLogStore() val eventLog = monitorFactory.waitForNextSuccessfulResult(eventLogsProvider).getEventLog(0) assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(eventLog).isOptionalPriority() assertThat(eventLog).hasOpenQuestionPlayerContext() } @Test fun testController_logImportantEvent_withNoNetwork_exceedLimit_checkEventLogStoreSize() { networkConnectionUtil.setCurrentConnectionStatus(NONE) logMultipleEvents() val eventLogsProvider = analyticsController.getEventLogStore() val eventLogs = monitorFactory.waitForNextSuccessfulResult(eventLogsProvider) assertThat(eventLogs.eventLogList).hasSize(2) } @Test fun testController_logImportantEvent_logLowPriorityEvent_withNoNetwork_checkOrderinCache() { networkConnectionUtil.setCurrentConnectionStatus(NONE) analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) val eventLogsProvider = analyticsController.getEventLogStore() val eventLogs = monitorFactory.waitForNextSuccessfulResult(eventLogsProvider) val firstEventLog = eventLogs.getEventLog(0) val secondEventLog = eventLogs.getEventLog(1) assertThat(firstEventLog).isOptionalPriority() assertThat(secondEventLog).isEssentialPriority() } @Test fun testController_logImportantEvent_switchToNoNetwork_logLowPriorityEvent_checkManagement() { analyticsController.logImportantEvent( TEST_TIMESTAMP, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) networkConnectionUtil.setCurrentConnectionStatus(NONE) analyticsController.logLowPriorityEvent( TEST_TIMESTAMP, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) val logsProvider = analyticsController.getEventLogStore() val uploadedEventLog = fakeAnalyticsEventLogger.getMostRecentEvent() val cachedEventLog = monitorFactory.waitForNextSuccessfulResult(logsProvider).getEventLog(0) assertThat(uploadedEventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(uploadedEventLog).isEssentialPriority() assertThat(uploadedEventLog).hasOpenQuestionPlayerContext() assertThat(cachedEventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP) assertThat(cachedEventLog).isOptionalPriority() assertThat(cachedEventLog).hasOpenQuestionPlayerContext() } @Test fun testController_logEvents_exceedLimit_withNoNetwork_checkCorrectEventIsEvicted() { networkConnectionUtil.setCurrentConnectionStatus(NONE) logMultipleEvents() val logsProvider = analyticsController.getEventLogStore() val eventLogs = monitorFactory.waitForNextSuccessfulResult(logsProvider) val firstEventLog = eventLogs.getEventLog(0) val secondEventLog = eventLogs.getEventLog(1) assertThat(eventLogs.eventLogList).hasSize(2) // In this case, 3 ESSENTIAL and 1 OPTIONAL event was logged. So while pruning, none of the // retained logs should have OPTIONAL priority. assertThat(firstEventLog).isEssentialPriority() assertThat(secondEventLog).isEssentialPriority() // If we analyse the implementation of logMultipleEvents(), we can see that record pruning will // begin from the logging of the third record. At first, the second event log will be removed as // it has OPTIONAL priority and the event logged at the third place will become the event record // at the second place in the store. When the forth event gets logged then the pruning will be // purely based on timestamp of the event as both event logs have ESSENTIAL priority. As the // third event's timestamp was lesser than that of the first event, it will be pruned from the // store and the forth event will become the second event in the store. assertThat(firstEventLog).hasTimestampThat().isEqualTo(1556094120000) assertThat(secondEventLog).hasTimestampThat().isEqualTo(1556094100000) } @Test fun testController_logEvent_withoutNetwork_verifySyncStatusIsUnchanged() { networkConnectionUtil.setCurrentConnectionStatus(NONE) analyticsController.logImportantEvent( 1556094120000, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) assertThat(fakeSyncStatusManager.getSyncStatuses()).containsExactly(NO_CONNECTIVITY) } @Test fun testController_logEvent_verifySyncStatusChangesToRepresentLoggedEvent() { analyticsController.logImportantEvent( 1556094120000, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) val syncStatuses = fakeSyncStatusManager.getSyncStatuses() assertThat(syncStatuses).containsExactly(DATA_UPLOADING, DATA_UPLOADED) } private fun setUpTestApplicationComponent() { ApplicationProvider.getApplicationContext<TestApplication>().inject(this) } private fun logMultipleEvents() { analyticsController.logImportantEvent( 1556094120000, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) analyticsController.logLowPriorityEvent( 1556094110000, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) analyticsController.logImportantEvent( 1556093100000, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) analyticsController.logImportantEvent( 1556094100000, oppiaLogger.createOpenQuestionPlayerContext( TEST_QUESTION_ID, listOf( TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID ) ) ) } // TODO(#89): Move this to a common test application component. @Module class TestModule { @Provides @Singleton fun provideContext(application: Application): Context { return application } // TODO(#59): Either isolate these to their own shared test module, or use the real logging // module in tests to avoid needing to specify these settings for tests. @EnableConsoleLog @Provides fun provideEnableConsoleLog(): Boolean = true @EnableFileLog @Provides fun provideEnableFileLog(): Boolean = false @GlobalLogLevel @Provides fun provideGlobalLogLevel(): LogLevel = LogLevel.VERBOSE } @Module class TestLogStorageModule { @Provides @EventLogStorageCacheSize fun provideEventLogStorageCacheSize(): Int = 2 } // TODO(#89): Move this to a common test application component. @Singleton @Component( modules = [ TestModule::class, TestLogReportingModule::class, RobolectricModule::class, TestDispatcherModule::class, TestLogStorageModule::class, NetworkConnectionUtilDebugModule::class, LocaleProdModule::class, FakeOppiaClockModule::class, PlatformParameterModule::class, PlatformParameterSingletonModule::class, LoggingIdentifierModule::class, SyncStatusTestModule::class ] ) interface TestApplicationComponent : DataProvidersInjector { @Component.Builder interface Builder { @BindsInstance fun setApplication(application: Application): Builder fun build(): TestApplicationComponent } fun inject(analyticsControllerTest: AnalyticsControllerTest) } class TestApplication : Application(), DataProvidersInjectorProvider { private val component: TestApplicationComponent by lazy { DaggerAnalyticsControllerTest_TestApplicationComponent.builder() .setApplication(this) .build() } fun inject(analyticsControllerTest: AnalyticsControllerTest) { component.inject(analyticsControllerTest) } override fun getDataProvidersInjector(): DataProvidersInjector = component } }
588
Kotlin
398
223
2f4714c2ea59077cee71930433ab47a91fcc726e
22,221
oppia-android
Apache License 2.0
app/src/main/java/com/erenpapakci/usgchallenge/data/remote/model/Stats.kt
erenpapakci
301,750,932
false
null
package com.erenpapakci.usgchallenge.data.remote.model class Stats { }
0
Kotlin
0
4
9e31731028ef7bbbad4903fb4f8332e5de977ee6
72
UsgChallenge
The Unlicense
src/main/kotlin/com/imoonday/skill/FireballSkill.kt
iMoonDay
759,188,611
false
{"Kotlin": 472390, "Java": 57363}
package com.imoonday.skill import com.imoonday.util.SkillType import com.imoonday.util.UseResult import net.minecraft.entity.projectile.FireballEntity import net.minecraft.server.network.ServerPlayerEntity import net.minecraft.sound.SoundEvents class FireballSkill : Skill( id = "fireball", types = listOf(SkillType.DESTRUCTION), cooldown = 5, rarity = Rarity.SUPERB, sound = SoundEvents.ENTITY_ENDER_DRAGON_SHOOT ) { override fun use(user: ServerPlayerEntity): UseResult { user.run { val rotation = rotationVector.normalize().multiply(1.5) world.spawnEntity( FireballEntity( world, this, rotation.x, rotation.y, rotation.z, 1 ).apply { setPosition(x + rotation.x, eyeY, z + rotation.z) } ) } return UseResult.success() } }
0
Kotlin
0
0
092d28a9c2f8a80e1742c81ccecf55ff77c880d5
1,002
AdvancedSkills
Creative Commons Zero v1.0 Universal
ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinUrlUtils.kt
danbrough
527,165,659
true
{"Kotlin": 5808536, "Python": 948, "JavaScript": 775, "HTML": 317, "Mustache": 77}
/* * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.darwin.internal.legacy import io.ktor.http.* import io.ktor.util.* import platform.Foundation.* internal fun Url.toNSUrl(): NSURL { val userEncoded = encodedUser.orEmpty().isEncoded(NSCharacterSet.URLUserAllowedCharacterSet) val passwordEncoded = encodedPassword.orEmpty().isEncoded(NSCharacterSet.URLUserAllowedCharacterSet) val hostEncoded = host.isEncoded(NSCharacterSet.URLHostAllowedCharacterSet) val pathEncoded = encodedPath.isEncoded(NSCharacterSet.URLPathAllowedCharacterSet) val queryEncoded = encodedQuery.isEncoded(NSCharacterSet.URLQueryAllowedCharacterSet) val fragmentEncoded = encodedFragment.isEncoded(NSCharacterSet.URLFragmentAllowedCharacterSet) if (userEncoded && passwordEncoded && hostEncoded && pathEncoded && queryEncoded && fragmentEncoded) { return NSURL(string = toString()) } val components = NSURLComponents() components.scheme = protocol.name components.percentEncodedUser = when { userEncoded -> encodedUser else -> user?.sanitize(NSCharacterSet.URLUserAllowedCharacterSet) } components.percentEncodedPassword = when { passwordEncoded -> encodedPassword else -> password?.sanitize(NSCharacterSet.URLUserAllowedCharacterSet) } components.percentEncodedHost = when { hostEncoded -> host else -> host.sanitize(NSCharacterSet.URLHostAllowedCharacterSet) } if (port != DEFAULT_PORT && port != protocol.defaultPort) { components.port = NSNumber(int = port) } components.percentEncodedPath = when { pathEncoded -> encodedPath else -> pathSegments.joinToString("/").sanitize(NSCharacterSet.URLPathAllowedCharacterSet) } when { encodedQuery.isEmpty() -> components.percentEncodedQuery = null queryEncoded -> components.percentEncodedQuery = encodedQuery else -> components.percentEncodedQueryItems = parameters.toMap() .flatMap { (key, value) -> if (value.isEmpty()) listOf(key to null) else value.map { key to it } } .map { NSURLQueryItem(it.first.encodeQueryKey(), it.second?.encodeQueryValue()) } } components.percentEncodedFragment = when { encodedFragment.isEmpty() -> null fragmentEncoded -> encodedFragment else -> fragment.sanitize(NSCharacterSet.URLFragmentAllowedCharacterSet) } return components.URL ?: error("Invalid url: $this") } private fun String.sanitize(allowed: NSCharacterSet): String = asNSString().stringByAddingPercentEncodingWithAllowedCharacters(allowed)!! private fun String.encodeQueryKey(): String = encodeQueryValue().replace("=", "%3D") private fun String.encodeQueryValue(): String = asNSString().stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet)!! .replace("&", "%26") .replace(";", "%3B") private fun String.isEncoded(allowed: NSCharacterSet) = all { it == '%' || allowed.characterIsMember(it.code.toUShort()) } @Suppress("CAST_NEVER_SUCCEEDS") private fun String.asNSString(): NSString = this as NSString
5
null
1051
2
f6f34582a36ee2f950ea672c4908498680cc24b2
3,264
ktor
Apache License 2.0
project-course/kotlin-problems/NumberOfDigits/src/kiz/learnwithvel/numberofdigits/NumberOfDigits.kt
vel02
261,988,454
false
null
package kiz.learnwithvel.numberofdigits fun main(args: Array<String>) { var input = 12345 var count = 0 while (input != 0) { count++ input /= 10 } println(count) }
1
null
1
1
7644d1911ff35fda44e45b1486bcce5d790fe7c0
203
learn-kotlin-android
MIT License
site/src/jsMain/kotlin/com/prashant/blog/widgets/PostComment.kt
prashant17d97
707,855,780
false
{"Kotlin": 283326, "JavaScript": 795, "Swift": 592, "Shell": 228}
package com.prashant.blog.widgets import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import com.prashant.blog.widgets.ButtonsWidgets.CapsuleButton import com.prashant.blog.widgets.ButtonsWidgets.OutlinedButton import com.prashant.blog.utils.constants.Constants import com.prashant.blog.utils.constants.Constants.borderRadiusMedium import com.prashant.blog.utils.constants.ResourceConstants.CSSIds.cssCardId import com.prashant.theme.MaterialTheme import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.backgroundColor import com.varabyte.kobweb.compose.ui.modifiers.borderRadius import com.varabyte.kobweb.compose.ui.modifiers.boxShadow import com.varabyte.kobweb.compose.ui.modifiers.classNames import com.varabyte.kobweb.compose.ui.modifiers.color import com.varabyte.kobweb.compose.ui.modifiers.fillMaxWidth import com.varabyte.kobweb.compose.ui.modifiers.gap import com.varabyte.kobweb.compose.ui.modifiers.margin import com.varabyte.kobweb.compose.ui.modifiers.padding import com.varabyte.kobweb.compose.ui.modifiers.width import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.silk.components.text.SpanText import org.jetbrains.compose.web.attributes.InputType import org.jetbrains.compose.web.css.percent import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.dom.H4 import org.jetbrains.compose.web.dom.Input import org.jetbrains.compose.web.dom.TextArea @Composable fun PostComment( heading: String = "Leave a comment", isReply: Boolean = false, isUserLoggedIn: Boolean = false, padding: Int = 0, isBreakpoint: Boolean = false, onClick: (comment: String, name: String, email: String) -> Unit ) { var comments by remember { mutableStateOf("") } var name by remember { mutableStateOf("") } var email by remember { mutableStateOf("") } val modifier = if (isBreakpoint) { Modifier.width(97.percent).margin( top = 60.px, leftRight = 10.px, bottom = 20.px ) } else { Modifier.width(60.percent).margin( top = 60.px ) } Box( modifier = modifier .backgroundColor(MaterialTheme.colorScheme.container) .classNames(cssCardId) .boxShadow( blurRadius = 10.px, color = MaterialTheme.colorScheme.unspecified.copyf(alpha = 0.5f) ).borderRadius(Constants.borderRadiusLarge).padding(padding.px) .padding(topBottom = 40.px, leftRight = 60.px), contentAlignment = Alignment.Center ) { Column( modifier = Modifier.gap(10.px).fillMaxWidth() ) { H4( attrs = Modifier.color(MaterialTheme.colorScheme.onContainer).toAttrs() ) { SpanText(heading) } TextArea(value = comments, attrs = Modifier.fillMaxWidth().borderRadius(borderRadiusMedium).padding(20.px) .classNames("comment").toAttrs { value(comments.trim()) onInput { comments = it.value.trim() } attr("placeholder", "Comments") }) if (!isUserLoggedIn) { Input(InputType.Text, attrs = Modifier.fillMaxWidth().borderRadius(borderRadiusMedium) .padding(20.px).classNames("name").toAttrs { value(name) onInput { name = it.value.trim() } attr("placeholder", "Name") }) Input(InputType.Email, attrs = Modifier.fillMaxWidth().borderRadius(borderRadiusMedium) .padding(20.px).classNames("email").toAttrs { value(email) onInput { email = it.value.trim() } attr("placeholder", "Email") }) } if (!isReply) { CapsuleButton(modifier = Modifier.backgroundColor(MaterialTheme.colorScheme.action), onClick = { onClick(comments.trim(), name.trim(), email.trim()) comments = "" name = "" email = "" }) { SpanText("Post comment") } } else { OutlinedButton(outlinedColor = MaterialTheme.colorScheme.onContainer, selectedOutlineColor = MaterialTheme.colorScheme.action, height = 35.px, onClick = { onClick(comments.trim(), name.trim(), email.trim()) comments = "" name = "" email = "" }) { SpanText("Reply") } } } } }
0
Kotlin
0
0
b11ba5b7334ae07fc928c2f59c6137ee3524ab7f
5,459
Blog
Apache License 2.0
src/main/kotlin/pounces/komrade/api/data/ChatAction.kt
RepoForks
115,181,391
true
{"Kotlin": 31385, "Java": 6851}
package pounces.komrade.api.data object ChatAction { const val TYPING = "typing" const val UPLOAD_PHOTO = "upload_photo" const val RECORD_VIDEO = "record_video" const val UPLOAD_VIDEO = "upload_video" const val RECORD_AUDIO = "record_audio" const val UPLOAD_AUDIO = "upload_audio" const val UPLOAD_DOCUMENT = "upload_document" const val FIND_LOCATION = "find_location" }
0
Kotlin
0
0
bb310a19742b132c678491f4eb06c1e94ed012fe
403
komrade
MIT License
app/src/test/java/org/n27/nutshell/presentation/topics/TopicsUiTest.kt
Narsuf
843,534,148
false
{"Kotlin": 104589}
package org.n27.nutshell.presentation.topics import org.junit.Test import org.n27.nutshell.presentation.topics.composables.TopicsContentScreenPreview import org.n27.nutshell.presentation.topics.composables.TopicsContentScrollableScreenPreview import org.n27.nutshell.presentation.topics.composables.TopicsErrorScreenPreview import org.n27.nutshell.presentation.topics.composables.TopicsLoadingScreenPreview import org.n27.nutshell.screenshot.PaparazziScreenTest import org.n27.nutshell.screenshot.TestConfig class TopicsUiTest(config: TestConfig) : PaparazziScreenTest(config) { @Test fun topicsContentScreenPreviewTest() { screenshotTest { TopicsContentScreenPreview() } } @Test fun topicsContentScrollableScreenPreviewTest() { screenshotTest { TopicsContentScrollableScreenPreview() } } @Test fun topicsErrorScreenPreviewTest() { screenshotTest { TopicsErrorScreenPreview() } } @Test fun topicsLoadingScreenPreviewTest() { screenshotTest { TopicsLoadingScreenPreview() } } }
0
Kotlin
0
0
956c4f789015dbe3068afa31ab86fc7d363ac657
1,063
Nutshell
Apache License 2.0
screen/folders/src/main/kotlin/ru/maksonic/beresta/screen/folders/ui/Content.kt
maksonic
580,058,579
false
{"Kotlin": 1619980}
package ru.maksonic.beresta.screen.folders.ui import androidx.activity.compose.BackHandler import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.SheetState import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import ru.maksonic.beresta.common.ui_kit.animation.AnimateFadeInOut import ru.maksonic.beresta.common.ui_kit.icons.AppIcon import ru.maksonic.beresta.common.ui_kit.icons.Wallpaper import ru.maksonic.beresta.common.ui_kit.placeholder.PlaceholderEmptyState import ru.maksonic.beresta.common.ui_kit.sheet.ModalBottomSheetContainer import ru.maksonic.beresta.common.ui_theme.Theme import ru.maksonic.beresta.common.ui_theme.colors.background import ru.maksonic.beresta.common.ui_theme.provide.dp16 import ru.maksonic.beresta.common.ui_theme.provide.dp6 import ru.maksonic.beresta.common.ui_theme.provide.dp8 import ru.maksonic.beresta.feature.folders_list.ui.api.FoldersListUiApi import ru.maksonic.beresta.feature.hidden_notes_dialog.ui.api.HiddenNotesDialogUiApi import ru.maksonic.beresta.feature.sorting_sheet.ui.api.SortingSheetUiApi import ru.maksonic.beresta.feature.ui.add_folder_dialog.api.AddFolderDialogUiApi import ru.maksonic.beresta.language_engine.shell.provider.text import ru.maksonic.beresta.screen.folders.core.Model import ru.maksonic.beresta.screen.folders.core.Msg import ru.maksonic.beresta.screen.folders.ui.widget.BottomBar import ru.maksonic.beresta.screen.folders.ui.widget.MultipleModalBottomSheetContent import ru.maksonic.beresta.screen.folders.ui.widget.TopBar /** * @Author maksonic on 09.10.2023 */ @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun Content( model: Model, send: Send, addFolderDialogApi: AddFolderDialogUiApi, foldersListApi: FoldersListUiApi, hiddenNotesPinInputDialogUiApi: HiddenNotesDialogUiApi.PinInputDialog, sortingSheetApi: SortingSheetUiApi, modalBottomSheetState: SheetState, modifier: Modifier = Modifier ) { val sorter = rememberFoldersSorter(model.folders.collection) val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState()) val barHeight = Theme.size.bottomMainBarHeight val paddingFoldersBottom = animateDpAsState( if (model.folders.isSelection) barHeight.plus(dp6) else barHeight, tween(Theme.animVelocity.common), label = "" ) BackHandler(model.folders.isSelection) { send(Msg.Ui.CancelSelectionState) } Box(modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) { Scaffold( topBar = { TopBar(model, send, scrollBehavior) }, containerColor = background, modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection) ) { paddings -> Box(modifier.padding(paddings)) { foldersListApi.List( state = model.folders, sorter = sorter, onFolderClicked = { send(Msg.Ui.OnFolderClicked(it)) }, onFolderLongClicked = { send(Msg.Ui.OnFolderLongClicked(it)) }, onErrorRetryClicked = { send(Msg.Ui.OnRetryFetchDataClicked) }, onToHiddenNotesClicked = { send(Msg.Inner.UpdatedHiddenNotesDialogVisibility(true)) }, isTrashPlacement = false, modifier = modifier, contentPadding = PaddingValues( top = dp16, start = dp16, end = dp16, bottom = paddingFoldersBottom.value ), loadingModifier = Modifier.padding(top = dp8), emptyListPlaceholder = { PlaceholderEmptyState( imageVector = AppIcon.Wallpaper, message = text.shared.hintNoFolders ) } ) } } AnimateFadeInOut(model.folders.state.successAfterLoading) { BottomBar(model, send) } if (model.modalSheet.isVisible) { ModalBottomSheetContainer( sheetState = modalBottomSheetState, onDismissRequest = { send(Msg.Inner.HiddenModalBottomSheet) }, ) { MultipleModalBottomSheetContent(model, sortingSheetApi) } } addFolderDialogApi.Widget( isVisible = model.isVisibleEditFolderDialog, hideDialog = { send(Msg.Ui.OnCloseEditFolderDialogClicked) } ) hiddenNotesPinInputDialogUiApi.Widget( isVisible = model.isVisibleHiddenNotesDialog, onSuccessPin = { send(Msg.Inner.NavigatedToHiddenNotes) }, hideDialog = { send(Msg.Inner.UpdatedHiddenNotesDialogVisibility(false)) }, isBlocked = false, onBlockedBackPressed = {} ) } }
0
Kotlin
0
0
d9a53cc50c6e149923fc5bc6fc2c38013bfadb9d
5,557
Beresta
MIT License
app/src/androidTest/java/com/test/util/TestUtils.kt
ETSEmpiricalStudyKotlinAndroidApps
496,716,943
true
{"Kotlin": 111686, "Java": 1387}
package com.test.util import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.ViewAction import androidx.test.espresso.util.HumanReadables import androidx.test.espresso.PerformException import androidx.annotation.IdRes import java.lang.IllegalStateException import android.view.View import androidx.test.espresso.UiController import org.hamcrest.Matcher import org.hamcrest.Matchers object TestUtils { fun <VH : RecyclerView.ViewHolder?> actionOnItemViewAtPosition( position: Int, @IdRes viewId: Int, viewAction: ViewAction ): ViewAction { return ActionOnItemViewAtPositionViewAction<RecyclerView.ViewHolder?>(position, viewId, viewAction) } fun withRecyclerView(recyclerViewId: Int): RecyclerViewMatcher { return RecyclerViewMatcher(recyclerViewId) } private class ActionOnItemViewAtPositionViewAction<VH : RecyclerView.ViewHolder?>( private val position: Int, @param:IdRes private val viewId: Int, private val viewAction: ViewAction ) : ViewAction { override fun getConstraints(): Matcher<View>{ return Matchers.allOf( ViewMatchers.isAssignableFrom(RecyclerView::class.java), ViewMatchers.isDisplayed() ) } override fun getDescription(): String { return ("actionOnItemAtPosition performing ViewAction: " + viewAction.description + " on item at position: " + position) } override fun perform(uiController: UiController, view: View) { val recyclerView = view as RecyclerView ScrollToPositionViewAction(position).perform(uiController, view) uiController.loopMainThreadUntilIdle() val targetView: View = recyclerView.getChildAt(position).findViewById(viewId) if (targetView == null) { throw PerformException.Builder().withActionDescription(this.toString()) .withViewDescription( HumanReadables.describe(view) ) .withCause( IllegalStateException( "No view with id " + viewId + " found at position: " + position ) ) .build() } else { viewAction.perform(uiController, targetView) } } } private class ScrollToPositionViewAction(private val position: Int) : ViewAction { override fun getConstraints(): Matcher<View> { return Matchers.allOf( ViewMatchers.isAssignableFrom(RecyclerView::class.java), ViewMatchers.isDisplayed() ) } override fun getDescription(): String { return "scroll RecyclerView to position: " + position } override fun perform(uiController: UiController?, view: View) { val recyclerView = view as RecyclerView recyclerView.scrollToPosition(position) } } }
0
null
0
0
4a06616b14298e4003fb0ed15b012f2f1b4cd19b
3,300
RoomPaging3TestProject
Apache License 2.0
waypoints-api/src/main/kotlin/de/md5lukas/waypoints/api/WaypointsPlayer.kt
Sytm
211,378,928
false
{"Gradle Kotlin DSL": 11, "Markdown": 16, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Kotlin": 179, "Java": 3, "YAML": 12, "TOML": 1, "INI": 1, "XML": 14}
package de.md5lukas.waypoints.api import java.time.OffsetDateTime import java.util.* import org.bukkit.Location /** * The WaypointsPlayer is an extensions of the WaypointHolder that allows processing player-specific * data */ interface WaypointsPlayer : WaypointHolder { /** The UUID of the player this profile belongs to */ val id: UUID /** Whether the player wants to see global waypoints in the GUI */ val showGlobals: Boolean @JvmSynthetic suspend fun setShowGlobals(showGlobals: Boolean) fun setShowGlobalsCF(showGlobals: Boolean) = future { setShowGlobals(showGlobals) } /** The method to sort the items in GUI with */ val sortBy: OverviewSort @JvmSynthetic suspend fun setSortBy(sortBy: OverviewSort) fun setSortByCF(sortBy: OverviewSort) = future { setSortBy(sortBy) } /** Whether the player wants to be trackable with player-tracking or not. */ val canBeTracked: Boolean @JvmSynthetic suspend fun setCanBeTracked(canBeTracked: Boolean) fun setCanBeTrackedCF(canBeTracked: Boolean) = future { setCanBeTracked(canBeTracked) } /** Whether the player can receive temporary waypoints from other players or not */ val canReceiveTemporaryWaypoints: Boolean @JvmSynthetic suspend fun setCanReceiveTemporaryWaypoints(canReceiveTemporaryWaypoints: Boolean) fun setCanReceiveTemporaryWaypointsCF(canReceiveTemporaryWaypoints: Boolean) = future { setCanReceiveTemporaryWaypoints(canReceiveTemporaryWaypoints) } val enabledPointers: Map<String, Boolean> @JvmSynthetic suspend fun setEnabledPointers(enabledPointers: Map<String, Boolean>) fun setEnabledPointersCF(enabledPointers: Map<String, Boolean>) = future { setEnabledPointers(enabledPointers) } fun isPointerEnabled(key: String) = enabledPointers.getOrDefault(key, true) @JvmSynthetic suspend fun setPointerEnabled(key: String, value: Boolean) { setEnabledPointers(enabledPointers.toMutableMap().also { it[key] = value }) } fun setPointerEnabledCF(key: String, value: Boolean) = future { setPointerEnabled(key, value) } /** * Get the point in time at which a cooldown for teleporting has expired if present. * * @param type The type the cooldown is valid for * @return The time the cooldown expires or null */ @JvmSynthetic suspend fun getCooldownUntil(type: Type): OffsetDateTime? fun getCooldownUntilCF(type: Type) = future { getCooldownUntil(type) } /** * Set a new cooldown for the player and the time at which it expires. * * @param type The type the cooldown is valid for * @param cooldownUntil The point in time at which the cooldown should expire */ @JvmSynthetic suspend fun setCooldownUntil(type: Type, cooldownUntil: OffsetDateTime) fun setCooldownUntilCF(type: Type, cooldownUntil: OffsetDateTime) = future { setCooldownUntil(type, cooldownUntil) } /** * Get the amount of teleportations this player has performed to the given waypoint type * * @param type The type the counter is applicable to * @return The amount of teleportations */ @JvmSynthetic suspend fun getTeleportations(type: Type): Int fun getTeleporationsCF(type: Type) = future { getTeleportations(type) } /** * Update the amount of teleportations the player has performed to the given waypoint type * * @param type The type the counter is applicable to * @param teleportations The new amount of teleportations */ @JvmSynthetic suspend fun setTeleportations(type: Type, teleportations: Int) fun setTeleportationsCF(type: Type, teleportations: Int) = future { setTeleportations(type, teleportations) } /** Adds a new location to the death history of the player. */ @JvmSynthetic suspend fun addDeathLocation(location: Location) fun addDeathLocationCF(location: Location) = future { addDeathLocation(location) } /** * Abstract folder representing the saved death history of the player. The only way to add * waypoints to it is by calling [addDeathLocation]. * * The returned folder implementation behaves differently compared to a normal implementation. * - [Folder.id] is the id of the player * - [Folder.createdAt] is always at Epoch in the System-Timezone * - [Folder.name] cannot be changed * - [Folder.description] cannot be changed * - [Folder.icon] cannot be changed * - [Folder.delete] cannot be called */ val deathFolder: Folder /** All the concurrent Waypoints the player has selected */ @JvmSynthetic suspend fun getSelectedWaypoints(): List<Waypoint> fun getSelectedWaypointsCF() = future { getSelectedWaypoints() } @JvmSynthetic suspend fun setSelectedWaypoints(selected: List<Waypoint>) fun setSelectedWaypointsCF(selected: List<Waypoint>) = future { setSelectedWaypoints(selected) } /** * The compass target the player currently has before it got overwritten by the compass pointer */ @JvmSynthetic suspend fun getCompassTarget(): Location? fun getCompassTargetCF() = future { getCompassTarget() } @JvmSynthetic suspend fun setCompassTarget(location: Location) fun setCompassTargetCF(location: Location) = future { setCompassTarget(location) } @JvmSynthetic suspend fun getSharingWaypoints(): List<WaypointShare> fun getSharingWaypointsCF() = future { getSharingWaypoints() } @JvmSynthetic suspend fun hasSharedWaypoints(): Boolean fun hasSharedWaypointsCF() = future { hasSharedWaypoints() } @JvmSynthetic suspend fun getSharedWaypoints(): List<WaypointShare> fun getSharedWaypointsCF() = future { getSharedWaypoints() } }
1
Kotlin
7
28
b31e54acb0cb8e93c9713492b1c1a0759f1045ed
5,559
waypoints
MIT License
app/src/main/java/us/carleton/onetouchhelp/data/Contacts.kt
DuyNguyenPhuong
603,655,814
false
null
package us.carleton.onetouchhelp.data class Contacts { companion object { val EmergencyNumber: HashMap<String, HashMap<String, String>> = hashMapOf( "DZ" to hashMapOf( "Police" to "18", "Fire" to "14", "Ambulance" to "14" ), "VN" to hashMapOf( "Police" to "113", "Fire" to "114", "Ambulance" to "115" ), "PG" to hashMapOf( "Police" to "112", "Fire" to "110", "Ambulance" to "111" ), "CN" to hashMapOf( "Police" to "110", "Fire" to "119", "Ambulance" to "120" ), "ES" to hashMapOf( "Police" to "112", "Fire" to "112", "Ambulance" to "112" ), "AU" to hashMapOf( "Police" to "000", "Fire" to "000", "Ambulance" to "000" ), "SG" to hashMapOf( "Police" to "999", "Fire" to "955", "Ambulance" to "955" ), "LK" to hashMapOf( "Police" to "119", "Fire" to "110", "Ambulance" to "110" ), "MV" to hashMapOf( "Police" to "119", "Fire" to "118", "Ambulance" to "102" ), "LA" to hashMapOf( "Police" to "191", "Fire" to "190", "Ambulance" to "195" ), "US" to hashMapOf( "Police" to "911", "Fire" to "911", "Ambulance" to "911" ), "DE" to hashMapOf( "Police" to "112", "Fire" to "112", "Ambulance" to "112" ), "GR" to hashMapOf( "Police" to "112", "Fire" to "112", "Ambulance" to "112" ), "HU" to hashMapOf( "Police" to "112", "Fire" to "112", "Ambulance" to "112" ) ) } }
0
Kotlin
0
3
f6e913d365cb85a27dbfc49aaba5af269aadc300
2,599
Emergency-Alert-Global-Version
MIT License
build-stats-module/src/main/kotlin/com/build/stats/vo/StartBuildRs.kt
SHvatov
571,232,915
false
{"Kotlin": 118267, "HTML": 50649, "Dockerfile": 1800, "Shell": 372, "CSS": 186}
package com.build.stats.vo import com.build.stats.model.Build import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty /** * VO object, which is used both to create a new [Build]. * [repoToken] is considered to be required, other elements are optional. * @author shvatov */ @JsonIgnoreProperties(ignoreUnknown = true) data class StartBuildRs @JsonCreator constructor( @JsonProperty("repoToken") val repoToken: String? = null, @JsonProperty("buildToken") val buildToken: String? = null, @JsonProperty("runId") val runId: String? = null, // GITHUB_RUN_ID ) { init { require(!repoToken.isNullOrBlank()) { "\"repoToken\" must be present in the request body" } require(!buildToken.isNullOrBlank()) { "\"buildToken\" must be present in the request body" } } }
0
Kotlin
0
0
49739408dbcabb0fc6e4b1d6bacbaa893b115068
945
build-stats
Apache License 2.0
src/main/kotlin/ui/viewModels/splitPane/FileTreeViewModel.kt
Daniel0110000
702,220,698
false
null
package ui.viewModels.splitPane import com.dr10.database.domain.repositories.AutocompleteSettingsRepository import com.dr10.editor.ui.tabs.TabModel import com.dr10.editor.ui.tabs.TabsState import dev.icerock.moko.mvvm.livedata.LiveData import dev.icerock.moko.mvvm.livedata.MutableLiveData import dev.icerock.moko.mvvm.viewmodel.ViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import ui.splitPane.fileTree.FileInfo import ui.splitPane.fileTree.FileObserver import java.io.File class FileTreeViewModel( private val repository: AutocompleteSettingsRepository, private val path: String, private val tabsState: TabsState ): ViewModel() { private val rootFile = FileInfo(File(path), 0, true) private val _listFiles: MutableLiveData<List<FileInfo>> = MutableLiveData(listOf(rootFile) + expandDirectory(rootFile)) val listFiles: LiveData<List<FileInfo>> = _listFiles private val scope = CoroutineScope(Dispatchers.IO) init { scope.launch { // Register callbacks for file changes using the [FileObserver] class FileObserver(path).registerCallbacksForChanges( // Callback when a new file or directory is created onCreate = { // Check if the [FileInfo] list already contains a directory with the same parent if(_listFiles.value.contains(FileInfo(File(it.parent), calculateRelativeDirectoryDepth(it.parent), true))){ // Add the created file to the list of FileInfo with appropriate depth _listFiles.value = _listFiles.value.plus(FileInfo(it, calculateRelativeDirectoryDepth(it.absolutePath), false)) } }, // Callback when a file or directory is deleted onDelete = { file -> val filePath = file.absolutePath // Remove the deleted file from the list of FileInfo and its subdirectories _listFiles.value = _listFiles.value.filter { it.file != file && it.file.absolutePath != filePath } // If the deleted file is open, its tab is closed tabsState.closeTab(TabModel(file.name, filePath)){ } if(file.extension == "asm" || file.extension == "s"){ // If the extension of the deleted file is 'asm' or 's', delete the selected autocomplete option from the database scope.launch { repository.deleteSelectedAutocompleteOption(asmFilePath = file.absolutePath) } } } ) } } /** * Toggles the expansion state of a directory or opens an ASM file in the editor tab * * @param item The FileInfo representing the directory or file to be opened or closed */ fun toggleDirectoryExpansion(item: FileInfo){ if(item.file.isDirectory){ val expandedFiles = expandDirectory(item) if(item.isExpanded){ // Close the directory by setting the [isExpanded] flag to false and removing its contents item.isExpanded = false val directoryPath = item.file.absolutePath _listFiles.value = _listFiles.value.filterNot { fileInfo -> fileInfo.file != item.file && fileInfo.file.absolutePath.startsWith(directoryPath) } } else { // Open the directory if it has contents and update the list of displayed files item.file.listFiles()?.let { if(it.isNotEmpty()) item.isExpanded = true } if(!_listFiles.value.containsAll(expandedFiles)) _listFiles.value += expandedFiles } } else{ // If it's an ASM file, open it in the editor tab using [tabsState.openTab] if(item.file.extension == "asm" || item.file.extension == "s") tabsState.openTab(item.file) } } /** * Expands a directory by creating a list of [FileInfo] objects fot its contents * * @param fileItem The [FileInfo] representing the directory to expand * @return A list of [FileInfo] objects for the contents of the directory */ private fun expandDirectory(fileItem: FileInfo): List<FileInfo> { val directoryContents = File(fileItem.file.absolutePath).listFiles() return directoryContents?.map { FileInfo(it, fileItem.depthLevel + 1, false) } ?: emptyList() } /** * Calculates the relative depth of a directory within a base path by comparing their common parts * * @param targetPath The target directory's path to calculate depth for * @return The depth of the target directory relative to the base path */ private fun calculateRelativeDirectoryDepth(targetPath: String): Int{ val basePathParts = path.split(File.separator) val targetPathParts = targetPath.split(File.separator) val commonParts = basePathParts.zip(targetPathParts).takeWhile { (a, b) -> a == b } return targetPathParts.size - commonParts.size } }
2
null
3
29
41b3661d6749b098966fe7beed5dd365cc31b462
5,175
DeepCodeStudio
Apache License 2.0
domain/src/main/java/com/beok/domain/di/NetworkModule.kt
BeokBeok
294,858,630
false
null
package com.beok.domain.di import com.beok.domain.BuildConfig import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import javax.inject.Singleton @Module @InstallIn(ApplicationComponent::class) class NetworkModule { @Provides @Singleton fun provideHttpLoggingInterceptor() = HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) { HttpLoggingInterceptor.Level.BODY } else { HttpLoggingInterceptor.Level.NONE } } @Provides @Singleton fun provideKotlinJsonAdapterFactory(): KotlinJsonAdapterFactory = KotlinJsonAdapterFactory() @Provides @Singleton fun provideMoshi(jsonAdapter: KotlinJsonAdapterFactory): Moshi = Moshi.Builder().add(jsonAdapter).build() @Provides @Singleton fun provideMoshiConverter(moshi: Moshi): MoshiConverterFactory = MoshiConverterFactory.create(moshi) @Provides @Singleton fun provideOkHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() @Provides @Singleton fun provideRetrofit(converterFactory: MoshiConverterFactory, client: OkHttpClient): Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(converterFactory) .client(client) .build() companion object { private const val BASE_URL = "http://192.168.127.12:11000/" } }
0
Kotlin
0
1
81f1d96ff8b95e5316b69c302838911cfa98d591
1,843
SnsImitate
MIT License
main/logbook/builtinscript/HougekiRow.kt
noratako5
60,863,062
true
{"XML": 14, "Text": 5, "Ant Build System": 1, "Markdown": 9, "Ignore List": 2, "Microsoft Visual Studio Solution": 1, "JSON": 8, "JavaScript": 36, "INI": 5, "Batchfile": 1, "Java": 231, "Kotlin": 48, "CSS": 1}
package logbook.builtinscript import com.google.gson.internal.LinkedTreeMap import logbook.dto.BattleExDto import logbook.dto.BattleAtackDto import logbook.internal.Item import logbook.scripting.BuiltinScriptFilter import logbook.util.GsonUtil import java.util.* fun HougekiRowHeader(): ArrayList<String> { val header = DamageDayNightRowHeader() header.add("戦闘種別") header.add("艦名1") header.add("艦名2") header.add("艦名3") header.add("艦名4") header.add("艦名5") header.add("艦名6") header.add("自艦隊") header.add("巡目") header.add("攻撃艦") header.add("砲撃種別") header.add("砲撃回数") header.add("表示装備1") header.add("表示装備2") header.add("表示装備3") header.add("クリティカル") header.add("ダメージ") header.add("かばう") val shipHeader = ShipRowHeader() val length = shipHeader.size for (i in 0..length - 1) { header.add(String.format("攻撃艦.%s", shipHeader[i])) } for (i in 0..length - 1) { header.add(String.format("防御艦.%s", shipHeader[i])) } header.add("艦隊種類") header.add("敵艦隊種類") return header } /** * attackListがnullのときは即returnする * 敵が連合のときisSecondフラグは無視される */ private fun HougekiRowBodyConstruct( arg:ScriptArg, attackList: List<BattleAtackDto>?, apiName:String, isSecond: Boolean, hougekiCount: String, startHP: ArrayList<IntArray>, body: ArrayList<ArrayList<String>> ) { if(attackList == null){ return } if(arg.battle.isEnemyCombined || arg.isSplitHp){ HougekiRowBodyConstructEC(arg = arg,attackList = attackList,apiName = apiName,hougekiCount = hougekiCount,startHP = startHP,body = body) return } val api_hougeki = arg.dayPhaseOrNull?.tree?.get(apiName) as? LinkedTreeMap<*,*> if(api_hougeki == null){ return } var prevHP = startHP val friendRows = if(isSecond) arg.combinedRows else arg.friendRows val enemyRows = arg.enemyRows val friendHPIndex = if(isSecond) HP_INDEX_FRIEND_COMBINED else HP_INDEX_FRIEND val enemyHPIndex = HP_INDEX_ENEMY val friendMaxHP = if(isSecond) arg.battle.maxFriendHpCombined else arg.battle.maxFriendHp val enemyMaxHP = arg.battle.maxEnemyHp val fleetName = if (arg.battle.isCombined.not()) {"通常艦隊"} else if (isSecond) {"連合第2艦隊"} else {"連合第1艦隊"} val hougekiHP = startHP.createAttackHP(attackList,arg.battle).first val api_at_list = GsonUtil.toIntArray(api_hougeki["api_at_list"]) val api_at_type = GsonUtil.toIntArray(api_hougeki["api_at_type"]) val api_df_list = GsonUtil.toIntArrayArray(api_hougeki["api_df_list"]) val api_si_list = GsonUtil.toIntArrayArray(api_hougeki["api_si_list"]) val api_cl_list = GsonUtil.toIntArrayArray(api_hougeki["api_cl_list"]) val api_damage = GsonUtil.toDoubleArrayArray(api_hougeki["api_damage"]) val dayPhaseRow = DamageDayRowBody(arg) for (i in 1..api_at_list.size - 1) { val at = api_at_list[i] val atType = api_at_type[i] val dfList = api_df_list[i] val siList = api_si_list[i] val clList = api_cl_list[i] val damageList = api_damage[i] val attackFleetName = if (at < 7) "自軍" else "敵軍" val itemName = arrayOf("","","") for (j in itemName.indices) { if (j < siList.size && siList[j] > 0) { itemName[j] = Item.get(siList[j]).name } } for (j in dfList.indices) { val at = NelsonTouchEffect(at,atType,j) val df = dfList[j] val damage = damageList[j].toInt() val kabau = damageList[j] - damage.toDouble() > 0.05 val cl = clList[j] val row = ArrayList<String>(dayPhaseRow) row.add("砲撃戦") for(k in 0..5) { if (at < 7) { //自軍 if (isSecond) { row.add(arg.battle.dockCombined?.ships?.tryGet(k)?.name ?: "") } else{ row.add(arg.battle.dock?.ships?.tryGet(k)?.name ?: "") } } else{ row.add(arg.battle.enemy?.tryGet(k)?.name?:"") } } row.add(fleetName) row.add(hougekiCount) row.add(attackFleetName) row.add(atType.toString()) row.add(j.toString()) row.add(itemName[0]) row.add(itemName[1]) row.add(itemName[2]) row.add(cl.toString()) row.add(damage.toString()) row.add(if (kabau) "1" else "0") if (at < 7) { row.addAll(friendRows[at-1].updateShipRowBody(prevHP[friendHPIndex][at-1],friendMaxHP[at-1])) } else { row.addAll(enemyRows[at-7].updateShipRowBody(prevHP[enemyHPIndex][at-7],enemyMaxHP[at-7])) } if (df < 7) { row.addAll(friendRows[df-1].updateShipRowBody(prevHP[friendHPIndex][df-1],friendMaxHP[df-1])) } else { row.addAll(enemyRows[df-7].updateShipRowBody(prevHP[enemyHPIndex][df-7],enemyMaxHP[df-7])) } row.add(arg.combinedFlagString) row.add(if (arg.battle.isEnemyCombined) "連合艦隊" else "通常艦隊") if (arg.filter.filterHougekiAttackDefence(arg.battle, at, df, isSecond) && arg.filter.filterOutput(row)) { body.add(row) } if (i-1 < hougekiHP.size && j < hougekiHP[i-1].size) { prevHP = hougekiHP[i-1][j] } } } } /** * 敵が連合の時用 勝手に分岐してこっちにくるので直接こっちを呼ぶ必要はない */ private fun HougekiRowBodyConstructEC( arg:ScriptArg, attackList: List<BattleAtackDto>?, apiName:String, hougekiCount: String, startHP: ArrayList<IntArray>, body: ArrayList<ArrayList<String>> ) { if(attackList == null){ return } val api_hougeki = arg.dayPhaseOrNull?.tree?.get(apiName) as? LinkedTreeMap<*,*> if(api_hougeki == null){ return } var prevHP = startHP val hougekiHP = startHP.createAttackHP(attackList,arg.battle).first val api_at_eflag = GsonUtil.toIntArray(api_hougeki["api_at_eflag"]) val api_at_list = GsonUtil.toIntArray(api_hougeki["api_at_list"]) val api_at_type = GsonUtil.toIntArray(api_hougeki["api_at_type"]) val api_df_list = GsonUtil.toIntArrayArray(api_hougeki["api_df_list"]) val api_si_list = GsonUtil.toIntArrayArray(api_hougeki["api_si_list"]) val api_cl_list = GsonUtil.toIntArrayArray(api_hougeki["api_cl_list"]) val api_damage = GsonUtil.toDoubleArrayArray(api_hougeki["api_damage"]) val dayPhaseRow = DamageDayRowBody(arg) if(arg.isSplitHp){ for (i in 0..api_at_list.size - 1) { val eflag = api_at_eflag[i] val at = api_at_list[i] val atType = api_at_type[i] val dfList = api_df_list[i] val siList = api_si_list[i] val clList = api_cl_list[i] val damageList = api_damage[i] val attackFleetName = if (eflag == 0) "自軍" else "敵軍" val itemName = arrayOf("", "", "") for (j in itemName.indices) { if (j < siList.size && siList[j] > 0) { itemName[j] = Item.get(siList[j]).name } } for (j in dfList.indices) { val at = NelsonTouchEffect(at,atType,j) val df = dfList[j] val damage = damageList[j].toInt() val kabau = damageList[j] - damage.toDouble() > 0.05 val cl = clList[j] val fleetName = if (arg.battle.isCombined.not()) { "通常艦隊" } else if ((eflag == 1 && df >= 6) || (eflag == 0 && at >= 6)) { "連合第2艦隊" } else { "連合第1艦隊" } val row = ArrayList<String>(dayPhaseRow) row.add("砲撃戦") for(k in 0..5) { if (eflag == 0 ) { //自軍 if (at < arg.battle.dock.ships.size) { row.add(arg.battle.dock?.ships?.tryGet(k)?.name ?: "") } else{ row.add(arg.battle.dockCombined?.ships?.tryGet(k)?.name ?: "") } } else{ if(at < 6) { row.add(arg.battle.enemy?.tryGet(k)?.name ?: "") } else{ row.add(arg.battle.enemyCombined?.tryGet(k)?.name ?: "") } } } row.add(fleetName) row.add(hougekiCount) row.add(attackFleetName) row.add(atType.toString()) row.add(j.toString()) row.add(itemName[0]) row.add(itemName[1]) row.add(itemName[2]) row.add(cl.toString()) row.add(damage.toString()) row.add(if (kabau) "1" else "0") if (eflag == 0) { if (at < arg.battle.dock.ships.size) { row.addAll(arg.friendRows[at].updateShipRowBody(prevHP[HP_INDEX_FRIEND][at], arg.battle.maxFriendHp[at])) } else { row.addAll(arg.combinedRows[at - 6].updateShipRowBody(prevHP[HP_INDEX_FRIEND_COMBINED][at - 6], arg.battle.maxFriendHpCombined.tryGet(at - 6)?:-1)) } if (df < 6) { row.addAll(arg.enemyRows[df].updateShipRowBody(prevHP[HP_INDEX_ENEMY][df], arg.battle.maxEnemyHp[df])) } else { row.addAll(arg.enemyCombinedRows[df - 6].updateShipRowBody(prevHP[HP_INDEX_ENEMY_COMBINED][df - 6], arg.battle.maxEnemyHpCombined.tryGet(df-6)?:-1)) } } else { if (at < 6) { row.addAll(arg.enemyRows[at].updateShipRowBody(prevHP[HP_INDEX_ENEMY][at], arg.battle.maxEnemyHp[at])) } else { row.addAll(arg.enemyCombinedRows[at - 6].updateShipRowBody(prevHP[HP_INDEX_ENEMY_COMBINED][at - 6], arg.battle.maxEnemyHpCombined?.tryGet(at-6)?:-1)) } if (df < arg.battle.dock.ships.size) { row.addAll(arg.friendRows[df].updateShipRowBody(prevHP[HP_INDEX_FRIEND][df], arg.battle.maxFriendHp[df])) } else { row.addAll(arg.combinedRows[df - 6].updateShipRowBody(prevHP[HP_INDEX_FRIEND_COMBINED][df - 6], arg.battle.maxFriendHpCombined?.tryGet(df-6)?:-1)) } } row.add(arg.combinedFlagString) row.add(if (arg.battle.isEnemyCombined) "連合艦隊" else "通常艦隊") if (arg.filter.filterHougekiAttackDefenceEC(arg.battle, at, df, eflag) && arg.filter.filterOutput(row)) { body.add(row) } if (i < hougekiHP.size && j < hougekiHP[i].size) { prevHP = hougekiHP[i][j] } } } } else { for (i in 1..api_at_list.size - 1) { val eflag = api_at_eflag[i] val at = api_at_list[i] val atType = api_at_type[i] val dfList = api_df_list[i] val siList = api_si_list[i] val clList = api_cl_list[i] val damageList = api_damage[i] val attackFleetName = if (eflag == 0) "自軍" else "敵軍" val itemName = arrayOf("", "", "") for (j in itemName.indices) { if (j < siList.size && siList[j] > 0) { itemName[j] = Item.get(siList[j]).name } } for (j in dfList.indices) { val at = NelsonTouchEffect(at,atType,j) val df = dfList[j] val damage = damageList[j].toInt() val kabau = damageList[j] - damage.toDouble() > 0.05 val cl = clList[j] val fleetName = if (arg.battle.isCombined.not()) { "通常艦隊" } else if ((eflag == 1 && df > 6) || (eflag == 0 && at > 6)) { "連合第2艦隊" } else { "連合第1艦隊" } val row = ArrayList<String>(dayPhaseRow) row.add("砲撃戦") for(k in 0..5) { if (eflag == 0 ) { //自軍 if (at < 7) { row.add(arg.battle.dock?.ships?.tryGet(k)?.name ?: "") } else{ row.add(arg.battle.dockCombined?.ships?.tryGet(k)?.name ?: "") } } else{ if(at < 7) { row.add(arg.battle.enemy?.tryGet(k)?.name ?: "") } else{ row.add(arg.battle.enemyCombined?.tryGet(k)?.name ?: "") } } } row.add(fleetName) row.add(hougekiCount) row.add(attackFleetName) row.add(atType.toString()) row.add(j.toString()) row.add(itemName[0]) row.add(itemName[1]) row.add(itemName[2]) row.add(cl.toString()) row.add(damage.toString()) row.add(if (kabau) "1" else "0") if (eflag == 0) { if (at < 7) { row.addAll(arg.friendRows[at - 1].updateShipRowBody(prevHP[HP_INDEX_FRIEND][at - 1], arg.battle.maxFriendHp[at - 1])) } else { row.addAll(arg.combinedRows[at - 7].updateShipRowBody(prevHP[HP_INDEX_FRIEND_COMBINED][at - 7], arg.battle.maxFriendHpCombined[at - 7])) } if (df < 7) { row.addAll(arg.enemyRows[df - 1].updateShipRowBody(prevHP[HP_INDEX_ENEMY][df - 1], arg.battle.maxEnemyHp[df - 1])) } else { row.addAll(arg.enemyCombinedRows[df - 7].updateShipRowBody(prevHP[HP_INDEX_ENEMY_COMBINED][df - 7], arg.battle.maxEnemyHpCombined[df - 7])) } } else { if (at < 7) { row.addAll(arg.enemyRows[at - 1].updateShipRowBody(prevHP[HP_INDEX_ENEMY][at - 1], arg.battle.maxEnemyHp[at - 1])) } else { row.addAll(arg.enemyCombinedRows[at - 7].updateShipRowBody(prevHP[HP_INDEX_ENEMY_COMBINED][at - 7], arg.battle.maxEnemyHpCombined[at - 7])) } if (df < 7) { row.addAll(arg.friendRows[df - 1].updateShipRowBody(prevHP[HP_INDEX_FRIEND][df - 1], arg.battle.maxFriendHp[df - 1])) } else { row.addAll(arg.combinedRows[df - 7].updateShipRowBody(prevHP[HP_INDEX_FRIEND_COMBINED][df - 7], arg.battle.maxFriendHpCombined[df - 7])) } } row.add(arg.combinedFlagString) row.add(if (arg.battle.isEnemyCombined) "連合艦隊" else "通常艦隊") if (arg.filter.filterHougekiAttackDefenceEC(arg.battle, at, df, eflag) && arg.filter.filterOutput(row)) { body.add(row) } if (i - 1 < hougekiHP.size && j < hougekiHP[i - 1].size) { prevHP = hougekiHP[i - 1][j] } } } } } fun HougekiRowBody(arg:ScriptArg): ArrayList<ArrayList<String>> { val body = ArrayList<ArrayList<String>>() arg.dayPhaseOrNull?.run { val phase = this HougekiRowBodyConstruct( arg = arg, attackList = phase.openingTaisen, apiName = "api_opening_taisen", hougekiCount = "先制対潜", isSecond = arg.battle.isCombined, startHP = arg.battleHP.dayPhase!!.openingTaisenStartHP, body = body ) HougekiRowBodyConstruct( arg = arg, attackList = phase.hougeki1, apiName = "api_hougeki1", hougekiCount = "1", isSecond = phase.kind.isHougeki1Second, startHP = arg.battleHP.dayPhase!!.hougeki1StartHP, body = body ) HougekiRowBodyConstruct( arg = arg, attackList = phase.hougeki2, apiName = "api_hougeki2", hougekiCount = if(phase.kind.isHougeki1Second == phase.kind.isHougeki2Second)"2" else "1", isSecond = phase.kind.isHougeki2Second, startHP = arg.battleHP.dayPhase!!.hougeki2StartHP, body = body ) HougekiRowBodyConstruct( arg = arg, attackList = phase.hougeki3, apiName = "api_hougeki3", hougekiCount = if(phase.kind.isHougeki1Second == phase.kind.isHougeki2Second && phase.kind.isHougeki1Second == phase.kind.isHougeki3Second)"3" else if(phase.kind.isHougeki1Second == phase.kind.isHougeki2Second) "1" else "2", isSecond = phase.kind.isHougeki3Second, startHP = arg.battleHP.dayPhase!!.hougeki3StartHP, body = body ) } return body }
0
Java
2
13
82350d0779bd5092ec07fa2e41d8455cf0ee055c
18,240
logbook
MIT License
app/src/main/java/com/videochat/domain/model/AgoraConfigDomainModel.kt
atakanozkan
850,938,910
false
{"Kotlin": 128837, "Java": 33555}
package com.videochat.domain.model data class AgoraConfigDomainModel ( val agoraAppId: String = "", val appCertificate: String = "", val chatAppKey: String = "", val chatClient: String = "", val chatClientToken: String = "", )
0
Kotlin
0
1
e3b19616d2d10d395d3ab78895ea1c2cc0ccad58
247
videochatapp
MIT License
shared/src/iosMain/kotlin/com.myapplication.common/view/ZoomControllerView.common.kt.kt
bytecode0
646,469,392
false
null
package com.myapplication.common.view import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.myapplication.common.domain.ScalableState @Composable actual fun ZoomControllerView(modifier: Modifier, scalableState: ScalableState) { }
0
Kotlin
0
0
79ae38ee8ffe25de3946deeeca617bc7523a9cc2
269
dogify
Apache License 2.0
app/src/main/java/com/example/mobiletest/utilities/singleevent/Event.kt
johnlaura
863,267,035
false
{"Kotlin": 18537}
package com.example.mobiletest.utilities.singleevent /** * MobileTest * Do one thing to change the world * create by johnlion at 2024/9/25 */ open class Event<out T>(private val content: T) { private var hasBeenHandled = false fun getContentIfNotHandled(): T? { return if (hasBeenHandled) { null } else { hasBeenHandled = true content } } }
0
Kotlin
0
0
60a6f1d67d2535762fa81c25d2dd08c6f02bc0cb
418
MobileTest
Apache License 2.0
idea/testData/quickfix/variables/changeMutability/valWithSetter.kt
JakeWharton
99,388,807
false
null
// "Make variable mutable" "true" class A() { val a: Int = 0 <caret>set(v: Int) {} }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
97
kotlin
Apache License 2.0
card/src/main/java/com/adyen/checkout/card/CardComponent.kt
rnerone1
329,187,693
true
{"Java Properties": 2, "Markdown": 6, "Gradle": 43, "Shell": 5, "EditorConfig": 1, "Batchfile": 1, "Text": 2, "Ignore List": 7, "INI": 22, "Proguard": 24, "Java": 241, "XML": 236, "Kotlin": 79, "JSON": 2, "CODEOWNERS": 1, "YAML": 4}
/* * Copyright (c) 2020 <NAME>. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by caiof on 17/12/2020. */ package com.adyen.checkout.card import androidx.lifecycle.viewModelScope import com.adyen.checkout.card.data.CardType import com.adyen.checkout.card.data.ExpiryDate import com.adyen.checkout.components.StoredPaymentComponentProvider import com.adyen.checkout.components.base.BasePaymentComponent import com.adyen.checkout.components.model.payments.request.CardPaymentMethod import com.adyen.checkout.components.model.payments.request.PaymentComponentData import com.adyen.checkout.components.util.PaymentMethodTypes import com.adyen.checkout.core.exception.ComponentException import com.adyen.checkout.core.log.LogUtil import com.adyen.checkout.core.log.Logger import com.adyen.checkout.cse.Card import com.adyen.checkout.cse.EncryptedCard import com.adyen.checkout.cse.EncryptionException import com.adyen.checkout.cse.Encryptor import kotlinx.coroutines.launch import java.util.ArrayList import java.util.Collections private val TAG = LogUtil.getTag() private val PAYMENT_METHOD_TYPES = arrayOf(PaymentMethodTypes.SCHEME) private const val BIN_VALUE_LENGTH = 6 class CardComponent private constructor( private val cardDelegate: CardDelegate, cardConfiguration: CardConfiguration ) : BasePaymentComponent<CardConfiguration, CardInputData, CardOutputData, CardComponentState>(cardDelegate, cardConfiguration) { var filteredSupportedCards: List<CardType> = emptyList() private set private var storedPaymentInputData: CardInputData? = null private var publicKey = "" init { viewModelScope.launch { publicKey = cardDelegate.fetchPublicKey() if (publicKey.isEmpty()) { notifyException(ComponentException("Unable to fetch publicKey.")) } } } constructor(storedCardDelegate: StoredCardDelegate, cardConfiguration: CardConfiguration) : this( storedCardDelegate as CardDelegate, cardConfiguration ) { storedPaymentInputData = storedCardDelegate.getStoredCardInputData() val cardType = storedCardDelegate.getCardType() if (cardType != null) { val storedCardType: MutableList<CardType> = ArrayList() storedCardType.add(cardType) filteredSupportedCards = Collections.unmodifiableList(storedCardType) } // TODO: 09/12/2020 move this logic to base component, maybe create the inputdata from the delegate? if (!requiresInput()) { inputDataChanged(CardInputData()) } } constructor(cardDelegate: NewCardDelegate, cardConfiguration: CardConfiguration) : this( cardDelegate as CardDelegate, cardConfiguration ) override fun requiresInput(): Boolean { return cardDelegate.requiresInput() } override fun getSupportedPaymentMethodTypes(): Array<String> { return PAYMENT_METHOD_TYPES } override fun onInputDataChanged(inputData: CardInputData): CardOutputData { Logger.v(TAG, "onInputDataChanged") if (!isStoredPaymentMethod()) { filteredSupportedCards = updateSupportedFilterCards(inputData.cardNumber) } val cardDelegate = mPaymentMethodDelegate as CardDelegate val firstCardType: CardType? = if (filteredSupportedCards.isNotEmpty()) filteredSupportedCards[0] else null return CardOutputData( cardDelegate.validateCardNumber(inputData.cardNumber), cardDelegate.validateExpiryDate(inputData.expiryDate), cardDelegate.validateSecurityCode(inputData.securityCode, firstCardType), cardDelegate.validateHolderName(inputData.holderName), inputData.isStorePaymentEnable, cardDelegate.isCvcHidden() ) } @Suppress("ReturnCount") override fun createComponentState(): CardComponentState { Logger.v(TAG, "createComponentState") val cardPaymentMethod = CardPaymentMethod() cardPaymentMethod.type = CardPaymentMethod.PAYMENT_METHOD_TYPE val card = Card.Builder() val outputData = outputData val paymentComponentData = PaymentComponentData<CardPaymentMethod>() val cardNumber = outputData!!.cardNumberField.value val firstCardType: CardType? = if (filteredSupportedCards.isNotEmpty()) filteredSupportedCards[0] else null val binValue: String = getBinValueFromCardNumber(cardNumber) // If data is not valid we just return empty object, encryption would fail and we don't pass unencrypted data. if (!outputData.isValid) { return CardComponentState(paymentComponentData, false, firstCardType, binValue) } val encryptedCard: EncryptedCard encryptedCard = try { if (!isStoredPaymentMethod()) { card.setNumber(outputData.cardNumberField.value) } if (!cardDelegate.isCvcHidden()) { card.setSecurityCode(outputData.securityCodeField.value) } val expiryDateResult = outputData.expiryDateField.value if (expiryDateResult.expiryYear != ExpiryDate.EMPTY_VALUE && expiryDateResult.expiryMonth != ExpiryDate.EMPTY_VALUE) { card.setExpiryDate(expiryDateResult.expiryMonth, expiryDateResult.expiryYear) } Encryptor.INSTANCE.encryptFields(card.build(), publicKey) } catch (e: EncryptionException) { notifyException(e) return CardComponentState(paymentComponentData, false, firstCardType, binValue) } if (!isStoredPaymentMethod()) { cardPaymentMethod.encryptedCardNumber = encryptedCard.encryptedNumber cardPaymentMethod.encryptedExpiryMonth = encryptedCard.encryptedExpiryMonth cardPaymentMethod.encryptedExpiryYear = encryptedCard.encryptedExpiryYear } else { cardPaymentMethod.storedPaymentMethodId = (mPaymentMethodDelegate as StoredCardDelegate).getId() } if (!cardDelegate.isCvcHidden()) { cardPaymentMethod.encryptedSecurityCode = encryptedCard.encryptedSecurityCode } if (cardDelegate.isHolderNameRequired()) { cardPaymentMethod.holderName = outputData.holderNameField.value } paymentComponentData.paymentMethod = cardPaymentMethod paymentComponentData.setStorePaymentMethod(outputData.isStoredPaymentMethodEnable) paymentComponentData.shopperReference = configuration.shopperReference return CardComponentState(paymentComponentData, outputData.isValid, firstCardType, binValue) } fun isStoredPaymentMethod(): Boolean { return cardDelegate is StoredCardDelegate } fun getStoredPaymentInputData(): CardInputData? { return storedPaymentInputData } fun isHolderNameRequire(): Boolean { return cardDelegate.isHolderNameRequired() } fun showStorePaymentField(): Boolean { return configuration.isShowStorePaymentFieldEnable } private fun updateSupportedFilterCards(cardNumber: String?): List<CardType> { Logger.d(TAG, "updateSupportedFilterCards") if (cardNumber.isNullOrEmpty()) { return emptyList() } val supportedCardTypes = configuration.supportedCardTypes val estimateCardTypes = CardType.estimate(cardNumber) val filteredCards: MutableList<CardType> = ArrayList() for (supportedCard in supportedCardTypes) { if (estimateCardTypes.contains(supportedCard)) { filteredCards.add(supportedCard) } } return Collections.unmodifiableList(filteredCards) } private fun getBinValueFromCardNumber(cardNumber: String): String { return if (cardNumber.length < BIN_VALUE_LENGTH) cardNumber else cardNumber.substring(0..BIN_VALUE_LENGTH) } companion object { @JvmStatic val PROVIDER: StoredPaymentComponentProvider<CardComponent, CardConfiguration> = CardComponentProvider() } }
0
null
0
0
b6069aa9df2fa2ab0e04d265dc6fa934b2d91222
8,189
adyen-android
MIT License
src/util/kotlin/org/platestack/util/ReflectionTarget.kt
PlateStack
91,766,401
false
null
/* * Copyright (C) 2017 <NAME> * * 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.platestack.util import kotlin.reflect.KClass /** * Indicates that the annotated element is used by reflection. * * Adjust your IDE to suppress unused warnings from elements which contains this annotation. * * @param value The classes which uses the annotated element * @param classNames Same as [value] but may be used when the class is not on classpath */ @MustBeDocumented @Retention(AnnotationRetention.BINARY) annotation class ReflectionTarget(vararg val value: KClass<*> = emptyArray(), val classNames: Array<String> = emptyArray())
1
Kotlin
1
3
e39e4f06b489a07677fff49553c02153f9af76f3
1,165
PlateAPI
Apache License 2.0
component-acgpicture/src/main/java/com/rabtman/acgpicture/mvp/model/entity/AcgPicture.kt
magic-coder
143,361,731
false
null
package com.rabtman.acgpicture.mvp.model.entity import com.fcannizzaro.jsoup.annotations.interfaces.Attr import com.fcannizzaro.jsoup.annotations.interfaces.Items import com.fcannizzaro.jsoup.annotations.interfaces.Selector import com.fcannizzaro.jsoup.annotations.interfaces.Text import com.google.gson.annotations.SerializedName /** * @author Rabtman * acg图数据类 */ /** * animate-picture页面信息 */ data class AnimatePicturePage( @SerializedName("posts_per_page") val postsPerPage: Int = 0, @SerializedName("response_posts_count") val responsePostsCount: Int = 0, @SerializedName("page_number") val pageNumber: Int = 0, @SerializedName("posts") val animatePictureItems: List<AnimatePictureItem>? = null, @SerializedName("posts_count") val postsCount: Int = 0, @SerializedName("max_pages") val maxPages: Int = 0 ) /** * animate-picture图片信息 */ data class AnimatePictureItem( @SerializedName("id") val id: Int = 0, @SerializedName("md5") val md5: String = "", @SerializedName("md5_pixels") val md5Pixels: String = "", @SerializedName("width") val width: Int = 0, @SerializedName("height") val height: Int = 0, @SerializedName("small_preview") val smallPreview: String = "", @SerializedName("medium_preview") val mediumPreview: String = "", @SerializedName("big_preview") val bigPreview: String = "", @SerializedName("pubtime") val pubtime: String = "", @SerializedName("score") val score: Int = 0, @SerializedName("score_number") val scoreNumber: Int = 0, @SerializedName("size") val size: Int = 0, @SerializedName("download_count") val downloadCount: Int = 0, @SerializedName("erotics") val erotics: Int = 0, @SerializedName("color") val color: List<Int>? = null, @SerializedName("ext") val ext: String = "", @SerializedName("status") val status: Int = 0 ) @Selector("main") class APicturePage { @Items var items: List<APictureItem>? = null private val pageCount: String? = null fun getPageCount(): Int { val count = pageCount!!.substring(pageCount.lastIndexOf("/") + 1) return try { Integer.parseInt(count) } catch (e: Exception) { e.printStackTrace() 1 } } } @Selector("div.grid-bor div div.pos-r.cart-list") class APictureItem { @Text("div h2 a") var title: String = "" @Attr(query = "div.thumb.pos-r div", attr = "style") var thumbUrl: String = "" get() = try { field.substring(field.lastIndexOf("(") + 1, field.lastIndexOf(".") + 4) } catch (e: Exception) { e.printStackTrace() "" } @Attr(query = "div h2 a", attr = "href") var contentLink: String = "" var count: String = "" }
1
null
1
1
d37bcfd8e1ec0e3b3598f196c068de09df5b8673
2,857
AcgClub
MIT License