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
modules/entities/sources-jvm/bson/RaptorEntitiesBsonComponent.kt
fluidsonic
246,018,343
false
null
package io.fluidsonic.raptor import kotlin.reflect.* internal class RaptorEntitiesBsonComponent internal constructor( private val bsonComponent: BsonRaptorComponent, ) : RaptorComponent.Default<RaptorEntitiesBsonComponent>() { private var idDefinitionsByDiscriminator: MutableMap<String, RaptorEntityId.Definition<*>> = hashMapOf() private var idDefinitionsByInstanceClass: MutableMap<KClass<out RaptorEntityId>, RaptorEntityId.Definition<*>> = hashMapOf() internal fun addIdDefinition(definition: RaptorEntityId.Definition<*>) { val discriminator = definition.idDescriptor.discriminator idDefinitionsByDiscriminator[discriminator]?.let { existingDefinition -> check(definition === existingDefinition) { "Cannot add multiple ID definitions with the same discriminator '$discriminator'.\n" + "First: $existingDefinition\n" + "Second: $definition" } return } val instanceClass = definition.idDescriptor.instanceClass idDefinitionsByInstanceClass[instanceClass]?.let { existingDefinition -> check(definition === existingDefinition) { "Cannot add multiple ID definitions for the same class '${instanceClass.qualifiedName}'.\n" + "First: $existingDefinition\n" + "Second: $definition" } return } idDefinitionsByDiscriminator[discriminator] = definition idDefinitionsByInstanceClass[instanceClass] = definition } override fun RaptorComponentConfigurationEndScope.onConfigurationEnded() { if (idDefinitionsByDiscriminator.isNotEmpty()) bsonComponent.definitions(RaptorTypedEntityId.bsonDefinition(idDefinitionsByDiscriminator.values)) } internal object Key : RaptorComponentKey<RaptorEntitiesBsonComponent> { override fun toString() = "entities" } } @RaptorDsl public fun RaptorComponentSet<BsonRaptorComponent>.definition( definition: RaptorEntityId.Definition<*>, priority: RaptorBsonDefinition.Priority = RaptorBsonDefinition.Priority.normal, ) { definitions(definition.bsonDefinition(), priority = priority) configure { componentRegistry.oneOrRegister(RaptorEntitiesBsonComponent.Key) { RaptorEntitiesBsonComponent(bsonComponent = this) }.addIdDefinition(definition) } }
0
Kotlin
1
3
47239ea4c2acb76e14b2125190ee76f253b60e4f
2,176
raptor
Apache License 2.0
backend/src/main/java/com/paligot/confily/backend/jobs/JobDb.kt
GerardPaligot
444,230,272
false
{"Kotlin": 897920, "Swift": 126158, "Shell": 1148, "Dockerfile": 576, "HTML": 338, "CSS": 102}
package org.gdglille.devfest.backend.jobs data class SalaryDb( val min: Int = 0, val max: Int = 0, val recurrence: String = "" ) data class JobDb( val id: String = "", val partnerId: String = "", val url: String = "", val title: String = "", val companyName: String = "", val location: String = "", val salary: SalaryDb? = null, val requirements: Double = 0.0, val propulsed: String = "", val publishDate: Long = 0L )
9
Kotlin
6
143
8c0985b73422d6b388012d79c7ab33c054dc55c1
472
Confily
Apache License 2.0
src/main/kotlin/kosi/unix_types/linux_types/Linux.kt
QazCetelic
384,973,530
false
null
package kosi.unix_types.linux_types import kosi.base_types.LinuxBased import java.io.File class Linux: LinuxBased() { val distro = Distro() class Distro { var name: String? = null var id: String? = null var version: String? = null var base: String? = null var site: String? = null init { try { File("/etc").listFiles()?.forEach { file -> if (file.name.endsWith("-release")) { val lines = file.readLines() val pairs = lines.map { line -> // 'NAME="ExampleName"' -> 'NAME' & '"ExampleName"' line.split("=").map { // '"ExampleName"' -> 'ExampleName' it.removeSurrounding("\"") } } for (pair in pairs) { when (pair[0]) { // Some entries do the same thing, I added both in case 1 is missing "NAME" -> name = pair[1] "VERSION" -> version = pair[1] "ID" -> id = pair[1].uppercase() "ID_LIKE" -> base = pair[1] "VERSION_ID" -> version = pair[1] "HOME_URL" -> site = pair[1] "DISTRIB_ID" -> id = pair[1].uppercase() "DISTRIB_RELEASE" -> version = pair[1] } } } } } catch (_: Exception) { // TODO add backup method } } override fun toString() = "(Name: $name, Version: $version)" } }
1
Kotlin
0
1
60699b21e1cdb8f0dafeb73cfaf4d49e4d2b4dc6
1,900
Kosi
MIT License
app/src/main/java/com/kirillemets/flashcards/domain/repository/DictionaryRepository.kt
KirillEmets
291,228,411
false
null
package com.kirillemets.flashcards.domain.repository import com.kirillemets.flashcards.domain.model.DictionaryEntry interface DictionaryRepository { suspend fun findWords(word: String): List<DictionaryEntry> }
3
Kotlin
0
1
c0df628b445e0d7ac9e8a9a989cc46d994c8e4b4
215
JpCards
MIT License
deferred-resources/src/androidTest/java/com/backbase/deferredresources/DeferredColorTest.kt
MarinKacaj
308,918,899
false
{"Gradle": 6, "Markdown": 5, "Java Properties": 2, "Shell": 2, "Text": 2, "Ignore List": 1, "Batchfile": 1, "YAML": 4, "INI": 2, "XML": 30, "Kotlin": 59, "Java": 6, "Proguard": 1}
package com.backbase.deferredresources import android.graphics.Color import com.backbase.deferredresources.test.R import com.google.common.truth.Truth.assertThat import org.junit.Test internal class DeferredColorTest { private val disabledState = intArrayOf(-android.R.attr.state_enabled) private val checkedState = intArrayOf(android.R.attr.state_enabled, android.R.attr.state_checked) private val defaultState = intArrayOf(android.R.attr.state_enabled, -android.R.attr.state_checked) //region Constant @Test fun constantResolve_withIntValue_returnsSameValue() { val deferred = DeferredColor.Constant(Color.MAGENTA) assertThat(deferred.resolve(context)).isEqualTo(Color.MAGENTA) } @Test fun constantResolve_withStringValue_returnsParsedValue() { val deferred = DeferredColor.Constant("#00FF00") assertThat(deferred.resolve(context)).isEqualTo(Color.GREEN) } @Test fun constantResolveToStateList_wrapsValue() { val deferred = DeferredColor.Constant(Color.MAGENTA) val resolved = deferred.resolveToStateList(context) assertThat(resolved.isStateful).isFalse() assertThat(resolved.getColorForState(disabledState, Color.BLACK)).isEqualTo(Color.MAGENTA) assertThat(resolved.getColorForState(defaultState, Color.BLACK)).isEqualTo(Color.MAGENTA) assertThat(resolved.defaultColor).isEqualTo(Color.MAGENTA) } //endregion //region Resource @Test fun resourceResolve_withStandardColor_resolvesColor() { val deferred = DeferredColor.Resource(R.color.blue) assertThat(deferred.resolve(context)).isEqualTo(Color.BLUE) } @Test fun resourceResolve_withSelectorColor_resolvesDefaultColor() { val deferred = DeferredColor.Resource(R.color.stateful_color_without_attr) assertThat(deferred.resolve(AppCompatContext())).isEqualTo(Color.parseColor("#aaaaaa")) } @Test fun resourceResolve_withSelectorColorWithAttribute_resolvesDefaultColor() { val deferred = DeferredColor.Resource(R.color.stateful_color_with_attr) assertThat(deferred.resolve(AppCompatContext())).isEqualTo(Color.parseColor("#987654")) } @Test fun resourceResolveToStateList_withStandardColor_resolvesStatelessList() { val deferred = DeferredColor.Resource(R.color.blue) val resolved = deferred.resolveToStateList(context) assertThat(resolved.isStateful).isFalse() assertThat(resolved.getColorForState(disabledState, Color.BLACK)).isEqualTo(Color.BLUE) assertThat(resolved.getColorForState(defaultState, Color.BLACK)).isEqualTo(Color.BLUE) assertThat(resolved.defaultColor).isEqualTo(Color.BLUE) } @Test fun resourceResolveToStateList_withSelectorColor_resolvesExpectedStateList() { val deferred = DeferredColor.Resource(R.color.stateful_color_without_attr) val resolved = deferred.resolveToStateList(context) assertThat(resolved.isStateful).isTrue() assertThat(resolved.getColorForState(disabledState, Color.BLACK)).isEqualTo(Color.parseColor("#dbdbdb")) assertThat(resolved.getColorForState(defaultState, Color.BLACK)).isEqualTo(Color.parseColor("#aaaaaa")) assertThat(resolved.defaultColor).isEqualTo(Color.parseColor("#aaaaaa")) } @Test fun resourceResolveToStateList_withSelectorColorWithAttribute_resolvesExpectedStateList() { val deferred = DeferredColor.Resource(R.color.stateful_color_with_attr) val resolved = deferred.resolveToStateList(AppCompatContext()) assertThat(resolved.isStateful).isTrue() assertThat(resolved.getColorForState(disabledState, Color.BLACK)).isEqualTo(Color.parseColor("#dbdbdb")) assertThat(resolved.getColorForState(checkedState, Color.BLACK)).isEqualTo(Color.parseColor("#aaaaaa")) assertThat(resolved.getColorForState(defaultState, Color.BLACK)).isEqualTo(Color.parseColor("#987654")) assertThat(resolved.defaultColor).isEqualTo(Color.parseColor("#987654")) } //endregion //region Attribute @Test fun attributeResolve_withStandardColor_resolvesColor() { val deferred = DeferredColor.Attribute(R.attr.colorPrimary) assertThat(deferred.resolve(AppCompatContext())).isEqualTo(Color.parseColor("#987654")) } @Test fun attributeResolve_withSelectorColor_resolvesDefaultColor() { val deferred = DeferredColor.Attribute(R.attr.subtitleTextColor) assertThat(deferred.resolve(AppCompatContext())).isEqualTo(Color.parseColor("#aaaaaa")) } @Test fun attributeResolve_withSelectorColorWithAttributeDefault_resolvesDefaultColor() { val deferred = DeferredColor.Attribute(R.attr.titleTextColor) assertThat(deferred.resolve(AppCompatContext())).isEqualTo(Color.parseColor("#987654")) } @Test(expected = IllegalArgumentException::class) fun attributeResolve_withUnknownAttribute_throwsException() { val deferred = DeferredColor.Attribute(R.attr.colorPrimary) // Default-theme context does not have <colorPrimary> attribute: deferred.resolve(context) } @Test(expected = IllegalArgumentException::class) fun attributeResolve_withWrongAttributeType_throwsException() { val deferred = DeferredColor.Attribute(R.attr.isLightTheme) deferred.resolve(AppCompatContext()) } @Test fun attributeResolveToStateList_withSelectorColor_resolvesExpectedStateList() { val deferred = DeferredColor.Attribute(R.attr.subtitleTextColor) val resolved = deferred.resolveToStateList(AppCompatContext()) assertThat(resolved.isStateful).isTrue() assertThat(resolved.getColorForState(disabledState, Color.BLACK)).isEqualTo(Color.parseColor("#dbdbdb")) assertThat(resolved.getColorForState(defaultState, Color.BLACK)).isEqualTo(Color.parseColor("#aaaaaa")) assertThat(resolved.defaultColor).isEqualTo(Color.parseColor("#aaaaaa")) } @Test fun attributeResolveToStateList_withSelectorColorWithAttribute_resolvesExpectedStateList() { val deferred = DeferredColor.Attribute(R.attr.titleTextColor) val resolved = deferred.resolveToStateList(AppCompatContext()) assertThat(resolved.isStateful).isTrue() assertThat(resolved.getColorForState(disabledState, Color.BLACK)).isEqualTo(Color.parseColor("#dbdbdb")) assertThat(resolved.getColorForState(checkedState, Color.BLACK)).isEqualTo(Color.parseColor("#aaaaaa")) assertThat(resolved.getColorForState(defaultState, Color.BLACK)).isEqualTo(Color.parseColor("#987654")) assertThat(resolved.defaultColor).isEqualTo(Color.parseColor("#987654")) } @Test fun attributeResolveToStateList_withStandardColor_resolvesExpectedStateList() { val deferred = DeferredColor.Attribute(R.attr.colorPrimary) val resolved = deferred.resolveToStateList(AppCompatContext()) assertThat(resolved.isStateful).isFalse() assertThat(resolved.getColorForState(disabledState, Color.BLACK)).isEqualTo(Color.parseColor("#987654")) assertThat(resolved.getColorForState(defaultState, Color.BLACK)).isEqualTo(Color.parseColor("#987654")) assertThat(resolved.defaultColor).isEqualTo(Color.parseColor("#987654")) } @Test(expected = IllegalArgumentException::class) fun attributeResolveToStateList_withUnknownAttribute_throwsException() { val deferred = DeferredColor.Attribute(R.attr.colorPrimary) // Default-theme context does not have <colorPrimary> attribute: deferred.resolveToStateList(context) } @Test(expected = IllegalArgumentException::class) fun attributeResolveToStateList_withWrongAttributeType_throwsException() { val deferred = DeferredColor.Attribute(R.attr.isLightTheme) deferred.resolveToStateList(AppCompatContext()) } //endregion }
1
null
1
1
33fa9ce7ab1bae32ae7d704e08aeb4268090e225
7,893
DeferredResources
Apache License 2.0
src/main/kotlin/util/converter/TypescriptClassConverter.kt
takaakit
164,598,033
false
null
package main.kotlin.util.converter // ˅ import com.change_vision.jude.api.inf.model.IClass import java.util.* import java.text.* // ˄ // Convert the TypeScript class type of the target class. class TypescriptClassConverter(targetClass: IClass) { // ˅ // ˄ enum class ClassKind(val value: String) { CLASS(""), ENUM("enum"); // ˅ // ˄ } private var targetClass: IClass = targetClass // ˅ // ˄ // Check whether it is the same as the argument class kind. fun isTypescriptClassKind(kinds: List<ClassKind>): Boolean { // ˅ // If the argument kinds dose not exist, return false kinds.forEach { if (it.value.isNotEmpty() && !targetClass.stereotypes.contains(it.value)) { return false } } // If kinds other than the argument kinds exist, return false ClassKind.values().subtract(kinds).forEach { if (it.value.isNotEmpty() && targetClass.stereotypes.contains(it.value)) { return false } } return true // ˄ } // Convert to the argument class kind. fun convertTypescriptClassKind(kinds: List<ClassKind>) { // ˅ // Remove the related stereotypes ClassKind.values().forEach { if (it.value.isNotEmpty() && targetClass.hasStereotype(it.value)) { targetClass.removeStereotype(it.value) } } // Set stereotypes kinds.forEach { if (it.value.isNotEmpty() && !targetClass.hasStereotype(it.value)) { targetClass.addStereotype(it.value) } } // ˄ } // ˅ // ˄ } // ˅ // ˄
0
Kotlin
0
6
ccef783fc643264da0ad4aa25f82c770d0b5edc9
1,865
helper-for-m-plus
Creative Commons Zero v1.0 Universal
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/messages/SetChatPhotoResponse.kt
alatushkin
156,866,851
false
null
package name.alatushkin.api.vk.generated.messages open class SetChatPhotoResponse( val messageId: Long? = null, val chat: Chat? = null )
2
Kotlin
3
10
123bd61b24be70f9bbf044328b98a3901523cb1b
146
kotlin-vk-api
MIT License
data/src/main/java/com/sample/player/data/mapper/video/RemoteVideoModelToEntityMapper.kt
ShivaniSoni22
391,935,457
false
null
package com.sample.player.data.mapper.video import com.sample.player.data.mapper.base.ModelMapper import com.sample.player.data.model.video.RemoteVideoModel import com.sample.player.domain.model.video.Video import javax.inject.Inject class RemoteVideoModelToEntityMapper @Inject constructor() : ModelMapper<RemoteVideoModel, Video> { override fun map(input: RemoteVideoModel): Video { return Video( input.id ?: -1, input.title ?: "", input.url ?: "" ) } }
0
Kotlin
0
0
77de8ad5e79ef532f46bc15eda22ef333878fdd1
518
CleanVideoPlayerSample
MIT License
app/src/main/java/com/drs/dseller/feature_account/presentation/AccountNavigation.kt
raaja-sn
704,140,729
false
{"Kotlin": 307720}
package com.drs.dseller.feature_account.presentation import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.composable import androidx.navigation.navigation fun NavGraphBuilder.Account(navHostController: NavHostController){ navigation( startDestination = DESTINATION_ACCOUNT, route = ROUTE_ACCOUNT ){ composable( route = DESTINATION_ACCOUNT ){ } composable( route = DESTINATION_USER_ORDERS ){ } } } fun NavHostController.toAccount(navHostController: NavHostController){ navHostController.navigate(DESTINATION_ACCOUNT) } fun NavHostController.toUserOrders(navHostController: NavHostController){ navHostController.navigate(DESTINATION_USER_ORDERS) } const val ROUTE_ACCOUNT = "account" const val DESTINATION_ACCOUNT = "user_profile" const val DESTINATION_USER_ORDERS = "user_orders"
0
Kotlin
0
0
2cab9113d3e0e92b0a3c97459b1b3fd4a6e84278
967
DSeller-Android
MIT License
ChatroomService/src/main/java/io/agora/chatroom/ChatroomUIKitClient.kt
apex-wang
728,010,838
false
{"Kotlin": 497622}
package io.agora.chatroom import android.content.Context import android.text.TextUtils import android.util.Log import com.hyphenate.chat.EMMessage import io.agora.chatroom.model.UIChatroomInfo import io.agora.chatroom.model.UIConstant import io.agora.chatroom.model.UserInfoProtocol import io.agora.chatroom.model.toUser import io.agora.chatroom.service.CallbackImpl import io.agora.chatroom.service.ChatClient import io.agora.chatroom.service.ChatConnectionListener import io.agora.chatroom.service.ChatCustomMessageBody import io.agora.chatroom.service.ChatError import io.agora.chatroom.service.ChatException import io.agora.chatroom.service.ChatLog import io.agora.chatroom.service.ChatMessage import io.agora.chatroom.service.ChatMessageListener import io.agora.chatroom.service.ChatMessageType import io.agora.chatroom.service.ChatOptions import io.agora.chatroom.service.ChatRoomChangeListener import io.agora.chatroom.service.ChatType import io.agora.chatroom.service.Chatroom import io.agora.chatroom.service.ChatroomChangeListener import io.agora.chatroom.service.ChatroomService import io.agora.chatroom.service.GiftEntityProtocol import io.agora.chatroom.service.GiftReceiveListener import io.agora.chatroom.service.GiftService import io.agora.chatroom.service.OnError import io.agora.chatroom.service.OnSuccess import io.agora.chatroom.service.OnValueSuccess import io.agora.chatroom.service.UserEntity import io.agora.chatroom.service.UserService import io.agora.chatroom.service.UserStateChangeListener import io.agora.chatroom.service.cache.UIChatroomCacheManager import io.agora.chatroom.service.serviceImpl.ChatroomServiceImpl import io.agora.chatroom.service.serviceImpl.GiftServiceImpl import io.agora.chatroom.service.serviceImpl.UserServiceImpl import io.agora.chatroom.service.transfer import io.agora.chatroom.utils.GsonTools import org.json.JSONObject class ChatroomUIKitClient { private var currentRoomContext:UIChatroomContext = UIChatroomContext() private var chatroomUser:UIChatroomUser = UIChatroomUser() private var eventListeners = mutableListOf<ChatroomChangeListener>() private var giftListeners = mutableListOf<GiftReceiveListener>() private var userStateChangeListeners = mutableListOf<UserStateChangeListener>() private val roomEventResultListener: MutableList<ChatroomResultListener> by lazy { mutableListOf() } private val cacheManager: UIChatroomCacheManager = UIChatroomCacheManager() private val messageListener by lazy { InnerChatMessageListener() } private val chatroomChangeListener by lazy { InnerChatroomChangeListener() } private val userStateChangeListener by lazy { InnerUserStateChangeListener() } private val userService: UserService by lazy { UserServiceImpl() } private val chatroomService: ChatroomService by lazy { ChatroomServiceImpl() } private var uiOptions: UiOptions = UiOptions() companion object { const val TAG = "ChatroomUIKitClient" private var shared: ChatroomUIKitClient? = null fun getInstance(): ChatroomUIKitClient { if (shared == null) { synchronized(ChatroomUIKitClient::class.java) { if (shared == null) { shared = ChatroomUIKitClient() } } } return shared!! } } /** * Init the chatroom ui kit */ fun setUp( applicationContext: Context, appKey:String, options: ChatroomUIKitOptions = ChatroomUIKitOptions(), ){ currentRoomContext.setRoomContext(applicationContext) uiOptions = options.uiOptions val chatOptions = ChatOptions() chatOptions.appKey = appKey chatOptions.autoLogin = options.chatOptions.autoLogin ChatClient.getInstance().init(applicationContext,chatOptions) ChatClient.getInstance().setDebugMode(options.chatOptions.enableDebug) cacheManager.init(applicationContext) registerConnectListener() } /** * Login the chat SDK * @param userId The user id * @param token The user token * @param onSuccess The callback to indicate the user login successfully * @param onError The callback to indicate the user login failed */ fun login(userId: String, token: String, onSuccess: OnSuccess, onError: OnError) { if (!ChatClient.getInstance().isSdkInited) { onError.invoke(ChatError.GENERAL_ERROR,"SDK not initialized") return } userService.login(userId, token, onSuccess, onError) } /** * Login the chat SDK * @param user The user info * @param token The user token * @param onSuccess The callback to indicate the user login successfully * @param onError The callback to indicate the user login failed */ fun login(user: UserInfoProtocol, token: String, onSuccess: OnSuccess, onError: OnError) { if (!ChatClient.getInstance().isSdkInited) { onError.invoke(ChatError.GENERAL_ERROR,"SDK not initialized") return } userService.login(user, token, onSuccess, onError) } /** * Logout the chat SDK * @param onSuccess The callback to indicate the user logout successfully * @param onError The callback to indicate the user logout failed */ fun logout(onSuccess: OnSuccess, onError: OnError) { if (!ChatClient.getInstance().isSdkInited) { onError.invoke(ChatError.GENERAL_ERROR,"SDK not initialized") return } ChatClient.getInstance().logout(false, CallbackImpl(onSuccess, onError)) } /** * Join a chatroom. * @param roomInfo The id of the chatroom info. * @param onSuccess The callback to indicate the user joined the chatroom successfully. * @param onError The callback to indicate the user failed to join the chatroom. */ fun joinChatroom(roomInfo:UIChatroomInfo, onSuccess: OnValueSuccess<Chatroom> = {}, onError: OnError = { _, _ ->}) { if (!ChatClient.getInstance().isSdkInited) { onError.invoke(ChatError.GENERAL_ERROR,"SDK not initialized") return } initRoom(roomInfo) roomInfo.roomOwner?.userId?.let { chatroomService.joinChatroom(roomInfo.roomId, it, onSuccess, onError) } } /** * Init the chatroom before joining it */ private fun initRoom(roomInfo:UIChatroomInfo){ Log.e(TAG, "initRoom owner: ${roomInfo.roomOwner}") currentRoomContext.setCurrentRoomInfo(roomInfo) registerMessageListener() registerChatroomChangeListener() } /** * Register a room result listener. */ @Synchronized fun registerRoomResultListener(listener: ChatroomResultListener){ if (!roomEventResultListener.contains(listener)) { roomEventResultListener.add(listener) } } /** * Unregister a room result listener. */ @Synchronized fun unregisterRoomResultListener(listener: ChatroomResultListener){ if (roomEventResultListener.contains(listener)) { roomEventResultListener.remove(listener) } } fun updateUserInfo(userEntity: UserInfoProtocol, onSuccess: OnSuccess, onError: OnError){ userService.updateUserInfo(userEntity,onSuccess,onError) } fun setCurrentTheme(isDark:Boolean){ cacheManager.setCurrentTheme(isDark) } fun getCurrentTheme():Boolean{ return cacheManager.getCurrentTheme() } fun getUseGiftsInMsg():Boolean{ return uiOptions.useGiftsInList } fun parseUserInfo(message: ChatMessage):UserInfoProtocol?{ if (message.ext().containsKey(UIConstant.CHATROOM_UIKIT_USER_INFO)) { val jsonObject = message.getStringAttribute(UIConstant.CHATROOM_UIKIT_USER_INFO) return GsonTools.toBean(jsonObject.toString(), UserInfoProtocol::class.java) } return null } @Synchronized internal fun callbackEvent(event: ChatroomResultEvent, errorCode: Int, errorMessage: String?) { if (roomEventResultListener.isEmpty()) { return } roomEventResultListener.iterator().forEach { listener -> listener.onEventResult(event, errorCode, errorMessage) } } fun getContext():UIChatroomContext{ return currentRoomContext } fun getChatroomUser():UIChatroomUser{ return chatroomUser } fun getCacheManager():UIChatroomCacheManager{ return cacheManager } fun checkJoinedMsg(msg:ChatMessage):Boolean{ val ext = msg.ext() return ext.containsKey(UIConstant.CHATROOM_UIKIT_USER_JOIN) } fun isCurrentRoomOwner(ownerId:String? = ""):Boolean{ return currentRoomContext.isCurrentOwner(ownerId) } /** * Check if the user has logged into the SDK before */ fun isLoginBefore():Boolean{ return ChatClient.getInstance().isSdkInited && ChatClient.getInstance().isLoggedInBefore } fun getTranslationLanguage():List<String>{ return uiOptions.targetLanguageList } fun getCurrentUser():UserEntity{ val currentUser = ChatClient.getInstance().currentUser return chatroomUser.getUserInfo(currentUser) } fun insertJoinedMessage(roomId:String,userId:String):ChatMessage{ val joinedUserInfo = chatroomUser.getUserInfo(userId) val joinedMessage:ChatMessage if (userId == getCurrentUser().userId){ joinedMessage = ChatMessage.createSendMessage(ChatMessageType.CUSTOM) joinedMessage.to = roomId }else{ joinedMessage = ChatMessage.createReceiveMessage(ChatMessageType.CUSTOM) joinedMessage.from = userId joinedMessage.to = roomId } val customMessageBody = ChatCustomMessageBody(UIConstant.CHATROOM_UIKIT_USER_JOIN) joinedMessage.addBody(customMessageBody) val jsonString = GsonTools.beanToString(joinedUserInfo) joinedMessage.setAttribute(UIConstant.CHATROOM_UIKIT_USER_INFO, jsonString?.let { JSONObject(it) }) return joinedMessage } fun sendJoinedMessage(){ val joinedUserInfo = getCurrentUser() val roomId = getContext().getCurrentRoomInfo().roomId val joinedMsg = ChatMessage.createSendMessage(ChatMessageType.CUSTOM) joinedMsg.to = roomId val customMessageBody = ChatCustomMessageBody(UIConstant.CHATROOM_UIKIT_USER_JOIN) joinedMsg.addBody(customMessageBody) val jsonString = GsonTools.beanToString(joinedUserInfo) joinedMsg.setAttribute(UIConstant.CHATROOM_UIKIT_USER_INFO, jsonString?.let { JSONObject(it) }) chatroomService.sendMessage( joinedMsg, onSuccess = {}, onError = {code, error -> ChatLog.e("sendJoinedMessage","sendJoinedMessage onError $code $error") }) } @Synchronized fun clear(){ eventListeners.clear() giftListeners.clear() } @Synchronized fun clearUserStateChangeListener(){ userStateChangeListeners.clear() } internal fun updateChatroomChangeListener(listener:MutableList<ChatroomChangeListener>){ this.eventListeners = listener } internal fun updateChatroomGiftListener(listener:MutableList<GiftReceiveListener>){ this.giftListeners = listener } internal fun updateChatroomUserStateChangeListener(listener:MutableList<UserStateChangeListener>){ this.userStateChangeListeners = listener } private fun registerMessageListener() { ChatClient.getInstance().chatManager().addMessageListener(messageListener) } private fun registerChatroomChangeListener() { ChatClient.getInstance().chatroomManager().addChatRoomChangeListener(chatroomChangeListener) } private fun registerConnectListener() { ChatClient.getInstance().addConnectionListener(userStateChangeListener) } private inner class InnerChatroomChangeListener: ChatRoomChangeListener { override fun onChatRoomDestroyed(roomId: String, roomName: String) { callbackEvent(ChatroomResultEvent.DESTROY_ROOM, ChatError.EM_NO_ERROR, "") clear() } override fun onMemberJoined(roomId: String?, participant: String?) {} override fun onMemberExited(roomId: String, roomName: String, participant: String) { try { for (listener in eventListeners.iterator()) { listener.onUserLeft(roomId,roomName) } } catch (e: Exception) { e.printStackTrace() } } override fun onRemovedFromChatRoom( reason: Int, roomId: String, roomName: String, participant: String ) { try { for (listener in eventListeners.iterator()) { listener.onUserBeKicked(roomId,roomName) } } catch (e: Exception) { e.printStackTrace() } } override fun onMuteListAdded( chatRoomId: String, mutes: MutableList<String>, expireTime: Long ) { try { for (listener in eventListeners.iterator()) { if (mutes.size > 0){ for (mute in mutes) { listener.onUserMuted(chatRoomId,mute) } } } } catch (e: Exception) { e.printStackTrace() } } override fun onMuteListRemoved(chatRoomId: String, mutes: MutableList<String>) { try { for (listener in eventListeners.iterator()) { if (mutes.size > 0){ for (mute in mutes) { listener.onUserUnmuted(chatRoomId,mute) } } } } catch (e: Exception) { e.printStackTrace() } } override fun onWhiteListAdded(chatRoomId: String?, whitelist: MutableList<String>?) {} override fun onWhiteListRemoved(chatRoomId: String?, whitelist: MutableList<String>?) {} override fun onAllMemberMuteStateChanged(chatRoomId: String?, isMuted: Boolean) {} override fun onAdminAdded(chatRoomId: String, admin: String) { try { for (listener in eventListeners.iterator()) { listener.onAdminAdded(chatRoomId,admin) } } catch (e: Exception) { e.printStackTrace() } } override fun onAdminRemoved(chatRoomId: String, admin: String) { try { for (listener in eventListeners.iterator()) { listener.onAdminRemoved(chatRoomId,admin) } } catch (e: Exception) { e.printStackTrace() } } override fun onOwnerChanged(chatRoomId: String?, newOwner: String?, oldOwner: String?) {} override fun onAnnouncementChanged(chatRoomId: String, announcement: String) { try { for (listener in eventListeners.iterator()) { listener.onAnnouncementUpdated(chatRoomId,announcement) } } catch (e: Exception) { e.printStackTrace() } } } private inner class InnerUserStateChangeListener: ChatConnectionListener { override fun onConnected() { try { for (listener in userStateChangeListeners.iterator()) { listener.onConnected() } } catch (e: Exception) { e.printStackTrace() } } override fun onDisconnected(errorCode: Int) { // Should listen onLogout in below cases: if (errorCode == ChatError.USER_LOGIN_ANOTHER_DEVICE || errorCode == ChatError.USER_REMOVED || errorCode == ChatError.USER_BIND_ANOTHER_DEVICE || errorCode == ChatError.USER_DEVICE_CHANGED || errorCode == ChatError.SERVER_SERVICE_RESTRICTED || errorCode == ChatError.USER_LOGIN_TOO_MANY_DEVICES || errorCode == ChatError.USER_KICKED_BY_CHANGE_PASSWORD || errorCode == ChatError.USER_KICKED_BY_OTHER_DEVICE || errorCode == ChatError.APP_ACTIVE_NUMBER_REACH_LIMITATION) { return } try { for (listener in userStateChangeListeners.iterator()) { listener.onDisconnected(errorCode) } } catch (e: Exception) { e.printStackTrace() } } override fun onTokenExpired() { try { for (listener in userStateChangeListeners.iterator()) { listener.onTokenExpired() } } catch (e: Exception) { e.printStackTrace() } } override fun onTokenWillExpire() { try { for (listener in userStateChangeListeners.iterator()) { listener.onTokenWillExpire() } } catch (e: Exception) { e.printStackTrace() } } override fun onLogout(errorCode: Int, info: String?) { try { for (listener in userStateChangeListeners.iterator()) { listener.onLogout(errorCode, info) } } catch (e: Exception) { e.printStackTrace() } } } private inner class InnerChatMessageListener: ChatMessageListener { override fun onMessageReceived(messages: MutableList<ChatMessage>?) { messages?.forEach { if (it.isBroadcast){ try { for (listener in eventListeners.iterator()) { listener.onBroadcastReceived(it) } } catch (e: Exception) { e.printStackTrace() } }else{ if (it.type == ChatMessageType.TXT) { try { for (listener in eventListeners.iterator()) { listener.onMessageReceived(it) } } catch (e: Exception) { e.printStackTrace() } } // Check if it is a custom message first if (it.type == ChatMessageType.CUSTOM) { val body = it.body as ChatCustomMessageBody val event = body.event() val msgType: UICustomMsgType? = getCustomMsgType(event) // Then exclude single chat if (it.chatType != ChatType.Chat){ val username: String = it.to // Check if it is the same chat room or group and event is not empty if (TextUtils.equals(username,currentRoomContext.getCurrentRoomInfo().roomId) && !TextUtils.isEmpty(event)) { when (msgType) { UICustomMsgType.CHATROOMUIKITUSERJOIN -> { try { for (listener in eventListeners.iterator()) { parseJoinedMsg(it)?.let { userInfo-> chatroomUser.setUserInfo(it.from,userInfo.toUser()) } Log.e("apex","CHATROOMUIKITUSERJOIN ${it.from}") listener.onUserJoined(it.conversationId(),it.from) } } catch (e: Exception) { e.printStackTrace() } } UICustomMsgType.CHATROOMUIKITGIFT -> { try { for (listener in giftListeners.iterator()) { val giftEntity = parseGiftMsg(it) listener.onGiftReceived( roomId = currentRoomContext.getCurrentRoomInfo().roomId, gift = giftEntity, message = it ) } } catch (e: Exception) { e.printStackTrace() } } else -> {} } } } } } } } override fun onMessageRecalled(messages: MutableList<EMMessage>?) { messages?.forEach { try { for (listener in eventListeners.iterator()) { listener.onRecallMessageReceived(it) } } catch (e: Exception) { e.printStackTrace() } } } private fun getCustomMsgType(event: String?): UICustomMsgType? { return if (TextUtils.isEmpty(event)) { null } else UICustomMsgType.fromName(event) } private fun parseGiftMsg(msg: ChatMessage): GiftEntityProtocol? { val userEntity = parseUserInfo(msg)?.toUser() userEntity?.let { chatroomUser.setUserInfo(msg.from, it) } if (msg.body is ChatCustomMessageBody){ val customBody = msg.body as ChatCustomMessageBody if (customBody.params.containsKey(UIConstant.CHATROOM_UIKIT_GIFT_INFO)){ val gift = customBody.params[UIConstant.CHATROOM_UIKIT_GIFT_INFO] val giftEntityProtocol = GsonTools.toBean(gift, GiftEntityProtocol::class.java) userEntity?.let { giftEntityProtocol?.sendUser = it.transfer() } return giftEntityProtocol } } return null } private fun parseJoinedMsg(msg: ChatMessage):UserInfoProtocol? { if (msg.ext().containsKey(UIConstant.CHATROOM_UIKIT_USER_INFO)){ return try { val jsonObject = msg.getStringAttribute(UIConstant.CHATROOM_UIKIT_USER_INFO) return GsonTools.toBean(jsonObject.toString(), UserInfoProtocol::class.java) }catch (e:ChatException){ null } } return null } } }
0
Kotlin
0
0
20b1ff03d06d87d44565e322ccf9abced24264c5
23,660
test
MIT License
app/src/main/java/com/senex/timetable/data/database/GroupDao.kt
Senex-x
458,101,117
false
{"Kotlin": 165234}
package com.senex.timetable.data.database import androidx.room.Dao import androidx.room.Query import com.senex.timetable.data.database.util.BaseDao import com.senex.timetable.data.entity.group.GroupEntity import kotlinx.coroutines.flow.Flow @Dao interface GroupDao: BaseDao<GroupEntity, GroupEntity> { @Query("SELECT * FROM groups WHERE id = :id") override fun get(id: Long): Flow<GroupEntity?> @Query("SELECT * FROM groups") override fun getAll(): Flow<List<GroupEntity>> @Query("DELETE FROM groups WHERE id = :id") override suspend fun deleteById(id: Long) @Query("DELETE FROM groups") override suspend fun deleteAll() }
1
Kotlin
1
7
d5ce2dbecaa8a8376de2c541ab18ab3901315c1a
659
itis-timetable
MIT License
app/src/main/java/com/withgoogle/experiments/unplugged/model/Account.kt
specialprojects-experiments
200,379,468
false
null
package com.withgoogle.experiments.unplugged.model data class Account(val accountName: String, val accountType: String) { override fun toString(): String { return accountName } }
10
Kotlin
22
188
5e9aba7d67711962f8139011ecde0139fa11ea64
195
paperphone
Apache License 2.0
documentrenderer/src/main/java/com/tanodxyz/documentrenderer/elements/SimpleTextElement.kt
tanoDxyz
556,710,302
false
null
package com.tanodxyz.documentrenderer.elements import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.graphics.Typeface import android.os.Build import android.text.Layout import android.text.Spannable import android.text.StaticLayout import android.text.TextDirectionHeuristic import android.text.TextDirectionHeuristics import android.text.TextPaint import android.text.TextUtils import android.util.SparseArray import android.view.View import android.widget.EditText import androidx.annotation.RequiresApi import androidx.core.text.toSpannable import com.tanodxyz.documentrenderer.R import com.tanodxyz.documentrenderer.events.LongPressEvent import com.tanodxyz.documentrenderer.getHeight import com.tanodxyz.documentrenderer.getWidth import com.tanodxyz.documentrenderer.misc.DialogHandle import com.tanodxyz.documentrenderer.page.DocumentPage import java.lang.reflect.Constructor import kotlin.math.roundToInt /** * [StaticLayout] based text rendering [PageElement]. */ open class SimpleTextElement(page: DocumentPage) : PageElement(page), PageElement.OnLongPressListener { private var editTextDialog: EditTextDialog? = null private var scaleLevelForWhichSizeMeasured = -1F protected var appliedLineBreaking = false protected lateinit var spannable: Spannable protected var textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { this.color = DEFAULT_TEXT_COLOR this.textSize = DEFAULT_TEXT_SIZE } protected var layout: StaticLayout? = null var textSizePixels: Float = textPaint.textSize var ellipseSize = TextUtils.TruncateAt.END var alignment = Layout.Alignment.ALIGN_NORMAL var textDirectionHeuristics: TextDirectionHeuristic = TextDirectionHeuristics.LTR var spacingmult = 1.0F var spacingAdd = 2.0F var textColor: Int = textPaint.color var includePadding = false var allowTextEditing = true override var movable = !allowTextEditing @RequiresApi(Build.VERSION_CODES.M) var lineBreakingStrategy = Layout.BREAK_STRATEGY_SIMPLE @RequiresApi(Build.VERSION_CODES.M) var hyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE @RequiresApi(Build.VERSION_CODES.P) var useLineSpacingFromFallbacks = false override var type = "TextElement" init { debug = false longPressListener = this } fun setText(text: Spannable) { this.spannable = text appliedLineBreaking = false layout = null page.redraw() } fun getText(): Spannable? { return if (this::spannable.isInitialized) { this.spannable } else { null } } override fun onLongPress( eventMarker: LongPressEvent?, pageElement: PageElement ) { if (allowTextEditing) { showTextEditDialog() } } fun setTypeFace(typeface: Typeface) { textPaint.typeface = typeface } override fun setContentBounds(bounds: RectF) { super.setContentBounds(bounds) layout = null // as bounds changed so text layout must be recreated. usePreCalculatedBounds = true } protected fun initTextLayout(args: SparseArray<Any>?) { if (shouldCalculate(args)) { textPaint.textSize = args.textSizeRelativeToSnap(textSizePixels) textPaint.color = textColor val boundsRelativeToPage = this.getContentBounds(args.shouldDrawSnapShot()) val width = boundsRelativeToPage.getWidth() val height = boundsRelativeToPage.getHeight() scaleLevelForWhichSizeMeasured = page.documentRenderView.getCurrentZoom() val maxLinesByInspection = getMaxLinesByInspection( makeStaticLayout(spannable, width.roundToInt(), Int.MAX_VALUE), height ) layout = makeStaticLayout(spannable, width.roundToInt(), maxLinesByInspection) } } private fun getMaxLinesByInspection(staticLayout: StaticLayout, maxHeight: Float): Int { var line = staticLayout.lineCount - 1 while (line >= 0 && staticLayout.getLineBottom(line) >= maxHeight) { line-- } return line + 1 } override fun draw(canvas: Canvas, args: SparseArray<Any>?) { super.draw(canvas, args) try { initTextLayout(args) canvas.apply { save() val leftAndTop = args.getLeftAndTop() translate(leftAndTop.x, leftAndTop.y) layout?.draw(this) restore() } } catch (ex: Exception) { ex.printStackTrace() } } override fun getContentHeight(args: SparseArray<Any>?): Float { if (desiredHeight > 0) { return super.getContentHeight(args) } return if (scaleLevelForWhichSizeMeasured != page.documentRenderView.getCurrentZoom()) { val pageHeight = page.pageBounds.getHeight() val width = getContentWidth(args).roundToInt() var calculatedHeight = makeStaticLayout( spannable, width, Int.MAX_VALUE ).height if (calculatedHeight >= pageHeight) { calculatedHeight = pageHeight.roundToInt() } calculatedHeight += (longestLineHeight(args)) actualHeight = calculatedHeight.toFloat() actualHeight } else { actualHeight } } override fun getContentWidth(args: SparseArray<Any>?): Float { if (desiredWidth > 0) { return super.getContentWidth(args) } return if (scaleLevelForWhichSizeMeasured != page.documentRenderView.getCurrentZoom()) { val pageWidth = page.pageBounds.getWidth() var calculatedWidth = (StaticLayout.getDesiredWidth(spannable, textPaint)).roundToInt() if (calculatedWidth >= pageWidth) { calculatedWidth = pageWidth.roundToInt() } actualWidth = (calculatedWidth.toFloat()) actualWidth } else { actualWidth } } protected fun makeStaticLayout( spannable: Spannable, width: Int, maxLines: Int ): StaticLayout { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val builder = StaticLayout.Builder.obtain(spannable, 0, spannable.length, textPaint, width) .setMaxLines(maxLines).setAlignment(alignment) .setEllipsize(ellipseSize) .setTextDirection(textDirectionHeuristics) .setLineSpacing(spacingAdd, spacingmult) .setIncludePad(includePadding) .setBreakStrategy(lineBreakingStrategy) .setHyphenationFrequency(hyphenationFrequency) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { builder.setUseLineSpacingFromFallbacks(useLineSpacingFromFallbacks) } builder.build() } else { val constructor: Constructor<StaticLayout> = StaticLayout::class.java.getConstructor( CharSequence::class.java, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, TextPaint::class.java, Int::class.javaPrimitiveType, Layout.Alignment::class.java, TextDirectionHeuristic::class.java, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Boolean::class.javaPrimitiveType, TextUtils.TruncateAt::class.java, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType ) constructor.isAccessible = true constructor.newInstance( spannable, 0, spannable.length, textPaint, width, alignment, textDirectionHeuristics, spacingmult, spacingAdd, includePadding, ellipseSize, width, maxLines ) } } fun longestLineHeight(args: SparseArray<Any>?): Int { val layout = makeStaticLayout(spannable, getContentWidth(args).roundToInt(), Int.MAX_VALUE) var longestLineHeight = 0 layout.apply { val lineCount: Int = lineCount for (i in 0 until lineCount) { val lineHeight: Int = getLineBottom(i) - getLineTop(i) if (lineHeight > longestLineHeight) { longestLineHeight = lineHeight } } } return longestLineHeight } open fun showTextEditDialog() { if (editTextDialog == null) { editTextDialog = EditTextDialog(page.documentRenderView.context, false) { changedText -> changedText?.let { setText(it) } } } editTextDialog?.setTextAndShow(spannable) } fun shouldCalculate(args: SparseArray<Any>?): Boolean { val drawSnapShot = args.shouldDrawSnapShot() val oldTextSize = textPaint.textSize val newTextSize = page.documentRenderView.toCurrentScale(textSizePixels) return (drawSnapShot || oldTextSize != newTextSize || layout == null) } inner class EditTextDialog( windowContext: Context, cancelOnTouchOutSide: Boolean = true, val textChangeCallback: (Spannable?) -> Unit ) : DialogHandle(windowContext, cancelOnTouchOutSide) { init { createDialog() setListeners() setOnShowListener { page.documentRenderView.canProcessTouchEvents = false } setOnDismissListener { page.documentRenderView.canProcessTouchEvents = true } } fun setListeners() { findViewViaId<View>(R.id.okButton)?.setOnClickListener { textChangeCallback(findViewViaId<EditText>(R.id.inputView)?.text?.toSpannable()) hide() } findViewViaId<View>(R.id.cancelButton)?.setOnClickListener { hide() } } fun setTextAndShow(spannable: Spannable) { findViewViaId<EditText>(R.id.inputView)?.setText(spannable) show() } override fun getContainerLayout(): Int { return R.layout.text_edit_dialog } } companion object { const val DEFAULT_TEXT_SIZE = 22F //px const val DEFAULT_TEXT_COLOR = Color.BLACK fun calculateTextHeight( simpleTextElement: SimpleTextElement, maxWidth: Int ): Int { val staticLayout = StaticLayout( simpleTextElement.spannable, simpleTextElement.textPaint, (maxWidth - if (simpleTextElement.symmetric) simpleTextElement.margins.left.times(2) else 0F).roundToInt(), simpleTextElement.alignment, simpleTextElement.spacingmult, simpleTextElement.spacingAdd, simpleTextElement.includePadding ) return staticLayout.height } } }
0
Kotlin
0
0
0eb8d1cdc45b222731261c1182364dee00a4f4e0
11,673
GeneralDocumentRenderer
Apache License 2.0
shared/src/iosMain/kotlin/core/datastore/DataStore.kt
prashant17d97
754,377,560
false
{"Kotlin": 326072, "Ruby": 2184, "Swift": 657, "Shell": 228}
package core.datastore import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import core.datastore.DataStoreObj.createDataStore import kotlinx.cinterop.ExperimentalForeignApi import platform.Foundation.NSDocumentDirectory import platform.Foundation.NSFileManager import platform.Foundation.NSURL import platform.Foundation.NSUserDomainMask /** * Creates a DataStore instance for managing preferences data on the iOS side. * @return A DataStore instance for managing preferences. * @OptIn Marks the function as experimental, allowing the use of foreign APIs. * @param producePath A lambda function that produces the path for storing the data store file. * * @author <NAME> */ @OptIn(ExperimentalForeignApi::class) fun dataStore(): DataStore<Preferences> = createDataStore( producePath = { // Produce the path for storing the data store file... val documentDirectory: NSURL? = NSFileManager.defaultManager.URLForDirectory( directory = NSDocumentDirectory, inDomain = NSUserDomainMask, appropriateForURL = null, create = false, error = null, ) requireNotNull(documentDirectory).path + "/${DataStoreObj.data_store_name}" }, )
1
Kotlin
0
0
d219d35d81823a049999285f57b5a8d6b1aff1bf
1,366
debug-desk
Apache License 2.0
app/src/main/java/org/ak80/skeleton/info/InfoFragment.kt
ak80
158,294,184
false
null
package org.ak80.skeleton.info import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import dagger.android.support.DaggerFragment import org.ak80.skeleton.R import org.ak80.skeleton.di.ActivityScoped import javax.inject.Inject /** * Display list of items */ @ActivityScoped class InfoFragment @Inject constructor() : DaggerFragment(), InfoContract.View { @Inject lateinit var presenter: InfoContract.Presenter private var infoView: TextView? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root = inflater!!.inflate(R.layout.info_frag, container, false) infoView = root.findViewById(R.id.info) presenter.takeView(this) return root } override fun onResume() { super.onResume() presenter.takeView(this) } override fun onDestroy() { presenter.dropView() super.onDestroy() } override fun setInfoText(id: Int) { infoView!!.text = getString(id) } }
0
Kotlin
0
1
ae3786a0031a5347c3e46f21f225de94718fd2c8
1,139
android-skeleton
Apache License 2.0
examples/sdk-app-example/app/src/main/java/com/example/bugsnag/android/MultiProcessActivity.kt
bugsnag
2,406,783
false
{"Kotlin": 1012357, "Java": 502120, "C": 461672, "Gherkin": 181499, "C++": 50967, "Ruby": 28576, "CMake": 5170, "Shell": 3373, "Makefile": 3254}
package com.example.bugsnag.android import android.os.Bundle import android.view.View class MultiProcessActivity : BaseCrashyActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) findViewById<View>(R.id.multi_process_title).visibility = View.VISIBLE } }
17
Kotlin
205
1,188
f5fd26b3cdeda9c4d4e221f55feb982a3fd97197
327
bugsnag-android
MIT License
app/src/main/java/com/babakbelur/studiary/core/data/remote/response/course/CourseItemResponse.kt
Babak-Belur
396,693,139
false
null
package com.babakbelur.studiary.core.data.remote.response.course import com.google.gson.annotations.SerializedName data class CourseItemResponse( @SerializedName("course_name") val courseName: String? = "", @SerializedName("description") val description: String? = "", @SerializedName("id_course") val idCourse: Int = 0 )
0
Kotlin
0
0
cc7d86e6fd132e24478a0abafb86258c7da087eb
349
android-app
Apache License 2.0
app/src/main/java/com/droidafricana/cleanarchitecturecrypto/di/CryptoApiModule.kt
Fbada006
289,015,235
false
null
package com.droidafricana.cleanarchitecturecrypto.di import com.droidafricana.data.api.CryptoApiService import com.droidafricana.data.api.HttpClient import com.droidafricana.data.api.LoggingInterceptor import com.droidafricana.data.api.MoshiCreator import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import com.squareup.moshi.Moshi 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.Named import javax.inject.Singleton @Module @InstallIn(ApplicationComponent::class) class CryptoApiModule { @Provides fun provideLoggingInterceptor() = LoggingInterceptor.create() @Provides fun provideOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor) = HttpClient.create(httpLoggingInterceptor) @Singleton @Provides fun provideCryptoApi(retrofit: Retrofit): CryptoApiService = retrofit.create(CryptoApiService::class.java) @Singleton @Provides fun provideMoshi(): Moshi = MoshiCreator.create() @Singleton @Provides fun provideRetrofit( okHttpClient: OkHttpClient, moshi: Moshi, @Named("baseUrl") baseUrl: String ): Retrofit { return Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() } @Provides @Named("baseUrl") fun provideBaseUrl(): String = "https://api.coingecko.com/api/v3/coins/" }
0
Kotlin
1
13
e5e0f9b2ae9bd4bf6adb052cd1dc4da88d1487e1
1,792
Clean_Architecture_Template_Crypto
Apache License 2.0
src/main/kotlin/org/jetbrains/webstorm/ide/WebAssemblyBraceMatcher.kt
pluralia
276,611,419
false
{"WebAssembly": 160485, "Kotlin": 60747, "Lex": 11525, "Java": 174}
package org.jetbrains.webstorm.ide import com.intellij.lang.BracePair import com.intellij.lang.PairedBraceMatcher import com.intellij.psi.PsiFile import com.intellij.psi.tree.IElementType import org.jetbrains.webstorm.lang.psi.* object WebAssemblyBraceMatcher : PairedBraceMatcher { override fun getPairs(): Array<BracePair> = arrayOf( BracePair(WebAssemblyTypes.LPAR, WebAssemblyTypes.RPAR, true)) override fun isPairedBracesAllowedBeforeType(lbraceType: IElementType, contextType: IElementType?): Boolean = true override fun getCodeConstructStart(file: PsiFile?, openingBraceOffset: Int): Int = openingBraceOffset }
4
WebAssembly
1
9
8d2fa2dd6c95e695b94f9884d7a9d6e49d6d8057
645
web-assembly-plugin
MIT License
app/src/main/java/com/setoh/slotsample/BadImplementationClass.kt
hiroyuki-seto
226,612,620
false
null
package com.setoh.slotsample import okhttp3.* class BadImplementationClass { companion object { fun fetchData(): String? { val body = FormBody.Builder() .add("key1", "value1") .build() val request = Request.Builder() .url("https://hoge.com/api/fugafuga") .header("header-name", "header-value") .post(body) .build() return OkHttpClientProvider.client .newCall(request) .execute() .body?.string() } } }
1
Kotlin
0
0
762411024b8b490807b1e0c2da4778a60fea969f
607
slot-sample
Apache License 2.0
modules/cli/src/test/kotlin/datamaintain/cli/app/PrintConfigTest.kt
4sh
207,514,876
false
null
package datamaintain.cli.app import ch.qos.logback.classic.Logger import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.slf4j.LoggerFactory import strikt.api.expectThat import strikt.assertions.isEqualTo import strikt.assertions.matches internal class PrintConfigTest : BaseCliTest() { private val logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as Logger private val testAppender = TestAppender() @BeforeEach fun setupLogger() { logger.addAppender(testAppender) testAppender.start() } @Test fun `should print config when command is mark-script-as-exectued`() { // Given val path = "/myPath" val markScriptAsExecutedArguments = listOf( "--path", path ) // When runAppWithMarkOneScriptAsExecuted( listOf( "--config", "--db-type", "mongo", "--db-uri", "mongo-uri" ), markScriptAsExecutedArguments ) // Then var index = 0 expectThat(testAppender.events) { get { get(index++).message }.isEqualTo("Configuration: ") get { get(index++).message }.matches("- working directory -> .*/datamaintain/modules/cli".toRegex()) get { get(index++).message }.isEqualTo("- path -> /myPath") get { get(index++).message }.isEqualTo("- identifier regex -> (.*)") get { get(index++).message }.isEqualTo("- create tags from folder -> false") get { get(index++).message }.isEqualTo("- tags -> []") get { get(index++).message }.isEqualTo("- whitelisted tags -> []") get { get(index++).message }.isEqualTo("- blacklisted tags -> []") get { get(index++).message }.isEqualTo("- tags to play again -> []") get { get(index++).message }.isEqualTo("- rules -> []") get { get(index++).message }.isEqualTo("- execution mode -> NORMAL") get { get(index++).message }.isEqualTo("- allow override executed script -> false") get { get(index++).message }.isEqualTo("- script action -> MARK_AS_EXECUTED") get { get(index++).message }.isEqualTo("- flags -> []") get { get(index++).message }.isEqualTo("- verbose -> false") get { get(index++).message }.isEqualTo("- porcelain -> false") } } @Test fun `should print inherited config when command is mark-script-as-exectued`() { // Given val path = "/myPath" val markScriptAsExecutedArguments = listOf( "--path", path ) // When runAppWithMarkOneScriptAsExecuted( listOf( "--config", "--db-type", "mongo", "--db-uri", "mongo-uri", "--config-file-path", "src/test/resources/config-child.properties" ), markScriptAsExecutedArguments ) // Then var index = 0 expectThat(testAppender.events) { get { get(index++).message }.matches(("Load new config keys from parent config located" + " at .*/datamaintain/modules/cli/src/test/resources/config-parent\\.properties").toRegex()) get { get(index++).message }.isEqualTo("Configuration: ") get { get(index++).message }.matches("- working directory -> .*/datamaintain/modules/cli/src/test/resources".toRegex()) get { get(index++).message }.isEqualTo("- name -> childConfig") get { get(index++).message }.isEqualTo("- path -> /myPath") get { get(index++).message }.isEqualTo("- identifier regex -> (.*)") get { get(index++).message }.isEqualTo("- create tags from folder -> false") get { get(index++).message }.isEqualTo("- tags -> [TagMatcher(tag=Tag(name=MYTAG2), globPaths=[/pathMatcher2])]") get { get(index++).message }.isEqualTo("- whitelisted tags -> []") get { get(index++).message }.isEqualTo("- blacklisted tags -> []") get { get(index++).message }.isEqualTo("- tags to play again -> []") get { get(index++).message }.isEqualTo("- rules -> []") get { get(index++).message }.isEqualTo("- execution mode -> NORMAL") get { get(index++).message }.isEqualTo("- allow override executed script -> false") get { get(index++).message }.isEqualTo("- script action -> MARK_AS_EXECUTED") get { get(index++).message }.isEqualTo("- flags -> []") get { get(index++).message }.isEqualTo("- verbose -> false") get { get(index++).message }.isEqualTo("- porcelain -> false") } } @Test fun `should print config when command is update-db`() { // Given val path = "/myPath" val updateDbArguments = listOf( "--path", path, "--identifier-regex", "v.*_", "--execution-mode", "NORMAL", "--action", "RUN", "--tag", "MYTAG1=/pathMatcher1", "--tag", "MYTAG2=/pathMatcher2", "--blacklisted-tags", "MYTAG1", "--whitelisted-tags", "MYTAG2", "--verbose", "--porcelain" ) // When runAppWithUpdateDb( listOf( "--config", "--db-type", "mongo", "--db-uri", "mongo-uri" ), updateDbArguments ) // Then var index = 0 expectThat(testAppender.events) { get { get(index++).message }.isEqualTo("Configuration: ") get { get(index++).message }.matches("- working directory -> .*/datamaintain/modules/cli".toRegex()) get { get(index++).message }.isEqualTo("- path -> /myPath") get { get(index++).message }.isEqualTo("- identifier regex -> v.*_") get { get(index++).message }.isEqualTo("- create tags from folder -> false") get { get(index++).message }.isEqualTo("- tags -> [TagMatcher(tag=Tag(name=MYTAG2), globPaths=[/pathMatcher2]), TagMatcher(tag=Tag(name=MYTAG1), globPaths=[/pathMatcher1])]") get { get(index++).message }.isEqualTo("- whitelisted tags -> [Tag(name=MYTAG2)]") get { get(index++).message }.isEqualTo("- blacklisted tags -> [Tag(name=MYTAG1)]") get { get(index++).message }.isEqualTo("- tags to play again -> []") get { get(index++).message }.isEqualTo("- rules -> []") get { get(index++).message }.isEqualTo("- execution mode -> NORMAL") get { get(index++).message }.isEqualTo("- allow override executed script -> false") get { get(index++).message }.isEqualTo("- script action -> RUN") get { get(index++).message }.isEqualTo("- flags -> []") get { get(index++).message }.isEqualTo("- verbose -> true") get { get(index++).message }.isEqualTo("- porcelain -> true") } } @Test fun `should print inherited config when command is update-db`() { // Given val path = "/myPath" val updateDbArguments = listOf( "--path", path, "--identifier-regex", "v.*_", "--execution-mode", "DRY", "--action", "RUN", "--tag", "MYTAG1=/pathMatcher1", "--blacklisted-tags", "MYTAG1", "--whitelisted-tags", "MYTAG2", "--verbose", "--porcelain" ) // When runAppWithUpdateDb( listOf( "--config", "--db-type", "mongo", "--db-uri", "mongo-uri", "--config-file-path", "src/test/resources/config-child.properties" ), updateDbArguments ) // Then var index = 0 expectThat(testAppender.events) { get { get(index++).message }.matches(("Load new config keys from parent config located" + " at .*/datamaintain/modules/cli/src/test/resources/config-parent\\.properties").toRegex()) get { get(index++).message }.isEqualTo("Configuration: ") get { get(index++).message }.matches("- working directory -> .*/datamaintain/modules/cli/src/test/resources".toRegex()) get { get(index++).message }.isEqualTo("- name -> childConfig") get { get(index++).message }.isEqualTo("- path -> /myPath") get { get(index++).message }.isEqualTo("- identifier regex -> v.*_") get { get(index++).message }.isEqualTo("- create tags from folder -> false") get { get(index++).message }.isEqualTo("- tags -> [TagMatcher(tag=Tag(name=MYTAG2), globPaths=[/pathMatcher2]), TagMatcher(tag=Tag(name=MYTAG1), globPaths=[/pathMatcher1])]") get { get(index++).message }.isEqualTo("- whitelisted tags -> [Tag(name=MYTAG2)]") get { get(index++).message }.isEqualTo("- blacklisted tags -> [Tag(name=MYTAG1)]") get { get(index++).message }.isEqualTo("- tags to play again -> []") get { get(index++).message }.isEqualTo("- rules -> []") get { get(index++).message }.isEqualTo("- execution mode -> DRY") get { get(index++).message }.isEqualTo("- allow override executed script -> false") get { get(index++).message }.isEqualTo("- script action -> RUN") get { get(index++).message }.isEqualTo("- flags -> []") get { get(index++).message }.isEqualTo("- verbose -> true") get { get(index++).message }.isEqualTo("- porcelain -> true") } } }
34
null
6
26
0cb32924208b053b36cd49a892d6be5a603095fc
9,856
datamaintain
Apache License 2.0
emoji-google-compat/src/commonMain/kotlin/com/vanniktech/emoji/googlecompat/category/SymbolsCategoryChunk1.kt
vanniktech
53,511,222
false
null
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.googlecompat.category import com.vanniktech.emoji.googlecompat.GoogleCompatEmoji internal object SymbolsCategoryChunk1 { internal val EMOJIS: List<GoogleCompatEmoji> = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F4DB), 0, 1), listOf("name_badge"), false), GoogleCompatEmoji(String(intArrayOf(0x1F530), 0, 1), listOf("beginner"), false), GoogleCompatEmoji(String(intArrayOf(0x2B55), 0, 1), listOf("o"), false), GoogleCompatEmoji(String(intArrayOf(0x2705), 0, 1), listOf("white_check_mark"), false), GoogleCompatEmoji(String(intArrayOf(0x2611, 0xFE0F), 0, 2), listOf("ballot_box_with_check"), false), GoogleCompatEmoji(String(intArrayOf(0x2714, 0xFE0F), 0, 2), listOf("heavy_check_mark"), false), GoogleCompatEmoji(String(intArrayOf(0x274C), 0, 1), listOf("x"), false), GoogleCompatEmoji(String(intArrayOf(0x274E), 0, 1), listOf("negative_squared_cross_mark"), false), GoogleCompatEmoji(String(intArrayOf(0x27B0), 0, 1), listOf("curly_loop"), false), GoogleCompatEmoji(String(intArrayOf(0x27BF), 0, 1), listOf("loop"), false), GoogleCompatEmoji(String(intArrayOf(0x303D, 0xFE0F), 0, 2), listOf("part_alternation_mark"), false), GoogleCompatEmoji(String(intArrayOf(0x2733, 0xFE0F), 0, 2), listOf("eight_spoked_asterisk"), false), GoogleCompatEmoji(String(intArrayOf(0x2734, 0xFE0F), 0, 2), listOf("eight_pointed_black_star"), false), GoogleCompatEmoji(String(intArrayOf(0x2747, 0xFE0F), 0, 2), listOf("sparkle"), false), GoogleCompatEmoji(String(intArrayOf(0x00A9, 0xFE0F), 0, 2), listOf("copyright"), false), GoogleCompatEmoji(String(intArrayOf(0x00AE, 0xFE0F), 0, 2), listOf("registered"), false), GoogleCompatEmoji(String(intArrayOf(0x2122, 0xFE0F), 0, 2), listOf("tm"), false), GoogleCompatEmoji(String(intArrayOf(0x0023, 0xFE0F, 0x20E3), 0, 3), listOf("hash"), false), GoogleCompatEmoji(String(intArrayOf(0x002A, 0xFE0F, 0x20E3), 0, 3), listOf("keycap_star"), false), GoogleCompatEmoji(String(intArrayOf(0x0030, 0xFE0F, 0x20E3), 0, 3), listOf("zero"), false), GoogleCompatEmoji(String(intArrayOf(0x0031, 0xFE0F, 0x20E3), 0, 3), listOf("one"), false), GoogleCompatEmoji(String(intArrayOf(0x0032, 0xFE0F, 0x20E3), 0, 3), listOf("two"), false), GoogleCompatEmoji(String(intArrayOf(0x0033, 0xFE0F, 0x20E3), 0, 3), listOf("three"), false), GoogleCompatEmoji(String(intArrayOf(0x0034, 0xFE0F, 0x20E3), 0, 3), listOf("four"), false), GoogleCompatEmoji(String(intArrayOf(0x0035, 0xFE0F, 0x20E3), 0, 3), listOf("five"), false), GoogleCompatEmoji(String(intArrayOf(0x0036, 0xFE0F, 0x20E3), 0, 3), listOf("six"), false), GoogleCompatEmoji(String(intArrayOf(0x0037, 0xFE0F, 0x20E3), 0, 3), listOf("seven"), false), GoogleCompatEmoji(String(intArrayOf(0x0038, 0xFE0F, 0x20E3), 0, 3), listOf("eight"), false), GoogleCompatEmoji(String(intArrayOf(0x0039, 0xFE0F, 0x20E3), 0, 3), listOf("nine"), false), GoogleCompatEmoji(String(intArrayOf(0x1F51F), 0, 1), listOf("keycap_ten"), false), GoogleCompatEmoji(String(intArrayOf(0x1F520), 0, 1), listOf("capital_abcd"), false), GoogleCompatEmoji(String(intArrayOf(0x1F521), 0, 1), listOf("abcd"), false), GoogleCompatEmoji(String(intArrayOf(0x1F522), 0, 1), listOf("1234"), false), GoogleCompatEmoji(String(intArrayOf(0x1F523), 0, 1), listOf("symbols"), false), GoogleCompatEmoji(String(intArrayOf(0x1F524), 0, 1), listOf("abc"), false), GoogleCompatEmoji(String(intArrayOf(0x1F170, 0xFE0F), 0, 2), listOf("a"), false), GoogleCompatEmoji(String(intArrayOf(0x1F18E), 0, 1), listOf("ab"), false), GoogleCompatEmoji(String(intArrayOf(0x1F171, 0xFE0F), 0, 2), listOf("b"), false), GoogleCompatEmoji(String(intArrayOf(0x1F191), 0, 1), listOf("cl"), false), GoogleCompatEmoji(String(intArrayOf(0x1F192), 0, 1), listOf("cool"), false), GoogleCompatEmoji(String(intArrayOf(0x1F193), 0, 1), listOf("free"), false), GoogleCompatEmoji(String(intArrayOf(0x2139, 0xFE0F), 0, 2), listOf("information_source"), false), GoogleCompatEmoji(String(intArrayOf(0x1F194), 0, 1), listOf("id"), false), GoogleCompatEmoji(String(intArrayOf(0x24C2, 0xFE0F), 0, 2), listOf("m"), false), GoogleCompatEmoji(String(intArrayOf(0x1F195), 0, 1), listOf("new"), false), GoogleCompatEmoji(String(intArrayOf(0x1F196), 0, 1), listOf("ng"), false), GoogleCompatEmoji(String(intArrayOf(0x1F17E, 0xFE0F), 0, 2), listOf("o2"), false), GoogleCompatEmoji(String(intArrayOf(0x1F197), 0, 1), listOf("ok"), false), GoogleCompatEmoji(String(intArrayOf(0x1F17F, 0xFE0F), 0, 2), listOf("parking"), false), GoogleCompatEmoji(String(intArrayOf(0x1F198), 0, 1), listOf("sos"), false), GoogleCompatEmoji(String(intArrayOf(0x1F199), 0, 1), listOf("up"), false), GoogleCompatEmoji(String(intArrayOf(0x1F19A), 0, 1), listOf("vs"), false), GoogleCompatEmoji(String(intArrayOf(0x1F201), 0, 1), listOf("koko"), false), GoogleCompatEmoji(String(intArrayOf(0x1F202, 0xFE0F), 0, 2), listOf("sa"), false), GoogleCompatEmoji(String(intArrayOf(0x1F237, 0xFE0F), 0, 2), listOf("u6708"), false), GoogleCompatEmoji(String(intArrayOf(0x1F236), 0, 1), listOf("u6709"), false), GoogleCompatEmoji(String(intArrayOf(0x1F22F), 0, 1), listOf("u6307"), false), GoogleCompatEmoji(String(intArrayOf(0x1F250), 0, 1), listOf("ideograph_advantage"), false), GoogleCompatEmoji(String(intArrayOf(0x1F239), 0, 1), listOf("u5272"), false), GoogleCompatEmoji(String(intArrayOf(0x1F21A), 0, 1), listOf("u7121"), false), GoogleCompatEmoji(String(intArrayOf(0x1F232), 0, 1), listOf("u7981"), false), GoogleCompatEmoji(String(intArrayOf(0x1F251), 0, 1), listOf("accept"), false), GoogleCompatEmoji(String(intArrayOf(0x1F238), 0, 1), listOf("u7533"), false), GoogleCompatEmoji(String(intArrayOf(0x1F234), 0, 1), listOf("u5408"), false), GoogleCompatEmoji(String(intArrayOf(0x1F233), 0, 1), listOf("u7a7a"), false), GoogleCompatEmoji(String(intArrayOf(0x3297, 0xFE0F), 0, 2), listOf("congratulations"), false), GoogleCompatEmoji(String(intArrayOf(0x3299, 0xFE0F), 0, 2), listOf("secret"), false), GoogleCompatEmoji(String(intArrayOf(0x1F23A), 0, 1), listOf("u55b6"), false), GoogleCompatEmoji(String(intArrayOf(0x1F235), 0, 1), listOf("u6e80"), false), GoogleCompatEmoji(String(intArrayOf(0x1F534), 0, 1), listOf("red_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E0), 0, 1), listOf("large_orange_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E1), 0, 1), listOf("large_yellow_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E2), 0, 1), listOf("large_green_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x1F535), 0, 1), listOf("large_blue_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E3), 0, 1), listOf("large_purple_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E4), 0, 1), listOf("large_brown_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x26AB), 0, 1), listOf("black_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x26AA), 0, 1), listOf("white_circle"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E5), 0, 1), listOf("large_red_square"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E7), 0, 1), listOf("large_orange_square"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E8), 0, 1), listOf("large_yellow_square"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E9), 0, 1), listOf("large_green_square"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7E6), 0, 1), listOf("large_blue_square"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7EA), 0, 1), listOf("large_purple_square"), false), GoogleCompatEmoji(String(intArrayOf(0x1F7EB), 0, 1), listOf("large_brown_square"), false), GoogleCompatEmoji(String(intArrayOf(0x2B1B), 0, 1), listOf("black_large_square"), false), GoogleCompatEmoji(String(intArrayOf(0x2B1C), 0, 1), listOf("white_large_square"), false), GoogleCompatEmoji(String(intArrayOf(0x25FC, 0xFE0F), 0, 2), listOf("black_medium_square"), false), GoogleCompatEmoji(String(intArrayOf(0x25FB, 0xFE0F), 0, 2), listOf("white_medium_square"), false), GoogleCompatEmoji(String(intArrayOf(0x25FE), 0, 1), listOf("black_medium_small_square"), false), GoogleCompatEmoji(String(intArrayOf(0x25FD), 0, 1), listOf("white_medium_small_square"), false), GoogleCompatEmoji(String(intArrayOf(0x25AA, 0xFE0F), 0, 2), listOf("black_small_square"), false), GoogleCompatEmoji(String(intArrayOf(0x25AB, 0xFE0F), 0, 2), listOf("white_small_square"), false), GoogleCompatEmoji(String(intArrayOf(0x1F536), 0, 1), listOf("large_orange_diamond"), false), GoogleCompatEmoji(String(intArrayOf(0x1F537), 0, 1), listOf("large_blue_diamond"), false), GoogleCompatEmoji(String(intArrayOf(0x1F538), 0, 1), listOf("small_orange_diamond"), false), GoogleCompatEmoji(String(intArrayOf(0x1F539), 0, 1), listOf("small_blue_diamond"), false), GoogleCompatEmoji(String(intArrayOf(0x1F53A), 0, 1), listOf("small_red_triangle"), false), GoogleCompatEmoji(String(intArrayOf(0x1F53B), 0, 1), listOf("small_red_triangle_down"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4A0), 0, 1), listOf("diamond_shape_with_a_dot_inside"), false), GoogleCompatEmoji(String(intArrayOf(0x1F518), 0, 1), listOf("radio_button"), false), GoogleCompatEmoji(String(intArrayOf(0x1F533), 0, 1), listOf("white_square_button"), false), GoogleCompatEmoji(String(intArrayOf(0x1F532), 0, 1), listOf("black_square_button"), false), ) }
20
null
289
1,501
2a17f4c14a08493aa3f637a02be5a35730942126
10,222
Emoji
Apache License 2.0
src/main/kotlin/insyncwithfoo/ryecharm/configurations/main/Services.kt
InSyncWithFoo
849,672,176
false
{"Kotlin": 264146, "Python": 3171, "HTML": 624}
package insyncwithfoo.ryecharm.configurations.main import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.Service import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import insyncwithfoo.ryecharm.configurations.ConfigurationService import insyncwithfoo.ryecharm.configurations.getMergedState @State(name = "insyncwithfoo.ryecharm.configurations.main.Global", storages = [Storage("ryecharm.xml")]) @Service(Service.Level.APP) internal class MainGlobalService : ConfigurationService<MainConfigurations>(MainConfigurations()) { companion object { fun getInstance() = service<MainGlobalService>() } } @State(name = "insyncwithfoo.ryecharm.configurations.main.Local", storages = [Storage("ryecharm.xml")]) @Service(Service.Level.PROJECT) internal class MainLocalService : ConfigurationService<MainConfigurations>(MainConfigurations()) { companion object { fun getInstance(project: Project) = project.service<MainLocalService>() } } @State( name = "insyncwithfoo.ryecharm.configurations.main.Override", storages = [Storage("ryecharm-overrides.xml", roamingType = RoamingType.DISABLED)] ) @Service(Service.Level.PROJECT) internal class MainOverrideService : ConfigurationService<MainOverrides>(MainOverrides()) { companion object { fun getInstance(project: Project) = project.service<MainOverrideService>() } } internal val globalMainConfigurations: MainConfigurations get() = MainGlobalService.getInstance().state internal val Project.mainConfigurations: MainConfigurations get() = getMergedState<MainGlobalService, MainLocalService, MainOverrideService, _>()
0
Kotlin
0
7
c1a04b622fbfb02a2fb155d8c9aa069520eda23e
1,825
ryecharm
MIT License
core/src/main/kotlin/me/ihdeveloper/humans/core/system/player.kt
iHDeveloper
297,037,463
false
null
package me.ihdeveloper.humans.core.system import me.ihdeveloper.humans.core.System import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.player.PlayerMoveEvent import org.bukkit.event.player.PlayerQuitEvent import org.bukkit.plugin.java.JavaPlugin /** * A system for handling frozen players */ class FreezeSystem : System("Core/Freeze"), Listener { companion object { val players = mutableMapOf<String, Location>() } override fun init(plugin: JavaPlugin) { Bukkit.getPluginManager().registerEvents(this, plugin) } override fun dispose() {} @EventHandler(priority = EventPriority.HIGHEST) @Suppress("UNUSED") fun onMove(event: PlayerMoveEvent) { event.run { if (!players.contains(player.name)) return player.teleport(players[player.name]) isCancelled = true } } @EventHandler(priority = EventPriority.LOWEST) @Suppress("UNUSED") fun onQuit(event: PlayerQuitEvent) { players.remove(event.player.name) } }
2
Kotlin
1
1
c20ecf2689c9fd2d1b355e6b0fdf7d3b8cbd0b5a
1,186
Humans
MIT License
core/tzdbOnFilesystem/src/internal/TzdbOnFilesystem.kt
Kotlin
215,849,579
false
{"Kotlin": 1104935, "C": 415, "Java": 236}
/* * Copyright 2019-2023 JetBrains s.r.o. and contributors. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package kotlinx.datetime.internal internal class TzdbOnFilesystem(defaultTzdbPath: Path? = null): TimeZoneDatabase { internal val tzdbPath = tzdbPaths(defaultTzdbPath).find { path -> tabPaths.any { path.containsFile(it) } } ?: throw IllegalStateException("Could not find the path to the timezone database") override fun rulesForId(id: String): TimeZoneRules { val idAsPath = Path.fromString(id) require(!idAsPath.isAbsolute) { "Timezone ID '$idAsPath' must not begin with a '/'" } require(idAsPath.components.none { it == ".." }) { "'$idAsPath' must not contain '..' as a component" } val file = Path(tzdbPath.isAbsolute, tzdbPath.components + idAsPath.components) val contents = file.readBytes() ?: throw RuntimeException("File '$file' not found") return readTzFile(contents).toTimeZoneRules() } override fun availableTimeZoneIds(): Set<String> = buildSet { tzdbPath.tryTraverseDirectory(exclude = tzdbUnneededFiles) { add(it.toString()) } } } // taken from https://github.com/tzinfo/tzinfo/blob/9953fc092424d55deaea2dcdf6279943f3495724/lib/tzinfo/data_sources/zoneinfo_data_source.rb#L354 private val tabPaths = listOf("zone1970.tab", "zone.tab", "tab/zone_sun.tab") /** The files that sometimes lie in the `zoneinfo` directory but aren't actually time zones. */ private val tzdbUnneededFiles: Regex = Regex( // taken from https://github.com/tzinfo/tzinfo/blob/9953fc092424d55deaea2dcdf6279943f3495724/lib/tzinfo/data_sources/zoneinfo_data_source.rb#L88C29-L97C21 "\\+VERSION|leapseconds|localtime|posix|posixrules|right|SECURITY|src|timeconfig|" + // replicating https://github.com/tzinfo/tzinfo/blob/9953fc092424d55deaea2dcdf6279943f3495724/lib/tzinfo/data_sources/zoneinfo_data_source.rb#L442 ".*\\..*|" + // taken from https://github.com/HowardHinnant/date/blob/ab37c362e35267d6dee02cb47760f9e9c669d3be/src/tz.cpp#L2863-L2874 "Factory" ) /** The directories checked for a valid timezone database. */ internal fun tzdbPaths(defaultTzdbPath: Path?) = sequence { defaultTzdbPath?.let { yield(it) } // taken from https://github.com/tzinfo/tzinfo/blob/9953fc092424d55deaea2dcdf6279943f3495724/lib/tzinfo/data_sources/zoneinfo_data_source.rb#L70 yieldAll(listOf("/usr/share/zoneinfo", "/usr/share/lib/zoneinfo", "/etc/zoneinfo").map { Path.fromString(it) }) currentSystemTimeZonePath?.splitTimeZonePath()?.first?.let { yield(it) } } internal val currentSystemTimeZonePath get() = chaseSymlinks("/etc/localtime") /** * Given a path like `/usr/share/zoneinfo/Europe/Berlin`, produces `/usr/share/zoneinfo to Europe/Berlin`. * Returns null if the function can't recognize the boundary between the time zone and the tzdb. */ // taken from https://github.com/HowardHinnant/date/blob/ab37c362e35267d6dee02cb47760f9e9c669d3be/src/tz.cpp#L3951-L3952 internal fun Path.splitTimeZonePath(): Pair<Path, Path>? { val i = components.indexOf("zoneinfo") if (!isAbsolute || i == -1 || i == components.size - 1) return null return Pair( Path(true, components.subList(0, i + 1)), Path(false, components.subList(i + 1, components.size)) ) }
78
Kotlin
101
2,411
670a914065f896487735c3120ac8930b30ac581f
3,370
kotlinx-datetime
Apache License 2.0
composeApp/src/commonMain/kotlin/data/source/local/dao/WorkoutPlanDao.kt
anwar-pasaribu
798,728,457
false
{"Kotlin": 370338, "Swift": 585}
package data.source.local.dao import app.cash.sqldelight.coroutines.asFlow import app.cash.sqldelight.coroutines.mapToList import com.unwur.tabiatmu.database.TabiatDatabase import domain.model.gym.WorkoutPlan import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class WorkoutPlanDao( private val database: TabiatDatabase ) : IWorkoutPlanDao { override suspend fun getAllWorkoutPlanObservable(): Flow<List<WorkoutPlan>> { return database.workoutPlanQueries.selectAllWorkoutPlan() .asFlow() .mapToList(Dispatchers.Default) .map { workoutPlanEntityList -> workoutPlanEntityList.map { WorkoutPlan( id = it.id, name = it.name, description = it.description, dateTimeStamp = it.dateTimeStamp, orderingNumber = it.orderingNumber.toInt() ) } } } override suspend fun getAllWorkoutPlan(): List<WorkoutPlan> { return database.workoutPlanQueries.selectAllWorkoutPlan() .executeAsList() .map { WorkoutPlan( id = it.id, name = it.name, description = it.description, dateTimeStamp = it.dateTimeStamp, orderingNumber = it.orderingNumber.toInt() ) } } override suspend fun getWorkoutPlan(workoutPlanId: Long): WorkoutPlan { try { val data = database.workoutPlanQueries.selectWorkoutPlanById(workoutPlanId).executeAsOne() return WorkoutPlan( id = data.id, name = data.name, description = data.description, dateTimeStamp = data.dateTimeStamp, orderingNumber = data.orderingNumber.toInt() ) } catch (e: Exception) { return WorkoutPlan( id = 0, name = "", description = "", dateTimeStamp = 0, orderingNumber = 0 ) } } override suspend fun getLatestWorkoutPlan(): WorkoutPlan { try { val data = database.workoutPlanQueries.selectLatestWorkoutPlan().executeAsOne() return WorkoutPlan( id = data.id, name = data.name, description = data.description, dateTimeStamp = data.dateTimeStamp, orderingNumber = data.orderingNumber.toInt() ) } catch (e: Exception) { return WorkoutPlan( id = 0, name = "", description = "", dateTimeStamp = 0, orderingNumber = 0 ) } } override suspend fun insertWorkoutPlan( name: String, description: String, datetimeStamp: Long, orderingNumber: Int ) { database.workoutPlanQueries.insertWorkoutPlan( name = name, description = description, dateTimeStamp = datetimeStamp, orderingNumber = orderingNumber.toLong() ) } override suspend fun updateWorkoutPlan( workoutPlanId: Long, name: String, description: String ) { val existingWorkoutPlan = getWorkoutPlan(workoutPlanId) if (existingWorkoutPlan.id > 0) { database.workoutPlanQueries.updateWorkoutPlan( id = workoutPlanId, name = name, description = description, orderingNumber = existingWorkoutPlan.orderingNumber.toLong(), ) } } override suspend fun deleteWorkoutPlan(workoutPlanId: Long) { database.workoutPlanQueries.deleteWorkoutPlanById(workoutPlanId) } }
0
Kotlin
0
0
f2878e0f953fd2003d0c412d6de344a4932c886d
3,996
Tabiat
MIT License
processor/src/main/kotlin/com/gediminaszukas/polyassistant/helpers/Generator.kt
GediminasZukas
310,505,536
false
{"Java": 11313, "Kotlin": 10297}
package com.gediminaszukas.polyassistant.helpers import com.gediminaszukas.polyassistant.RuntimeTypeAdapterFactory import com.google.gson.GsonBuilder import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.TypeSpec import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.TypeElement class Generator( private val polymorphicTypesHierarchies: Map<TypeElement, Set<TypeElement>>, private val processingEnv: ProcessingEnvironment ) { fun generateCode() { val fileSpec = FileSpec.builder("", GENERATED_OBJECT_NAME) .addType( TypeSpec.objectBuilder(GENERATED_OBJECT_NAME) .addFunction( createFunctionSpec() ).build() ).build() fileSpec.writeTo(processingEnv.filer) } private fun createFunctionSpec(): FunSpec { val funcSpecBuilder = FunSpec.builder("registerIn") .addParameter("gsonBuilder", GsonBuilder::class.java) createFunctionBody(funcSpecBuilder) return funcSpecBuilder.build() } private fun createFunctionBody(funcSpecBuilder: FunSpec.Builder) { var factoryIndex = 0 polymorphicTypesHierarchies.forEach { (parentType, parentTypeChildren) -> val factoryParamName = "factory${factoryIndex}" funcSpecBuilder.addStatement( "val $factoryParamName = %T.of($parentType::class.java)", RuntimeTypeAdapterFactory::class.java ) parentTypeChildren.forEach { childType -> funcSpecBuilder.addStatement(".registerSubtype(${childType}::class.java)") } funcSpecBuilder.addStatement("gsonBuilder.registerTypeAdapterFactory($factoryParamName)") funcSpecBuilder.addStatement("") factoryIndex++ } } companion object { private const val GENERATED_OBJECT_NAME = "GeneratedRuntimeTypeAdapterFactories" } }
1
null
1
1
430566f126613c6bb32a9aa4db8ead7a8abc4bd6
2,050
PolyAssistant
Apache License 2.0
app/src/main/java/com/mlievens/listdetailapp/data/repositories/ItemDetailDataRepository.kt
mjl757
593,397,660
false
null
package com.mlievens.listdetailapp.data.repositories import com.mlievens.listdetailapp.data.service.MagicItemsService import com.mlievens.listdetailapp.domain.models.ItemDetail import com.mlievens.listdetailapp.domain.repositories.ItemDetailRepository class ItemDetailDataRepository( private val magicItemsService: MagicItemsService ) : ItemDetailRepository { override suspend fun getItemDetail(id: String): Result<ItemDetail> { return magicItemsService.getMagicItem(id) } }
0
Kotlin
0
0
6d9684560c1c78f5fb92a2522ab523997a180673
496
ListDetailApp
MIT License
libraries/csm.cloud.common.streamable/src/main/kotlin/com/bosch/pt/csm/cloud/common/eventstore/BaseLocalEventBus.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.common.eventstore import com.bosch.pt.csm.cloud.common.command.mapper.AvroEventMapper import com.bosch.pt.csm.cloud.common.eventstore.EventSourceEnum.ONLINE import com.bosch.pt.csm.cloud.common.model.key.AggregateEventMessageKey import org.apache.avro.specific.SpecificRecordBase import org.springframework.context.ApplicationEventPublisher /** * Generic implementation of a [LocalEventBus]. To create a sub-class of it, just specify your * implementation of the event store and the marker interfaces used to search for all snapshot * stores relevant for your sub-class of the [LocalEventBus]. * * @param ES: Implementation of [AbstractEventStore] used for the instance of this bus * @param S: Marker interface derived from [SnapshotStore] used to inject the corresponding snapshot * stores relevant for this context */ open class BaseLocalEventBus<ES : AbstractEventStore<*>, S : SnapshotStore>( private val eventStore: ES, private val snapshotStores: List<S>, private val eventPublisher: ApplicationEventPublisher, private val avroEventMappers: List<AvroEventMapper> = emptyList() ) : LocalEventBus { override fun emit(event: Any, newVersion: Long, source: EventSourceEnum) { try { val mapper = avroEventMappers.single { it.canMap(event) } emit(mapper.mapToKey(event, newVersion), mapper.mapToValue(event, newVersion), source) } catch (e: NoSuchElementException) { throw NoSuchElementException( "No avro event mapper found for ${event::class.java}. " + "Did you forget to register the mapper on the event bus?", e) } catch (e: IllegalArgumentException) { throw IllegalArgumentException( "Multiple avro event mappers found for ${event::class.java}.", e) } } override fun emit( key: AggregateEventMessageKey, value: SpecificRecordBase, source: EventSourceEnum ) { dispatchToSnapshotStore(key, value, source) if (source == ONLINE) { eventStore.save(key, value) eventPublisher.publishEvent(value) } } private fun dispatchToSnapshotStore( key: AggregateEventMessageKey, message: SpecificRecordBase, source: EventSourceEnum ) { snapshotStores .filter { it.handlesMessage(key, message) } .map { it.handleMessage(key, message, source) } .count() .apply { if (this < 1) { error("No snapshot store handled message with key $key") } else if (this > 1) { error("More than one snapshot store handled message with key $key") } } } } @Deprecated("Use BaseLocalEventBus instead.") typealias AbstractLocalEventBus<ES, S> = BaseLocalEventBus<ES, S>
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
2,978
bosch-pt-refinemysite-backend
Apache License 2.0
app-examples/example-kt-03adapters/src/main/java/foo/bar/example/foreadapterskt/ui/playlist/PlaylistsActivity.kt
erdo
92,027,307
false
{"Kotlin": 602726, "Java": 405950, "Shell": 1405}
package foo.bar.example.foreadapterskt.ui.playlist import androidx.fragment.app.FragmentActivity import foo.bar.example.foreadapterskt.R class PlaylistsActivity : FragmentActivity(R.layout.activity_playlists)
2
Kotlin
3
46
1af5bd3ad9b2395a636fac12c40016fd2c815d0c
211
android-fore
Apache License 2.0
src/test/kotlin/no/nav/syfo/testutil/mocks/MockData.kt
navikt
303,972,532
false
{"Kotlin": 502117, "Dockerfile": 148}
package no.nav.syfo.testutil.mocks import no.nav.syfo.access.domain.UserAccessStatus const val fnr1 = "12345678901" const val fnr2 = "23456789012" const val fnr3 = "34567890123" const val fnr4 = "45678901234" const val fnr5 = "45678901230" const val orgnummer = "999888777" val userAccessStatus1 = UserAccessStatus(fnr1, true) val userAccessStatus2 = UserAccessStatus(fnr2, true) val userAccessStatus3 = UserAccessStatus(fnr3, false) val userAccessStatus4 = UserAccessStatus(fnr4, false) val userAccessStatus5 = UserAccessStatus(fnr5, false) val dkifResponseSuccessKanVarslesResponseJSON = """ { "kanVarsles": true, "reservert": false } """.trim() val dkifResponseSuccessReservertResponseJSON = """ { "kanVarsles": false, "reservert": true } """.trim() val dkifResponseMap = mapOf( fnr1 to dkifResponseSuccessKanVarslesResponseJSON, fnr2 to dkifResponseSuccessReservertResponseJSON ) val tokenFromAzureServer = Token( access_token = "AAD access token", token_type = "Bearer", expires_in = 3600 ) data class Token( val access_token: String, val token_type: String, val expires_in: Long )
1
Kotlin
2
0
88e968573ef981c80a724a99dc9ea83a3d33d05b
1,175
esyfovarsel
MIT License
mvi-core-primitives/src/main/kotlin/dev/sunnyday/arch/mvi/primitive/Cancellable.kt
SunnyDayDev
613,837,799
false
null
package dev.sunnyday.arch.mvi.primitive fun interface Cancellable { fun cancel() companion object { private val EMPTY = Cancellable { } fun empty(): Cancellable = EMPTY } }
13
Kotlin
0
1
30d3e472138d9797d9eda0363c7aae052e89623c
205
arch-mvi
MIT License
src/main/kotlin/br/com/zup/ot6/izabel/grpc/GerenciadorChavePixFactory.kt
adsizabel
399,903,970
true
{"Kotlin": 22448}
package br.com.zup.ot6.izabel.grpc import br.com.zup.ot6.izabel.GerenciadorChavePixGrpcServiceGrpc import io.grpc.ManagedChannel import io.micronaut.context.annotation.Factory import io.micronaut.grpc.annotation.GrpcChannel import jakarta.inject.Singleton @Factory class GerenciadorChavePixFactory(@GrpcChannel("keyManager") val channel: ManagedChannel) { @Singleton fun gerenciadorChave() = GerenciadorChavePixGrpcServiceGrpc.newBlockingStub(channel) }
0
Kotlin
0
0
6bb1edc34c8f71e1b24045c097c210404f9b26c2
464
orange-talents-06-template-pix-keymanager-rest
Apache License 2.0
talk/src/test/kotlin/com/tgirard12/kotlintalk/12_Tests.kt
tgirard12
80,903,448
false
null
package com.tgirard12.kotlintalk import io.kotlintest.matchers.be import io.kotlintest.specs.StringSpec /** * https://github.com/kotlintest/kotlintest */ class KotlinTest : StringSpec() { override fun beforeAll() { super.beforeAll() } override fun beforeEach() { super.beforeEach() } init { "strings.length should return size of string" { "hello".length shouldBe 5 } listOf(3, 5, 7).forEach { "$it must be < 10" { it should be lt 10 } } } }
0
Kotlin
1
11
ac8fdc64c777ee258e3690061692ac8acdbb3efa
574
kotlin-talk
Apache License 2.0
gpx/src/main/java/com/kylecorry/andromeda/gpx/GPXSerializer.kt
kylecorry31
394,273,851
false
{"Kotlin": 845341, "Python": 307}
package com.kylecorry.andromeda.gpx import com.kylecorry.andromeda.core.io.DeserializationException import com.kylecorry.andromeda.core.io.ISerializer import com.kylecorry.andromeda.core.io.SerializationException import java.io.InputStream import java.io.OutputStream class GPXSerializer(private val creator: String) : ISerializer<GPXData> { override fun serialize(obj: GPXData, stream: OutputStream) { try { GPXParser.toGPX(obj, creator, stream) } catch (e: Exception) { throw SerializationException(e.message ?: "Unknown error", e) } } override fun deserialize(stream: InputStream): GPXData { return try { GPXParser.parse(stream) } catch (e: Exception) { throw DeserializationException(e.message ?: "Unknown error", e) } } }
43
Kotlin
4
21
a5d9aedd834055b0f8959c9d7cb4149719fdd769
841
andromeda
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/events/SecondaryPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.events import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.events.CfnEndpoint @Generated public fun buildSecondaryProperty(initializer: @AwsCdkDsl CfnEndpoint.SecondaryProperty.Builder.() -> Unit): CfnEndpoint.SecondaryProperty = CfnEndpoint.SecondaryProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
451a1e42282de74a9a119a5716bd95b913662e7c
435
aws-cdk-kt
Apache License 2.0
api-dev/src/main/kotlin/io/qalipsis/api/sync/Slot.kt
qalipsis
428,742,260
false
{"Kotlin": 708982, "Dockerfile": 2015}
/* * Copyright 2022 AERIS IT Solutions GmbH * * 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.qalipsis.api.sync import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeout import java.time.Duration /** * * A slot is a suspended equivalent implementation slightly comparable to a [java.util.concurrent.atomic.AtomicReference]. * * It suspends the caller until a value is set in the slot. All the callers receive the same value. * Setting a new value always overwrite the previous one. * * @author <NAME> */ class Slot<T>(private var value: T? = null) { private val latch = Latch(value == null) private val writeLock = Mutex() /** * If a value is present, returns `true`, otherwise `false`. */ fun isPresent() = value != null /** * If a value is not present, returns `true`, otherwise `false`. */ fun isEmpty() = !isPresent() /** * Non-blocking operation returning the value if present or an error otherwise. */ fun forceGet() = requireNotNull(value) /** * Sets the value into the slot and release all the current caller to [get] or [remove]. */ suspend fun set(value: T) { writeLock.withLock { this.value = value latch.release() } } /** * Clears the content of the slot. */ suspend fun clear() { writeLock.withLock { latch.lock() this.value = null } } /** * Blocking implementation of [set]. */ fun offer(value: T) { runBlocking { set(value) } } /** * Returns the value if it exists or suspend the call otherwise. */ suspend fun get(): T { await() return value!! } /** * Returns the value if it exists or null otherwise. */ fun getOrNull(): T? { return value } /** * Returns the value if it exists or suspends until the timeout is reached otherwise. * If the timeout is reached before a value is set, a [kotlinx.coroutines.TimeoutCancellationException] is thrown. */ suspend fun get(timeout: Duration): T { withTimeout(timeout.toMillis()) { await() } return value!! } /** * Returns and removes the value if it exists or suspend the call otherwise. */ suspend fun remove(): T { await() val result = value!! writeLock.withLock { latch.lock() value = null } return result } /** * Returns and removes the value if it exists or suspends until the timeout is reached otherwise. * If the timeout is reached before a value is available, a [kotlinx.coroutines.TimeoutCancellationException] is thrown. */ suspend fun remove(timeout: Duration): T { return withTimeout(timeout.toMillis()) { remove() } } /** * If not value is currently, suspend the call until the latch is released. */ private suspend fun await() { if (isEmpty()) { latch.await() } } override fun toString(): String { return "Slot(value=$value)" } }
0
Kotlin
0
0
6d5cc75c30f47434ee8cacf81430fece6d0e0a4f
3,822
qalipsis-api
Apache License 2.0
src/main/kotlin/org/jetbrains/kotlin/demo/BaseController.kt
tomasky
98,508,921
false
null
package org.jetbrains.kotlin.demo import org.springframework.web.bind.annotation.* import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.CompletableFuture import org.springframework.stereotype.Component import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.access.annotation.* import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.servlet.mvc.method.annotation.* import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import org.springframework.http.HttpStatus import org.springframework.security.access.AccessDeniedException import org.springframework.web.HttpRequestMethodNotSupportedException import com.fasterxml.jackson.annotation.* @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) abstract class BaseController { @ExceptionHandler @ResponseBody fun handleServiceException(req:HttpServletRequest , response:HttpServletResponse , e:Exception ):ErrorResponse { var status = when(e){ is AccessDeniedException -> HttpStatus.FORBIDDEN.value() is org.springframework.web.bind.MissingServletRequestParameterException -> 400 is org.springframework.web.HttpRequestMethodNotSupportedException -> 405 is java.lang.IllegalArgumentException -> 400 is org.springframework.http.converter.HttpMessageNotReadableException -> 4002 is DataCanNotNullException -> 400 is DataNOTFOUNDException -> 404 else -> HttpStatus.OK.value() } if(status != 200){ var msg = e.message?:e.getLocalizedMessage() if(status == 4002){ msg = "json data error" status = 400 } val error = ErrorResponse(status,msg) response.setStatus(status) return error } else throw e } }
0
Kotlin
1
0
56cfa66b6aa982794ec66fe111f2f028797992b7
2,004
spring-boot-restful
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/hardware/drive/tank/TankDrive.kt
randomnetcat
208,137,961
true
{"Kotlin": 119475, "Java": 43105}
package org.firstinspires.ftc.teamcode.hardware.drive.tank import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.DcMotorEx import org.firstinspires.ftc.teamcode.hardware.drive.BaseDriveEx import org.firstinspires.ftc.teamcode.hardware.drive.FourWheelDrivetrain import org.firstinspires.ftc.teamcode.hardware.drive.FourWheelDrivetrainEx import org.firstinspires.ftc.teamcode.hardware.drive.tank.TankDriveConstants.AXIAL_PID import org.firstinspires.ftc.teamcode.hardware.drive.tank.TankDriveConstants.BASE_CONSTRAINTS import org.firstinspires.ftc.teamcode.hardware.drive.tank.TankDriveConstants.CROSS_TRACK_PID import org.firstinspires.ftc.teamcode.hardware.drive.tank.TankDriveConstants.FEEDFORWARD import org.firstinspires.ftc.teamcode.hardware.drive.tank.TankDriveConstants.HEADING_PID import org.firstinspires.ftc.teamcode.util.roadrunner.PIDCoefficients import org.firstinspires.ftc.teamcode.util.roadrunner.roadrunner import org.firstinspires.ftc.teamcode.util.units.Meters import org.firstinspires.ftc.teamcode.hardware.drive.tank.TankDriveConstants.TRACK_WIDTH import org.firstinspires.ftc.teamcode.hardware.imu.InternalIMU import org.firstinspires.ftc.teamcode.util.setPID import org.firstinspires.ftc.teamcode.util.units.Seconds import org.firstinspires.ftc.teamcode.util.units.div data class TankDrivetrain(val frontLeft: DcMotorEx, val frontRight: DcMotorEx, val backLeft: DcMotorEx, val backRight: DcMotorEx) { private val fourWheelValue by lazy { FourWheelDrivetrainEx( frontLeft = frontLeft, frontRight = frontRight, backLeft = backLeft, backRight = backRight ) } fun toFourWheelDrivetrain() = fourWheelValue } class TankDrive(private val imu: InternalIMU, drivetrain: TankDrivetrain) : BaseDriveEx(drivetrain.toFourWheelDrivetrain()) { private val roadrunnerValue by lazy { object : RRTankDriveBase(TankDrivetrainConfig(trackWidth = TRACK_WIDTH), TankDrivePID(axialPID = AXIAL_PID, headingPID = HEADING_PID, crossTrackPID = CROSS_TRACK_PID), FEEDFORWARD, BASE_CONSTRAINTS) { override fun getPIDCoefficients(runMode: DcMotor.RunMode): PIDCoefficients { return PIDCoefficients(motors()[0].getPIDFCoefficients(runMode)) } override fun setPIDCoefficients(runMode: DcMotor.RunMode, coefficients: PIDCoefficients) { forEachMotor { this.setPID(runMode, coefficients) } } override val rawExternalHeading: Double get() { imu.update() return imu.heading().toRadians().raw } private fun positionOf(motor: DcMotor) = TankDriveConstants.encoderTicksToDistance(motor.currentPosition).roadrunner() private fun positionOf(motorList: Iterable<DcMotor>) = Meters(motorList.map { positionOf(it).toMeters().raw }.average()).roadrunner() override fun getWheelVelocities(): List<Double> { return listOf(leftMotors().map { (TankDriveConstants.encoderTicksToDistance(it.getVelocity()) / Seconds(1)).roadrunner().raw }.average()) } override fun getWheelPositions(): List<Double> { return listOf(positionOf(leftMotors()).roadrunner().raw, positionOf(rightMotors()).roadrunner().raw) } override fun setMotorPowers(left: Double, right: Double) { leftPower(left) rightPower(right) } } } fun roadrunner() = roadrunnerValue fun update() = roadrunner().update() }
0
Kotlin
0
0
ec4226d7aee8c3b4b8309655cdffeaf223bc22fe
3,632
SkyStone
MIT License
src/main/kotlin/modloader/ModLoader.kt
Asteroid4
786,465,937
false
{"Kotlin": 25712, "Shell": 114, "Batchfile": 102}
package asteroid4.tileengine.modloader import asteroid4.tileengine.ProgramData import java.io.File import javax.script.* object ModLoader { private val loadedMods = HashMap<String, Pair<ModListener, TileEngineApi?>>() fun init() { loadedMods.clear() File(ProgramData.WORKING_DIR + File.separatorChar + "TileEngineData" + File.separatorChar + "mods").listFiles() .sorted().forEach { modFile -> if (modFile.isFile && modFile.extension == "jar") { (ClassLoader.getSystemClassLoader() as DynamicClassLoader).add(modFile.toURI().toURL()) val mainClass = Class.forName("ModKt", true, ClassLoader.getSystemClassLoader()) val instance = mainClass.getDeclaredConstructor().newInstance() as ModListener val api = getApi(modFile.nameWithoutExtension, instance.getPreferredApiVersion()) instance.loadMod(api) loadedMods[modFile.nameWithoutExtension] = Pair(instance, api) } } } private fun getApi(modName: String, version: Int) = when (version) { 1 -> TileEngineApiV1(modName) else -> null } }
0
Kotlin
0
1
fba322491a395f2ce3b54989465208d2e1df631e
1,178
TileEngine
The Unlicense
app/src/main/java/com/github/wanderwise_inc/app/data/SignInLauncher.kt
WanderWise-Inc
775,382,316
false
{"Kotlin": 505854}
package com.github.wanderwise_inc.app.data interface SignInLauncher { fun signIn() }
12
Kotlin
0
1
d25519f75bae52d0e1cc22a4e53db652b561d3f5
88
app
MIT License
src/main/kotlin/com/jacobhyphenated/day25/Day25.kt
jacobhyphenated
572,119,677
false
null
package com.jacobhyphenated.day25 import com.jacobhyphenated.Day import com.jacobhyphenated.day9.IntCode import java.io.File // Cryostasis class Day25: Day<List<Long>> { override fun getInput(): List<Long> { return this.javaClass.classLoader.getResource("day25/input.txt")!! .readText() .split(",") .map { it.toLong() } } /** * Play the text based game using console input to navigate the robot * pick up items along the way to pass through the weight based security scanner. * * Use commands provided by the program, plus two additional commands (help, quit) * * Spoiler - collect: spool of cat6, fixed point, candy cane, shell */ override fun part1(input: List<Long>): Number { val robot = IntCode(input) robot.execute() val helpText = """ Commands are: north Move north south Move south east Move east west Move west take <item> Pick up a nearby item drop <item> Drop an item from the inventory inv List items in the inventory help Show help text and list of commands quit Exit the program """.trimIndent() readln() while(true) { val outputAsString = robot.output .map { it.toInt() } .map { it.toChar() } .joinToString("") println(outputAsString) robot.output.clear() print("cmd: ") when(val command = readln().lines()[0].lowercase()){ "help" -> println(helpText) "quit" -> break else -> robot.execute(commandToAscii(command)) } } return 0 } /** * Day 25 has no part 2 */ override fun part2(input: List<Long>): Number { return 0 } private fun commandToAscii(command: String): List<Long> { return command.toCharArray().map { it.code } .map { it.toLong() } .toMutableList().also { it.add(10L) } } }
0
Kotlin
0
0
1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4
2,210
advent2019
The Unlicense
processor/src/main/java/com/joom/lightsaber/processor/model/InjectionContext.kt
joomcode
170,310,869
false
null
/* * Copyright 2020 <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 com.joom.lightsaber.processor.model import com.joom.grip.mirrors.Type data class InjectionContext( val modules: Collection<Module>, val components: Collection<Component>, val contractConfigurations: Collection<ContractConfiguration>, val injectableTargets: Collection<InjectionTarget>, val providableTargets: Collection<InjectionTarget>, val factories: Collection<Factory>, val bindings: Collection<Binding> ) { private val componentsByType = components.associateBy { it.type } private val contractConfigurationsByType = contractConfigurations.associateBy { it.type } private val modulesByType = getModulesWithDescendants().associateBy { it.type } private val injectableTargetsByType = injectableTargets.associateBy { it.type } private val providableTargetsByType = providableTargets.associateBy { it.type } private val factoryInjectionPointsByType = factories.flatMap { it.provisionPoints }.map { it.injectionPoint }.associateBy { it.containerType } fun getModulesWithDescendants(): Sequence<Module> { return (components.asSequence().flatMap { it.getModulesWithDescendants() } + contractConfigurations.asSequence().flatMap { it.getModulesWithDescendants() } + modules.flatMap { it.getModulesWithDescendants() }).distinct() } fun getImportsWithDescendants(): Sequence<Import> { return (components.asSequence().flatMap { it.getImportsWithDescendants() } + contractConfigurations.asSequence().flatMap { it.getImportsWithDescendants() } + modules.asSequence().flatMap { it.getImportsWithDescendants() }).distinct() } fun findComponentByType(componentType: Type.Object): Component? = componentsByType[componentType] fun findContractConfigurationByType(contractConfigurationType: Type.Object): ContractConfiguration? = contractConfigurationsByType[contractConfigurationType] fun findModuleByType(moduleType: Type.Object): Module? = modulesByType[moduleType] fun findInjectableTargetByType(injectableTargetType: Type.Object): InjectionTarget? = injectableTargetsByType[injectableTargetType] fun findProvidableTargetByType(providableTargetType: Type.Object): InjectionTarget? = providableTargetsByType[providableTargetType] fun findFactoryInjectionPointByType(factoryInjectionPointType: Type.Object): FactoryInjectionPoint? = factoryInjectionPointsByType[factoryInjectionPointType] }
2
Kotlin
0
9
f1eede8e14ecb399a451085fd5d13e77dd67f329
2,997
lightsaber
Apache License 2.0
application/module/module_movie/src/main/java/novalinx/module/movie/MovieInitializer.kt
imswy
710,208,893
false
{"Kotlin": 613223}
package novalinx.module.movie import novalinx.core.BaseInitializer import android.content.Context import androidx.startup.Initializer import java.util.* /** * detail: Movie Module ( App Startup Initializer ) * @author Ttt */ class MovieInitializer : BaseInitializer<MovieModule>() { override fun create(context: Context): MovieModule { MovieModule.instance.initialize(context) return MovieModule.instance } override fun dependencies_abs(): MutableList<Class<out Initializer<*>>> = Collections.emptyList() }
0
Kotlin
0
0
44cd560c6087f570c15d6892a38720f23415330d
549
Novalinx
Apache License 2.0
src/main/kotlin/app/load/services/impl/FilterServiceImpl.kt
uk-gov-mirror
356,707,933
true
{"Kotlin": 220958, "Python": 4434, "Makefile": 1455, "Shell": 654}
package app.load.services.impl import app.load.configurations.FilterServiceConfiguration import app.load.services.FilterService import org.apache.commons.lang3.StringUtils import uk.gov.dwp.dataworks.logging.DataworksLogger import java.io.File import java.io.FileReader import java.text.SimpleDateFormat import java.util.* class FilterServiceImpl(private val propertiesFile: String, private val skipEarlierThan: String, private val skipLaterThan: String): FilterService { override fun filterStatus(timestamp: Long): FilterService.FilterStatus = when { // timestamp == epoch means a record with no last modified date // so put these in as a precaution as they may be recent. timestamp < earlierThan && timestamp != epoch -> { FilterService.FilterStatus.FilterTooEarly } timestamp > laterThan -> { FilterService.FilterStatus.FilterTooLate } else -> { FilterService.FilterStatus.DoNotFilter } } private val earlierThan: Long by lazy { if (properties.getProperty("filter.earlier.than") != null) { parsedDate(properties.getProperty("filter.earlier.than")) } else if (StringUtils.isNotBlank(skipEarlierThan)) { parsedDate(skipEarlierThan) } else { Long.MIN_VALUE } } private val laterThan: Long by lazy { if (properties.getProperty("filter.later.than") != null) { parsedDate(properties.getProperty("filter.later.than")) } else if (StringUtils.isNotBlank(skipLaterThan)) { parsedDate(skipLaterThan) } else { Long.MAX_VALUE } } private fun parsedDate(date: String) = if (alternateDateFormatPattern.matches(date)) { SimpleDateFormat(alternateDateFormat).parse(date).time } else { SimpleDateFormat(dateFormat).parse(date).time } private val properties: Properties by lazy { Properties().apply { if (File(propertiesFile).isFile) { load(FileReader(propertiesFile)) } } } companion object { const val dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" const val alternateDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" val epoch = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ").parse("1980-01-01T00:00:00.000+0000").time val alternateDateFormatPattern = Regex("""Z$""") val logger = DataworksLogger.getLogger(FilterServiceImpl::class.java.toString()) fun connect() = FilterServiceImpl(FilterServiceConfiguration.propertiesFile, FilterServiceConfiguration.earlierThan, FilterServiceConfiguration.laterThan) } }
0
null
0
0
1827c850058841f909b874ae939959db7b8da6d5
3,059
dwp.historic-data-loader
ISC License
Mentorias/PraticandoOO/src/main/kotlin/conta/Conta.kt
P3d50
385,913,689
false
{"Kotlin": 77599, "Java": 630}
package conta import MovimentaçãoFinanceira abstract class Conta( val numero:Int, val agencia:String, private var _valorSaldo:Double=0.0): MovimentaçãoFinanceira { init { printSaldo() } fun getSaldo():Double{ return this._valorSaldo } fun instanceTypeName():String{ return this.javaClass.name.drop(6) } fun printSaldo(){ println("${instanceTypeName()}: $numero - Agencia: $agencia - Saldo atual: $_valorSaldo ") } private fun temSaldo(valor: Double): Boolean { return (_valorSaldo - valor) >= 0 } abstract fun taxaDeSaque():Double override fun depositar(valor:Double){ _valorSaldo+=valor println("Depósito de $valor para ${instanceTypeName()}: $numero " ) printSaldo() } override fun sacar(valor:Double){ val valorTaxa = valor*taxaDeSaque() if(temSaldo(valor)){ println(""" Saque ${instanceTypeName()} valor solicitato: $valor taxa de saque: ${taxaDeSaque()}% valor da taxa de saque: R$ ${valorTaxa} """.trimIndent()) this._valorSaldo-=valor this._valorSaldo-=valorTaxa }else{ println(""" Saque de R$ $valor não realizado por falta de saldo Saldo atual: R$ $this._valorSaldo """.trimIndent()) } printSaldo() } }
0
Kotlin
0
0
c01548ce52429782c2185d0872f2405afa6ee4c6
1,471
Santander-Bootcamp-Kotlin-Mobile-Developer-Digital-Innovation-One-2021
MIT License
app/src/main/java/dev/luchonetvv/postedarticleapp/domain/model/Article.kt
luchonetvv
403,812,391
false
null
package dev.luchonetvv.postedarticleapp.domain.model import com.google.gson.annotations.SerializedName data class Article( @SerializedName("created_at_i") var createdAtI: Long, @SerializedName("story_id") var storyId: Long, @SerializedName("title") var title: String?, @SerializedName("story_title") var storyTitle: String?, @SerializedName("url") var url: String?, @SerializedName("story_url") var storyUrl: String?, @SerializedName("author") var author: String, @SerializedName("created_at") var createdAt: String )
0
Kotlin
0
0
d3a90942ddb795e99c305ddfa9bb3fe8d06cd4a9
584
posted-article
Apache License 2.0
src/main/kotlin/no/nav/klage/util/TokenUtil.kt
navikt
253,461,869
false
null
package no.nav.klage.util import no.nav.security.token.support.core.context.TokenValidationContextHolder import no.nav.security.token.support.core.exceptions.JwtTokenValidatorException import org.springframework.stereotype.Component @Component class TokenUtil(private val ctxHolder: TokenValidationContextHolder) { companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) private val issuer = "selvbetjening" } fun getSubject(): String { val token = ctxHolder.tokenValidationContext?.getClaims(issuer) val subject = if (token?.get("pid") != null) { token.get("pid").toString() } else if (token?.subject != null) { token.subject.toString() } else { throw JwtTokenValidatorException("pid/sub not found in token") } return subject } fun getToken(): String { val token = ctxHolder.tokenValidationContext?.getJwtToken(issuer)?.tokenAsString return checkNotNull(token) { "Token must be present" } } fun getExpiry(): Long? = ctxHolder.tokenValidationContext?.getClaims(issuer)?.expirationTime?.time }
0
Kotlin
0
0
a85f6560aa3fecb7444d40b0840c27bd749a7fec
1,256
klage-dittnav-api
MIT License
leakcanary/leakcanary-core/src/test/java/leakcanary/ObjectGrowthWarmupHeapDumperTest.kt
square
34,824,499
false
null
package leakcanary import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.toByteString import org.assertj.core.api.Assertions.assertThat import org.junit.Test import shark.HprofHeader import shark.HprofWriterHelper import shark.ValueHolder import shark.dumpToBytes class ObjectGrowthWarmupHeapDumperTest { @Test fun `heap dump 1 as hex constant matches generated heap dump hex`() { assertThat(ObjectGrowthWarmupHeapDumper.heapDump1Hex(androidHeap = false)).isEqualTo(dumpGrowingListHeapAsHex(1)) } @Test fun `heap dump 2 as hex constant matches generated heap dump hex`() { assertThat(ObjectGrowthWarmupHeapDumper.heapDump2Hex(androidHeap = false)).isEqualTo(dumpGrowingListHeapAsHex(2)) } @Test fun `heap dump 3 as hex constant matches generated heap dump hex`() { assertThat(ObjectGrowthWarmupHeapDumper.heapDump3Hex(androidHeap = false)).isEqualTo(dumpGrowingListHeapAsHex(3)) } @Test fun `android heap dump 1 as hex constant matches generated heap dump hex`() { assertThat(ObjectGrowthWarmupHeapDumper.heapDump1Hex(androidHeap = true)).isEqualTo(dumpAndroidGrowingListHeapAsHex(1)) } @Test fun `android heap dump 2 as hex constant matches generated heap dump hex`() { assertThat(ObjectGrowthWarmupHeapDumper.heapDump2Hex(androidHeap = true)).isEqualTo(dumpAndroidGrowingListHeapAsHex(2)) } @Test fun `android heap dump 3 as hex constant matches generated heap dump hex`() { assertThat(ObjectGrowthWarmupHeapDumper.heapDump3Hex(androidHeap = true)).isEqualTo(dumpAndroidGrowingListHeapAsHex(3)) } private fun dumpGrowingListHeapAsHex(listItemCount: Int): String { val heapDumpTimestamp = ("0b501e7e" + "ca55e77e").decodeHex().toByteArray().toLong() return dumpToBytes(hprofHeader = HprofHeader(heapDumpTimestamp = heapDumpTimestamp)) { growingList(listItemCount) }.toByteString().hex() } private fun dumpAndroidGrowingListHeapAsHex(listItemCount: Int): String { val heapDumpTimestamp = ("0b501e7e" + "ca55e77e").decodeHex().toByteArray().toLong() return dumpToBytes(hprofHeader = HprofHeader(heapDumpTimestamp = heapDumpTimestamp)) { "android.os.Build" clazz { staticField["MANUFACTURER"] = string("M") staticField["ID"] = string("I") } "android.os.Build\$VERSION" clazz { staticField["SDK_INT"] = ValueHolder.IntHolder(42) } growingList(listItemCount) }.toByteString().hex() } private fun HprofWriterHelper.growingList(listItemCount: Int) { "Holder" clazz { val refs = (1..listItemCount).map { instance(objectClassId) }.toTypedArray() staticField["list"] = objectArray(*refs) } } private fun ByteArray.toLong(): Long { check(size == 8) var pos = 0 return (this[pos++].toLong() and 0xffL shl 56 or (this[pos++].toLong() and 0xffL shl 48) or (this[pos++].toLong() and 0xffL shl 40) or (this[pos++].toLong() and 0xffL shl 32) or (this[pos++].toLong() and 0xffL shl 24) or (this[pos++].toLong() and 0xffL shl 16) or (this[pos++].toLong() and 0xffL shl 8) or (this[pos].toLong() and 0xffL)) } }
81
null
3958
29,180
5738869542af44bdfd8224603eac7af82327b054
3,165
leakcanary
Apache License 2.0
adventure/src/main/kotlin/com/briarcraft/adventure/event/RegenerateLootEventListener.kt
toddharrison
581,553,858
false
null
package com.briarcraft.adventure.event import com.destroystokyo.paper.loottable.LootableInventory import com.github.shynixn.mccoroutine.bukkit.launch import com.github.shynixn.mccoroutine.bukkit.ticks import kotlinx.coroutines.delay import org.bukkit.block.Barrel import org.bukkit.block.Chest import org.bukkit.block.ShulkerBox import org.bukkit.entity.minecart.StorageMinecart import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.world.LootGenerateEvent import org.bukkit.inventory.InventoryHolder import org.bukkit.plugin.Plugin class RegenerateLootEventListener(private val plugin: Plugin): Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) suspend fun on(event: LootGenerateEvent) { when (val holder = event.inventoryHolder) { is StorageMinecart -> { checkForRefill(event, holder) waitForInventoryClose(holder) { holder.lootTable = event.lootTable } } is Chest, is ShulkerBox, is Barrel -> { holder.inventory.clear() } } } private fun <T> checkForRefill(event: LootGenerateEvent, holder: T) where T: InventoryHolder, T: LootableInventory { val now = System.currentTimeMillis() val remaining = holder.nextRefill - now if (remaining > 0) { event.isCancelled = true } else { holder.inventory.clear() holder.nextRefill = now + 1000 * 60 // TODO Generate from config } } private suspend fun waitForInventoryClose(holder: InventoryHolder, action: () -> Unit) { plugin.launch { do { delay(1.ticks) } while (holder.inventory.viewers.isNotEmpty()) action() } } }
0
Kotlin
1
4
80528c8dbea16f3f7e3058785351eaba027c23a8
1,917
BriarCode
MIT License
src/main/kotlin/io/ysakhno/adventofcode2015/day15/Day15.kt
YSakhno
816,649,625
false
{"Kotlin": 93259}
/* * --- Day 15: Science for Hungry People --- * * Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right * balance of ingredients. * * Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you * could use to finish the recipe (your puzzle input) and their properties per teaspoon: * * - capacity (how well it helps the cookie absorb milk) * - durability (how well it keeps the cookie intact when full of milk) * - flavor (how tasty it makes the cookie) * - texture (how it improves the feel of the cookie) * - calories (how many calories it adds to the cookie) * * You can only measure ingredients in whole-teaspoon amounts accurately, and you have to be accurate so you can * reproduce your results in the future. The total score of a cookie can be found by adding up each of the properties * (negative totals become 0) and then multiplying together everything except calories. * * For instance, suppose you have these two ingredients: * * Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8 * Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3 * * Then, choosing to use 44 teaspoons of butterscotch and 56 teaspoons of cinnamon (because the amounts of each * ingredient must add up to 100) would result in a cookie with the following properties: * * - A capacity of 44*-1 + 56*2 = 68 * - A durability of 44*-2 + 56*3 = 80 * - A flavor of 44*6 + 56*-2 = 152 * - A texture of 44*3 + 56*-1 = 76 * * Multiplying these together (68 * 80 * 152 * 76, ignoring calories for now) results in a total score of 62842880, * which happens to be the best score possible given these ingredients. If any properties had produced a negative * total, it would have instead become zero, causing the whole score to multiply to zero. * * Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you * can make? * * --- Part Two --- * * Your cookie recipe becomes wildly popular! Someone asks if you can make another recipe that has exactly 500 calories * per cookie (so they can use it as a meal replacement). Keep the rest of your award-winning process the same * (100 teaspoons, same ingredients, same scoring system). * * For example, given the ingredients above, if you had instead selected 40 teaspoons of butterscotch and 60 teaspoons * of cinnamon (which still adds to 100), the total calorie count would be 40*8 + 60*3 = 500. The total score would go * down, though: only 57600000, the best you can do in such trying circumstances. * * Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you * can make with a calorie total of 500? */ package io.ysakhno.adventofcode2015.day15 import io.ysakhno.adventofcode2015.util.ProblemInput import io.ysakhno.adventofcode2015.util.allInts import io.ysakhno.adventofcode2015.util.println import org.junit.jupiter.api.Assertions.assertEquals private val problemInput = object : ProblemInput {} private data class Ingredient( val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int, ) { val score get() = capacity * durability * flavor * texture } private fun parseIngredient(line: String): Ingredient { val name = line.split(':').first() val (capacity, durability, flavor, texture, calories) = line.allInts().toList() return Ingredient(name, capacity, durability, flavor, texture, calories) } private fun generateCounts(number: Int): Sequence<List<Int>> { val counts = IntArray(number) return sequence { do { yield(counts.toList()) for (i in counts.lastIndex downTo 0) { if (counts[i] != 100) { ++counts[i] break } else { counts[i] = 0 } } } while (!counts.all { it == 0 }) } } private fun bakeCookie(recipe: List<Pair<Ingredient, Int>>) = recipe.fold(Ingredient("Cookie", 0, 0, 0, 0, 0)) { cookie, (ingredient, spoons) -> cookie.copy( capacity = cookie.capacity + ingredient.capacity * spoons, durability = cookie.durability + ingredient.durability * spoons, flavor = cookie.flavor + ingredient.flavor * spoons, texture = cookie.texture + ingredient.texture * spoons, calories = cookie.calories + ingredient.calories * spoons, ) }.let { it.copy( capacity = it.capacity.coerceAtLeast(0), durability = it.durability.coerceAtLeast(0), flavor = it.flavor.coerceAtLeast(0), texture = it.texture.coerceAtLeast(0), ) } private fun solveWithFilter(input: List<String>, predicate: (Ingredient) -> Boolean = { true }): Int { val ingredients = input.map(::parseIngredient) return generateCounts(ingredients.size) .filter { it.sum() == 100 } .map(ingredients::zip) .map(::bakeCookie) .filter(predicate) .maxOf(Ingredient::score) } private fun part1(input: List<String>) = solveWithFilter(input) private fun part2(input: List<String>) = solveWithFilter(input) { it.calories == 500 } fun main() { // Test if implementation meets criteria from the description val testInput = problemInput.readTest() assertEquals(62_842_880, part1(testInput), "Part one (sample input)") assertEquals(57_600_000, part2(testInput), "Part two (sample input)") println("All tests passed") val input = problemInput.read() part1(input).println() part2(input).println() }
0
Kotlin
0
0
200685847c7abf2e66f6af95cb3982a8b42713b4
5,830
advent-of-code-2015-in-kotlin
MIT License
src/main/kotlin/no/oyvindis/kafkaproducerclimate/service/ClimateService.kt
oyvindis
532,031,323
false
{"Kotlin": 7068, "Dockerfile": 208}
package no.oyvindis.kafkaproducerclimate.service import no.oyvindis.kafkaproducerclimate.entities.Sensor import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.kafka.core.KafkaTemplate import org.springframework.kafka.support.KafkaHeaders import org.springframework.messaging.Message import org.springframework.messaging.support.MessageBuilder import org.springframework.scheduling.annotation.Scheduled import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.bodyToMono private val logger: Logger = LoggerFactory.getLogger(ClimateService::class.java) class AirthingsResponse { val data: Sensor? = null } @Service class ClimateService( private val webClient: WebClient, @Autowired val kafkaTemplate: KafkaTemplate<String, Any>, @Value("\${kafka.topics.sensor}") val topic: String, ) { @Scheduled(fixedDelay = 900000) fun postReadingFromAirthings() { try { logger.debug("postReadingFromAirthings") val data = webClient .get() .uri("https://ext-api.airthings.com/v1/devices/2960009475/latest-samples") .attributes( ServerOAuth2AuthorizedClientExchangeFilterFunction .clientRegistrationId("airthings") ) .retrieve() .bodyToMono<AirthingsResponse>() val responseStr = data.block() val sensorReading: Sensor? = responseStr?.data sensorReading?.location = "2960009475" sensorReading?.let { val message: Message<Sensor?> = MessageBuilder .withPayload(sensorReading) .setHeader(KafkaHeaders.TOPIC, topic) .build() kafkaTemplate.send(message) logger.info("Message sent with success") } } catch (e: Exception) { logger.error("Exception: {}", e) } } }
2
Kotlin
0
1
4c1096289690804cca89caaa256a88c4bbf7f3fb
2,337
kafka-producer-climate
Apache License 2.0
mobile/src/main/java/never/ending/splendor/app/utils/util.kt
AndrewReitz
222,597,616
true
{"Kotlin": 249060, "HTML": 28014}
package never.ending.splendor.app.utils import java.util.Collections // junk drawer for code. /** Returns an immutable copy of this. */ fun <T> List<T>.toImmutableList(): List<T> = Collections.unmodifiableList(toList())
10
Kotlin
0
4
c01c7be00045c87bb869d9d3ecd6277ca0bed033
223
never-ending-splendor
Apache License 2.0
mobile/src/main/java/never/ending/splendor/app/utils/util.kt
AndrewReitz
222,597,616
true
{"Kotlin": 249060, "HTML": 28014}
package never.ending.splendor.app.utils import java.util.Collections // junk drawer for code. /** Returns an immutable copy of this. */ fun <T> List<T>.toImmutableList(): List<T> = Collections.unmodifiableList(toList())
10
Kotlin
0
4
c01c7be00045c87bb869d9d3ecd6277ca0bed033
223
never-ending-splendor
Apache License 2.0
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/request/TLRequestInvokeWithLayer.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api.request import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32 import com.github.badoualy.telegram.tl.core.TLMethod import com.github.badoualy.telegram.tl.core.TLObject import com.github.badoualy.telegram.tl.serialization.TLDeserializer import com.github.badoualy.telegram.tl.serialization.TLSerializer import java.io.IOException /** * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLRequestInvokeWithLayer<T : TLObject>() : TLMethod<T>() { var layer: Int = 0 var query: TLMethod<T>? = null private val _constructor: String = "invokeWithLayer#da9b0d0d" override val constructorId: Int = CONSTRUCTOR_ID constructor(layer: Int, query: TLMethod<T>?) : this() { this.layer = layer this.query = query } @Throws(IOException::class) override fun deserializeResponse_(tlDeserializer: TLDeserializer): T = query!!.deserializeResponse(tlDeserializer) @Throws(IOException::class) override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) { writeInt(layer) writeTLMethod(query!!) } @Throws(IOException::class) override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) { layer = readInt() query = readTLMethod() } override fun computeSerializedSize(): Int { var size = SIZE_CONSTRUCTOR_ID size += SIZE_INT32 size += query!!.computeSerializedSize() return size } override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLRequestInvokeWithLayer<*>) return false if (other === this) return true return layer == other.layer && query == other.query } companion object { const val CONSTRUCTOR_ID: Int = 0xda9b0d0d.toInt() } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
2,032
kotlogram-resurrected
MIT License
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/request/TLRequestInvokeWithLayer.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api.request import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32 import com.github.badoualy.telegram.tl.core.TLMethod import com.github.badoualy.telegram.tl.core.TLObject import com.github.badoualy.telegram.tl.serialization.TLDeserializer import com.github.badoualy.telegram.tl.serialization.TLSerializer import java.io.IOException /** * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLRequestInvokeWithLayer<T : TLObject>() : TLMethod<T>() { var layer: Int = 0 var query: TLMethod<T>? = null private val _constructor: String = "invokeWithLayer#da9b0d0d" override val constructorId: Int = CONSTRUCTOR_ID constructor(layer: Int, query: TLMethod<T>?) : this() { this.layer = layer this.query = query } @Throws(IOException::class) override fun deserializeResponse_(tlDeserializer: TLDeserializer): T = query!!.deserializeResponse(tlDeserializer) @Throws(IOException::class) override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) { writeInt(layer) writeTLMethod(query!!) } @Throws(IOException::class) override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) { layer = readInt() query = readTLMethod() } override fun computeSerializedSize(): Int { var size = SIZE_CONSTRUCTOR_ID size += SIZE_INT32 size += query!!.computeSerializedSize() return size } override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLRequestInvokeWithLayer<*>) return false if (other === this) return true return layer == other.layer && query == other.query } companion object { const val CONSTRUCTOR_ID: Int = 0xda9b0d0d.toInt() } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
2,032
kotlogram-resurrected
MIT License
browser-kotlin/src/jsMain/kotlin/web/payment/PaymentOptions.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.payment import kotlinx.js.JsPlainObject @JsPlainObject external interface PaymentOptions { val requestPayerEmail: Boolean? val requestPayerName: Boolean? val requestPayerPhone: Boolean? val requestShipping: Boolean? val shippingType: PaymentShippingType? }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
336
types-kotlin
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/client/nonassociationsapi/api/extensions/PrisonerNonAssociationExt.kt
ministryofjustice
533,838,017
false
{"Kotlin": 3274121, "Shell": 11230, "Dockerfile": 1490}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.client.nonassociationsapi.api.extensions import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.client.nonassociationsapi.model.PrisonerNonAssociation import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model.suitability.nonassociation.NonAssociationDetails import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model.suitability.nonassociation.OtherPrisonerDetails import java.time.LocalDateTime fun PrisonerNonAssociation.toModel() = NonAssociationDetails( reasonCode = this.reason.toString(), reasonDescription = this.reasonDescription, otherPrisonerDetails = with(this.otherPrisonerDetails) { OtherPrisonerDetails( prisonerNumber = this.prisonerNumber, firstName = this.firstName, lastName = this.lastName, cellLocation = this.cellLocation, ) }, whenCreated = LocalDateTime.parse(this.whenCreated), comments = this.comment, )
4
Kotlin
0
1
af0af6f344301d28db35d7b67e3c624fd31148d4
976
hmpps-activities-management-api
MIT License
src/main/kotlin/me/samboycoding/sambotv6/orm/tables/CustomRoles.kt
SamboyCoding
214,277,724
false
null
package me.samboycoding.sambotv6.orm.tables import me.liuwj.ktorm.dsl.eq import me.liuwj.ktorm.entity.add import me.liuwj.ktorm.entity.find import me.liuwj.ktorm.schema.Table import me.liuwj.ktorm.schema.int import me.liuwj.ktorm.schema.varchar import me.samboycoding.sambotv6.SambotV6 import me.samboycoding.sambotv6.customRoles import me.samboycoding.sambotv6.guildConfigurations import me.samboycoding.sambotv6.orm.entities.CustomRole import me.samboycoding.sambotv6.orm.entities.GuildConfiguration import net.dv8tion.jda.api.entities.Role object CustomRoles : Table<CustomRole>("CustomRoles") { val actualId = int("idReal").primaryKey() val id = varchar("id").bindTo { it.tag } //VARCHAR(100) val roleId = varchar("roleId").bindTo { it.roleId } //VARCHAR(32) val guild = varchar("guildId").references(GuildConfigurations) { it.guildConfig } //VARCHAR(32) FOREIGN KEY GuildConfigurations:GUILD_ID fun createForRole(role: Role, tag: String): CustomRole { val new = CustomRole { this.role = role this.tag = tag this.guildConfig = SambotV6.instance.db.guildConfigurations.find { it.id eq role.guild.id } ?: GuildConfigurations.makeDefault(role.guild) } SambotV6.instance.db.customRoles.add(new) return new } fun createForRole(roleId: String, tag: String, config: GuildConfiguration): CustomRole { val new = CustomRole { this.roleId = roleId this.tag = tag this.guildConfig = config } SambotV6.instance.db.customRoles.add(new) return new } }
0
Kotlin
0
2
8c3f96b8ec14422c92312d6d6c68083c258d2f27
1,632
SambotV6
Apache License 2.0
imageclassification/src/main/java/com/hms/lib/commonmobileservices/imageclassification/implementation/HuaweiImageClassification.kt
Explore-In-HMS
402,745,331
false
{"Kotlin": 593917}
// Copyright 2020. Explore in HMS. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // 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.hms.lib.commonmobileservices.imageclassification.implementation import android.graphics.Bitmap import com.hms.lib.commonmobileservices.core.ErrorModel import com.hms.lib.commonmobileservices.imageclassification.common.ClassificationResult import com.hms.lib.commonmobileservices.imageclassification.common.ImageLabel import com.huawei.hms.mlsdk.classification.MLImageClassificationAnalyzer import com.huawei.hms.mlsdk.common.MLFrame class HuaweiImageClassification( private val analyzer: MLImageClassificationAnalyzer ) : IImageClassification { override fun analyseImage( bitmap: Bitmap, callback: (classificationResult: ClassificationResult<List<ImageLabel>>) -> Unit ) { val frame = MLFrame.fromBitmap(bitmap) analyzer.asyncAnalyseFrame(frame) .addOnSuccessListener { classification -> callback( ClassificationResult.Success( classification.map { ImageLabel( name = it.name, possibility = it.possibility ) } ) ) }.addOnFailureListener { e -> callback( ClassificationResult.Error( errorMessage = e.localizedMessage, errorModel = ErrorModel( message = e.message, exception = e ) ) ) } } override fun stopAnalyzer() { analyzer.stop() } }
3
Kotlin
6
50
68640eadd9950bbdd9aac52dad8d22189a301859
2,297
common-mobile-services
Apache License 2.0
src/test/kotlin/net/dunciboy/discord_bot/CaseSystemTest.kt
alfonsojon
100,499,288
false
null
/* * Copyright 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. */ import net.dunciboy.discord_bot.CaseSystem import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.RepeatedTest import java.io.IOException /** * Created by Duncan on 28/06/2017. */ internal class CaseSystemTest { @DisplayName("net.dunciboy.discord_bot.Test requesting numbers") @RepeatedTest(5) @Throws(IOException::class) fun requestCaseNumberTest() { println(CaseSystem(-99).newCaseNumber) } @DisplayName("net.dunciboy.discord_bot.Test if reset of count works") @RepeatedTest(2) fun resetTest() { CaseSystem(-99).reset() } }
1
null
1
1
5fa24db82729121561ae44a757427b61047a3032
1,189
JDADiscordBot
Apache License 2.0
data/core/src/main/java/com/gnoemes/shimori/data/core/sources/UserDataSource.kt
gnoemes
213,210,354
false
{"Kotlin": 788446, "Shell": 2974}
package com.gnoemes.shimori.data.core.sources import com.gnoemes.shimori.data.core.entities.user.User interface UserDataSource { suspend fun getMyUser(): User suspend fun getUser(id: Long): User }
0
Kotlin
1
31
7bf5caccb92d3c789ecd3f1c8a6d3a7eeb4d408b
209
Shimori
Apache License 2.0
Application/app/src/main/java/com/istudio/distancetracker/features/map/presentation/state/MapStates.kt
devrath
570,594,617
false
{"Kotlin": 238294}
package com.istudio.distancetracker.features.map.presentation.state import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.LatLngBounds import com.google.android.gms.maps.model.PolylineOptions import com.istudio.core_common.ui.uiEvent.UiText import com.istudio.distancetracker.features.map.domain.entities.outputs.CalculateResultOutput sealed class MapStates { //object OnSubmitClick : MapStates() data class ShowErrorMessage(val message: UiText) : MapStates() data class JourneyResult(val result: CalculateResultOutput) : MapStates() data class AnimateCamera(val location: LatLng) : MapStates() data class AnimateCameraForBiggerPitchure(val bounds: LatLngBounds, val padding:Int, val duration:Int) : MapStates() data class AddPolyline(val polyLine: PolylineOptions) : MapStates() data class FollowCurrentLocation(val location: LatLng, val duration:Int) : MapStates() data class AddMarker(val location: LatLng) : MapStates() object DisplayStartButton : MapStates() object DisableStopButton : MapStates() object LaunchInAppReview : MapStates() object CounterGoState : MapStates() object CounterFinishedState : MapStates() data class CounterCountDownState(val currentSecond: String) : MapStates() }
0
Kotlin
3
6
17d03b535e2ced992b97cc1e3a6d40c5393afded
1,293
Distance-Tracker
Apache License 2.0
app/src/main/java/coloring/com/ccb/ui/view/UserLockBottomSheetBehavior.kt
SeungYongSon
214,967,245
false
{"Java": 45681, "Kotlin": 25476}
package coloring.com.ccb.ui.view import android.content.Context import android.util.AttributeSet import androidx.coordinatorlayout.widget.CoordinatorLayout import android.view.MotionEvent import android.view.View import com.google.android.material.bottomsheet.BottomSheetBehavior class UserLockBottomSheetBehavior<V : View>(context: Context?, attrs: AttributeSet?) : BottomSheetBehavior<V>(context, attrs) { override fun onInterceptTouchEvent(parent: CoordinatorLayout, child: V, event: MotionEvent): Boolean { return false } override fun onTouchEvent(parent: CoordinatorLayout, child: V, event: MotionEvent): Boolean { return false } override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: V, directTargetChild: View, target: View, axes: Int, type: Int): Boolean { return false } override fun onNestedFling(coordinatorLayout: CoordinatorLayout, child: V, target: View, velocityX: Float, velocityY: Float, consumed: Boolean): Boolean { return false } }
0
Java
1
0
5518ed8ecf4702162809933de9488f871aa58a33
1,045
Camera-Coloring-Book
MIT License
app/src/main/java/org/tokend/template/data/repository/base/MemoryOnlyRepositoryCache.kt
krisguo
235,389,048
true
{"Kotlin": 940181, "HTML": 55444, "Java": 9720}
package org.tokend.template.data.repository.base /** * Repository cache without persistence */ open class MemoryOnlyRepositoryCache<T> : RepositoryCache<T>() { override fun isContentSame(first: T, second: T): Boolean = false override fun getAllFromDb(): List<T> = emptyList() override fun addToDb(items: List<T>) {} override fun updateInDb(items: List<T>) {} override fun deleteFromDb(items: List<T>) {} override fun clearDb() {} }
0
Kotlin
0
0
e33576eb5bbe360fab3bec74fd52f9c2efb67b3d
463
android-client
Apache License 2.0
sample/src/main/kotlin/cz/levinzonr/roxiesample/presentation/notelist/NoteListFragment.kt
levinzonr
201,771,827
true
{"Kotlin": 9353, "Ruby": 4308}
/* * Copyright (C) 2019. WW International, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cz.levinzonr.roxiesample.presentation.notelist import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import cz.levinzonr.roxiesample.R import cz.levinzonr.roxiesample.domain.AddNoteInteractor import cz.levinzonr.roxiesample.domain.DeleteNoteInteractor import cz.levinzonr.roxiesample.domain.GetNotesInteractor import cz.levinzonr.roxiesample.domain.Note import kotlinx.android.synthetic.main.note_list.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach class NoteListFragment : Fragment() { private val clickListener: ClickListener = this::onNoteClicked private val recyclerViewAdapter = NoteAdapter(clickListener) companion object { fun newInstance() = NoteListFragment() } private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) private lateinit var viewModel: NoteListViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.note_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() // Normally ViewModelFactory should be injected here along with its UseCases injected into it viewModel = ViewModelProviders.of( this, NoteListViewModelFactory( null, GetNotesInteractor(), DeleteNoteInteractor(), AddNoteInteractor() ) ).get(NoteListViewModel::class.java) viewModel.stateFlow.onEach { state -> renderState(state) }.launchIn(scope) viewModel.eventFlow.onEach { Toast.makeText( requireContext(), "Note Added", Toast.LENGTH_SHORT).show() }.launchIn(scope) addNoteBtn.setOnClickListener { viewModel.dispatch(Action.AddNote("Test")) } } override fun onDestroyView() { super.onDestroyView() scope.cancel() } private fun renderState(state: State) { with(state) { when { isLoading -> renderLoadingState() isError -> renderErrorState() else -> renderNotesState(notes) } } } private fun renderLoadingState() { loadingIndicator.visibility = View.VISIBLE } private fun renderErrorState() { loadingIndicator.visibility = View.GONE Toast.makeText(requireContext(), R.string.error_loading_notes, Toast.LENGTH_LONG).show() } private fun renderNotesState(notes: List<Note>) { loadingIndicator.visibility = View.GONE recyclerViewAdapter.updateNotes(notes) notesRecyclerView.visibility = View.VISIBLE } private fun setupRecyclerView() { notesRecyclerView.layoutManager = LinearLayoutManager(requireContext()) notesRecyclerView.adapter = recyclerViewAdapter notesRecyclerView.setHasFixedSize(true) } private fun onNoteClicked(note: Note) { viewModel.dispatch(Action.DeleteNote(note)) } }
0
Kotlin
0
0
a9d97ffea99c8a09a5a9b279082caacbc02474e6
4,084
roxie-coroutines
Apache License 2.0
android/src/main/kotlin/com/pisey/flutter_native_player/download/download_service/DownloadTracker.kt
Pisey-Nguon
447,498,894
false
{"Dart": 199204, "Kotlin": 56893, "Swift": 23228, "Ruby": 2350, "Objective-C": 786}
package com.pisey.flutter_native_player.download.download_service import android.content.Context import android.net.Uri import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.offline.Download import com.google.android.exoplayer2.offline.DownloadIndex import com.google.android.exoplayer2.offline.DownloadManager import com.google.android.exoplayer2.offline.DownloadRequest import com.google.android.exoplayer2.upstream.HttpDataSource import com.google.android.exoplayer2.util.Assertions import com.google.android.exoplayer2.util.Log import java.io.IOException import java.util.* import java.util.concurrent.CopyOnWriteArraySet /** Tracks media that has been downloaded. */ class DownloadTracker( context: Context, httpDataSourceFactory: HttpDataSource.Factory?, downloadManager: DownloadManager? ) { /** Listens for changes in the tracked downloads. */ interface Listener { /** Called when the tracked downloads changed. */ fun onDownloadsChanged() } private val context: Context private val httpDataSourceFactory: HttpDataSource.Factory? private val listeners: CopyOnWriteArraySet<Listener> private val downloads: HashMap<Uri, Download> private val downloadIndex: DownloadIndex fun addListener(listener: Listener) { Assertions.checkNotNull(listener) listeners.add(listener) } fun removeListener(listener: Listener) { listeners.remove(listener) } fun isDownloaded(mediaItem: MediaItem): Boolean { val download = downloads[Assertions.checkNotNull(mediaItem.localConfiguration).uri] return download != null && download.state != Download.STATE_FAILED } fun getDownloadRequest(uri: Uri): DownloadRequest? { val download = downloads[uri] return if (download != null && download.state != Download.STATE_FAILED) download.request else null } private fun loadDownloads() { try { downloadIndex.getDownloads().use { loadedDownloads -> while (loadedDownloads.moveToNext()) { val download = loadedDownloads.download downloads[download.request.uri] = download } } } catch (e: IOException) { Log.w(TAG, "Failed to query downloads", e) } } private inner class DownloadManagerListener : DownloadManager.Listener { override fun onDownloadChanged( downloadManager: DownloadManager, download: Download, finalException: Exception? ) { downloads[download.request.uri] = download for (listener in listeners) { listener.onDownloadsChanged() } } override fun onDownloadRemoved(downloadManager: DownloadManager, download: Download) { downloads.remove(download.request.uri) for (listener in listeners) { listener.onDownloadsChanged() } } } companion object { private const val TAG = "DownloadTracker" } init { this.context = context.applicationContext this.httpDataSourceFactory = httpDataSourceFactory listeners = CopyOnWriteArraySet() downloads = HashMap() downloadIndex = downloadManager!!.downloadIndex downloadManager.addListener(DownloadManagerListener()) loadDownloads() } }
0
Dart
0
6
5b42987628ff5ac47b44f3788acdce531cf958e0
3,431
Flutter_Native_Player
MIT License
plot-config/src/commonMain/kotlin/jetbrains/datalore/plot/config/transform/encode/ServerSideEncodeChange.kt
paddlelaw
369,508,598
true
{"Kotlin": 5076335, "Python": 760241, "C": 2832, "CSS": 1948, "Shell": 1773, "JavaScript": 1048}
/* * 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.datalore.plot.config.transform.encode import jetbrains.datalore.plot.config.transform.SpecChange import jetbrains.datalore.plot.config.transform.SpecChangeContext internal class ServerSideEncodeChange : SpecChange { override fun apply(spec: MutableMap<String, Any>, ctx: SpecChangeContext) { jetbrains.datalore.plot.FeatureSwitch.printEncodedDataSummary("DataFrameOptionHelper.encodeUpdateOption", spec) @Suppress("ConstantConditionIf") if (jetbrains.datalore.plot.FeatureSwitch.USE_DATA_FRAME_ENCODING) { val encoded = DataFrameEncoding.encode1(spec) spec.clear() spec.putAll(encoded) } } }
0
null
0
0
c1f6b678cf58aa9499542b863f6da93cfb854604
834
lets-plot
MIT License
shared/data/models/src/commonMain/kotlin/io/afalabarce/template/kmm/models/features/example/remote/RemoteExampleEntity.kt
afalabarce
767,763,918
false
{"Kotlin": 76194, "Swift": 684}
package io.afalabarce.template.kmm.models.features.example.remote import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class RemoteExampleEntity( @SerialName("id") val remoteId: Long, @SerialName("title") val remoteTitle: String, @SerialName("description") val remoteDescription: String )
0
Kotlin
2
51
0c071ce4d275c27dfe8f2382ce0003cb88fc50df
363
kmm-template
MIT License
ontrack-ui-graphql/src/test/java/net/nemerosa/ontrack/graphql/support/Entity.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.graphql.support data class Entity( val type: EntityType, val id: Int, )
57
Kotlin
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
109
ontrack
MIT License
app/src/main/java/com/karimi/seller/api/ApiService.kt
karimi96
520,105,490
false
null
package com.karimi.seller.api import com.karimi.seller.model.ResponseBusinessSample import com.karimi.seller.model.ResponseData import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path interface ApiService { @GET("business_sample.json") fun getBusinessSample(): Call<ResponseData<ResponseBusinessSample>> @GET("{url}") fun getBusinessSample(@Path("url") url: String ): Call<ResponseData<ResponseBusinessSample>> }
0
Kotlin
0
0
dde24d07b705b893e799a24c97ef15e340312251
450
Seller
MIT License
app/src/main/java/com/sudzusama/comparephones/data/source/network/CPApiService.kt
Anothery
234,905,404
false
null
package com.sudzusama.comparephones.data.source.network import com.sudzusama.comparephones.data.model.DeviceEntity import io.reactivex.Single import retrofit2.http.GET import retrofit2.http.Query interface CPApiService { @GET("getdevice") fun getDevices( @Query("device") deviceName: String ): Single<List<DeviceEntity>> }
0
Kotlin
0
1
9a3b58b033c9da5b79db0d17e39ab525b4af3659
345
phone-specs
Apache License 2.0
cabret-log/src/commonMain/kotlin/de/jensklingenberg/cabret/Log.kt
PXNX
326,745,151
true
{"Kotlin": 28932, "Swift": 6247}
package de.jensklingenberg.cabret import kotlin.native.concurrent.ThreadLocal @Target(AnnotationTarget.FUNCTION) annotation class DebugLog(val logLevel: Cabret.LogLevel = Cabret.LogLevel.DEBUG,val tag:String="") @ThreadLocal object LogHandler { private var listener: Cabret.Listener = DefaultListener() fun onLog(tag: String, name: String, logLevel: String) { val serv = Cabret.LogLevel.valueOf(logLevel) listener.log(tag, name, serv) } fun addListener(listener: Cabret.Listener) { this.listener = listener } /** * This is used to log the retun values */ fun <T> logReturn(tag: String, returnObject: T, logLevel: String): T { onLog(tag, returnObject.toString(), logLevel) return returnObject } fun removeListener() { listener = DefaultListener() } } expect class DefaultListener() : Cabret.Listener { override fun log(tag: String, msg: String, logLevel: Cabret.LogLevel) } class CommonListener : Cabret.Listener { override fun log(tag: String, msg: String, logLevel: Cabret.LogLevel) { println(tag + " " + msg) } } object Cabret { enum class LogLevel { VERBOSE, DEBUG, INFO, WARN, ERROR } interface Listener { fun log(tag: String, msg: String, logLevel: Cabret.LogLevel) } fun addListener(listener: Cabret.Listener) { LogHandler.addListener(listener) } fun removeListener() { LogHandler.removeListener() } }
0
null
0
1
1f3bf5e1a6732ca88c83e49b6ce93687f67078ef
1,508
Cabret-Log
Apache License 2.0
navigation/navigation-common/src/main/java/androidx/navigation/serialization/NavTypeConverter.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2024 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. */ @file:OptIn(ExperimentalSerializationApi::class) package androidx.navigation.serialization import android.net.Uri import android.os.Bundle import androidx.navigation.CollectionNavType import androidx.navigation.NavType import java.io.Serializable import kotlin.reflect.KType import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.descriptors.SerialKind import kotlinx.serialization.serializerOrNull /** Marker for Native Kotlin types with either full or partial built-in NavType support */ private enum class InternalType { INT, INT_NULLABLE, BOOL, BOOL_NULLABLE, DOUBLE, DOUBLE_NULLABLE, FLOAT, FLOAT_NULLABLE, LONG, LONG_NULLABLE, STRING, STRING_NULLABLE, INT_ARRAY, BOOL_ARRAY, DOUBLE_ARRAY, FLOAT_ARRAY, LONG_ARRAY, ARRAY, LIST, ENUM, ENUM_NULLABLE, UNKNOWN } /** * Converts an argument type to a built-in NavType. * * Built-in NavTypes include NavType objects declared within [NavType.Companion], such as * [NavType.IntType], [NavType.BoolArrayType] etc. * * Returns [UNKNOWN] type if the argument does not have built-in NavType support. */ internal fun SerialDescriptor.getNavType(): NavType<*> { val type = when (this.toInternalType()) { InternalType.INT -> NavType.IntType InternalType.INT_NULLABLE -> InternalNavType.IntNullableType InternalType.BOOL -> NavType.BoolType InternalType.BOOL_NULLABLE -> InternalNavType.BoolNullableType InternalType.DOUBLE -> InternalNavType.DoubleType InternalType.DOUBLE_NULLABLE -> InternalNavType.DoubleNullableType InternalType.FLOAT -> NavType.FloatType InternalType.FLOAT_NULLABLE -> InternalNavType.FloatNullableType InternalType.LONG -> NavType.LongType InternalType.LONG_NULLABLE -> InternalNavType.LongNullableType InternalType.STRING -> InternalNavType.StringNonNullableType InternalType.STRING_NULLABLE -> NavType.StringType InternalType.INT_ARRAY -> NavType.IntArrayType InternalType.BOOL_ARRAY -> NavType.BoolArrayType InternalType.DOUBLE_ARRAY -> InternalNavType.DoubleArrayType InternalType.FLOAT_ARRAY -> NavType.FloatArrayType InternalType.LONG_ARRAY -> NavType.LongArrayType InternalType.ARRAY -> { val typeParameter = getElementDescriptor(0).toInternalType() when (typeParameter) { InternalType.STRING -> NavType.StringArrayType InternalType.STRING_NULLABLE -> InternalNavType.StringNullableArrayType else -> UNKNOWN } } InternalType.LIST -> { val typeParameter = getElementDescriptor(0).toInternalType() when (typeParameter) { InternalType.INT -> NavType.IntListType InternalType.BOOL -> NavType.BoolListType InternalType.DOUBLE -> InternalNavType.DoubleListType InternalType.FLOAT -> NavType.FloatListType InternalType.LONG -> NavType.LongListType InternalType.STRING -> NavType.StringListType InternalType.STRING_NULLABLE -> InternalNavType.StringNullableListType else -> UNKNOWN } } InternalType.ENUM -> NavType.parseSerializableOrParcelableType(getClass(), false) ?: UNKNOWN InternalType.ENUM_NULLABLE -> { val clazz = getClass() if (Enum::class.java.isAssignableFrom(clazz)) { @Suppress("UNCHECKED_CAST") InternalNavType.EnumNullableType(clazz as Class<Enum<*>?>) } else UNKNOWN } else -> UNKNOWN } return type } /** * Convert SerialDescriptor to an InternalCommonType. * * The descriptor's associated argument could be any of the native Kotlin types supported in * [InternalType], or it could be an unsupported type (custom class, object or enum). */ private fun SerialDescriptor.toInternalType(): InternalType { val serialName = serialName.replace("?", "") return when { kind == SerialKind.ENUM -> if (isNullable) InternalType.ENUM_NULLABLE else InternalType.ENUM serialName == "kotlin.Int" -> if (isNullable) InternalType.INT_NULLABLE else InternalType.INT serialName == "kotlin.Boolean" -> if (isNullable) InternalType.BOOL_NULLABLE else InternalType.BOOL serialName == "kotlin.Double" -> if (isNullable) InternalType.DOUBLE_NULLABLE else InternalType.DOUBLE serialName == "kotlin.Float" -> if (isNullable) InternalType.FLOAT_NULLABLE else InternalType.FLOAT serialName == "kotlin.Long" -> if (isNullable) InternalType.LONG_NULLABLE else InternalType.LONG serialName == "kotlin.String" -> if (isNullable) InternalType.STRING_NULLABLE else InternalType.STRING serialName == "kotlin.IntArray" -> InternalType.INT_ARRAY serialName == "kotlin.DoubleArray" -> InternalType.DOUBLE_ARRAY serialName == "kotlin.BooleanArray" -> InternalType.BOOL_ARRAY serialName == "kotlin.FloatArray" -> InternalType.FLOAT_ARRAY serialName == "kotlin.LongArray" -> InternalType.LONG_ARRAY serialName == "kotlin.Array" -> InternalType.ARRAY // serial name for both List and ArrayList serialName.startsWith("kotlin.collections.ArrayList") -> InternalType.LIST // custom classes or other types without built-in NavTypes else -> InternalType.UNKNOWN } } private fun SerialDescriptor.getClass(): Class<*> { var className = serialName.replace("?", "") // first try to get class with original class name try { return Class.forName(className) } catch (_: ClassNotFoundException) {} // Otherwise, it might be nested Class. Try incrementally replacing last `.` with `$` // until we find the correct enum class name. while (className.contains(".")) { className = Regex("(\\.+)(?!.*\\.)").replace(className, "\\$") try { return Class.forName(className) } catch (_: ClassNotFoundException) {} } var errorMsg = "Cannot find class with name \"$serialName\". Ensure that the " + "serialName for this argument is the default fully qualified name" if (kind is SerialKind.ENUM) { errorMsg = "$errorMsg.\nIf the build is minified, try annotating the Enum class with \"androidx.annotation.Keep\" to ensure the Enum is not removed." } throw IllegalArgumentException(errorMsg) } /** * Match the [SerialDescriptor] of a type to a KType * * Returns true if match, false otherwise. */ internal fun SerialDescriptor.matchKType(kType: KType): Boolean { if (this.isNullable != kType.isMarkedNullable) return false val kTypeSerializer = serializerOrNull(kType) checkNotNull(kTypeSerializer) { "Custom serializers declared directly on a class field via @Serializable(with = ...) " + "is currently not supported by safe args for both custom types and third-party " + "types. Please use @Serializable or @Serializable(with = ...) on the " + "class or object declaration." } return this == kTypeSerializer.descriptor } internal object UNKNOWN : NavType<String>(false) { override val name: String get() = "unknown" override fun put(bundle: Bundle, key: String, value: String) {} override fun get(bundle: Bundle, key: String): String? = null override fun parseValue(value: String): String = "null" } internal object InternalNavType { val IntNullableType = object : NavType<Int?>(true) { override val name: String get() = "integer_nullable" override fun put(bundle: Bundle, key: String, value: Int?) { // store null as serializable inside bundle, so that decoder will use the null // instead of default value if (value == null) bundle.putSerializable(key, null) else IntType.put(bundle, key, value) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): Int? { return bundle[key] as? Int } override fun parseValue(value: String): Int? { return if (value == "null") null else IntType.parseValue(value) } } val BoolNullableType = object : NavType<Boolean?>(true) { override val name: String get() = "boolean_nullable" override fun put(bundle: Bundle, key: String, value: Boolean?) { if (value == null) bundle.putSerializable(key, null) else BoolType.put(bundle, key, value) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): Boolean? { return bundle[key] as? Boolean } override fun parseValue(value: String): Boolean? { return if (value == "null") null else BoolType.parseValue(value) } } val DoubleType: NavType<Double> = object : NavType<Double>(false) { override val name: String get() = "double" override fun put(bundle: Bundle, key: String, value: Double) { bundle.putDouble(key, value) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): Double { return bundle[key] as Double } override fun parseValue(value: String): Double = value.toDouble() } val DoubleNullableType: NavType<Double?> = object : NavType<Double?>(true) { override val name: String get() = "double_nullable" override fun put(bundle: Bundle, key: String, value: Double?) { if (value == null) bundle.putSerializable(key, null) else DoubleType.put(bundle, key, value) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): Double? { return bundle[key] as? Double } override fun parseValue(value: String): Double? { return if (value == "null") null else DoubleType.parseValue(value) } } val FloatNullableType = object : NavType<Float?>(true) { override val name: String get() = "float_nullable" override fun put(bundle: Bundle, key: String, value: Float?) { if (value == null) bundle.putSerializable(key, null) else FloatType.put(bundle, key, value) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): Float? { return bundle[key] as? Float } override fun parseValue(value: String): Float? { return if (value == "null") null else FloatType.parseValue(value) } } val LongNullableType = object : NavType<Long?>(true) { override val name: String get() = "long_nullable" override fun put(bundle: Bundle, key: String, value: Long?) { if (value == null) bundle.putSerializable(key, null) else LongType.put(bundle, key, value) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): Long? { return bundle[key] as? Long } override fun parseValue(value: String): Long? { return if (value == "null") null else LongType.parseValue(value) } } val StringNonNullableType = object : NavType<String>(false) { override val name: String get() = "string_non_nullable" override fun put(bundle: Bundle, key: String, value: String) { bundle.putString(key, value) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): String = bundle.getString(key) ?: "null" // "null" is still parsed as "null" override fun parseValue(value: String): String = value // "null" is still serialized as "null" override fun serializeAsValue(value: String): String = Uri.encode(value) } val StringNullableArrayType: NavType<Array<String?>?> = object : CollectionNavType<Array<String?>?>(true) { override val name: String get() = "string_nullable[]" override fun put(bundle: Bundle, key: String, value: Array<String?>?) { bundle.putStringArray(key, value) } @Suppress("UNCHECKED_CAST", "DEPRECATION") override fun get(bundle: Bundle, key: String): Array<String?>? = bundle[key] as Array<String?>? // match String? behavior where null -> null, and "null" -> null override fun parseValue(value: String): Array<String?> = arrayOf(StringType.parseValue(value)) override fun parseValue( value: String, previousValue: Array<String?>? ): Array<String?>? = previousValue?.plus(parseValue(value)) ?: parseValue(value) override fun valueEquals(value: Array<String?>?, other: Array<String?>?): Boolean = value.contentDeepEquals(other) override fun serializeAsValues(value: Array<String?>?): List<String> = value?.map { Uri.encode(it) } ?: emptyList() override fun emptyCollection(): Array<String?>? = arrayOf() } val StringNullableListType: NavType<List<String?>?> = object : CollectionNavType<List<String?>?>(true) { override val name: String get() = "List<String?>" override fun put(bundle: Bundle, key: String, value: List<String?>?) { bundle.putStringArray(key, value?.toTypedArray()) } @Suppress("UNCHECKED_CAST", "DEPRECATION") override fun get(bundle: Bundle, key: String): List<String?>? { return (bundle[key] as Array<String?>?)?.toList() } override fun parseValue(value: String): List<String?> { return listOf(StringType.parseValue(value)) } override fun parseValue(value: String, previousValue: List<String?>?): List<String?>? { return previousValue?.plus(parseValue(value)) ?: parseValue(value) } override fun valueEquals(value: List<String?>?, other: List<String?>?): Boolean { val valueArray = value?.toTypedArray() val otherArray = other?.toTypedArray() return valueArray.contentDeepEquals(otherArray) } override fun serializeAsValues(value: List<String?>?): List<String> = value?.map { Uri.encode(it) } ?: emptyList() override fun emptyCollection(): List<String?> = emptyList() } val DoubleArrayType: NavType<DoubleArray?> = object : CollectionNavType<DoubleArray?>(true) { override val name: String get() = "double[]" override fun put(bundle: Bundle, key: String, value: DoubleArray?) { bundle.putDoubleArray(key, value) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): DoubleArray? = bundle[key] as DoubleArray? override fun parseValue(value: String): DoubleArray = doubleArrayOf(DoubleType.parseValue(value)) override fun parseValue(value: String, previousValue: DoubleArray?): DoubleArray = previousValue?.plus(parseValue(value)) ?: parseValue(value) override fun valueEquals(value: DoubleArray?, other: DoubleArray?): Boolean { val valueArray = value?.toTypedArray() val otherArray = other?.toTypedArray() return valueArray.contentDeepEquals(otherArray) } override fun serializeAsValues(value: DoubleArray?): List<String> = value?.toList()?.map { it.toString() } ?: emptyList() override fun emptyCollection(): DoubleArray = doubleArrayOf() } public val DoubleListType: NavType<List<Double>?> = object : CollectionNavType<List<Double>?>(true) { override val name: String get() = "List<Double>" override fun put(bundle: Bundle, key: String, value: List<Double>?) { bundle.putDoubleArray(key, value?.toDoubleArray()) } @Suppress("DEPRECATION") override fun get(bundle: Bundle, key: String): List<Double>? = (bundle[key] as? DoubleArray?)?.toList() override fun parseValue(value: String): List<Double> = listOf(DoubleType.parseValue(value)) override fun parseValue(value: String, previousValue: List<Double>?): List<Double>? = previousValue?.plus(parseValue(value)) ?: parseValue(value) override fun valueEquals(value: List<Double>?, other: List<Double>?): Boolean { val valueArray = value?.toTypedArray() val otherArray = other?.toTypedArray() return valueArray.contentDeepEquals(otherArray) } override fun serializeAsValues(value: List<Double>?): List<String> = value?.map { it.toString() } ?: emptyList() override fun emptyCollection(): List<Double> = emptyList() } class EnumNullableType<D : Enum<*>?>(type: Class<D?>) : SerializableNullableType<D?>(type) { private val type: Class<D?> /** Constructs a NavType that supports a given Enum type. */ init { require(type.isEnum) { "$type is not an Enum type." } this.type = type } override val name: String get() = type.name override fun parseValue(value: String): D? { return if (value == "null") { null } else { type.enumConstants!!.firstOrNull { constant -> constant!!.name.equals(value, ignoreCase = true) } ?: throw IllegalArgumentException( "Enum value $value not found for type ${type.name}." ) } } } // Base Serializable class to support nullable EnumNullableType open class SerializableNullableType<D : Serializable?>(private val type: Class<D?>) : NavType<D?>(true) { override val name: String get() = type.name init { require(Serializable::class.java.isAssignableFrom(type)) { "$type does not implement Serializable." } } override fun put(bundle: Bundle, key: String, value: D?) { bundle.putSerializable(key, type.cast(value)) } @Suppress("UNCHECKED_CAST", "DEPRECATION") override fun get(bundle: Bundle, key: String): D? { return bundle[key] as? D } /** * @throws UnsupportedOperationException since Serializables do not support default values */ public override fun parseValue(value: String): D? { throw UnsupportedOperationException("Serializables don't support default values.") } public override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SerializableNullableType<*>) return false return type == other.type } public override fun hashCode(): Int { return type.hashCode() } } }
29
Kotlin
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
20,966
androidx
Apache License 2.0
domain/src/main/java/com/example/domain/utils/ByteExt.kt
llOldmenll
338,361,910
false
{"Kotlin": 119152}
package com.example.domain.utils fun Byte.asPercents(): String = "${this}%"
0
Kotlin
0
0
14a0cf567713db9731a9464b8cf1edf1c1303f92
76
RIBsApp
Apache License 2.0
app/src/main/java/com/jrodriguezva/rickandmortykotlin/ui/character/DetailViewModel.kt
jrodriguezva
361,051,350
false
null
package com.jrodriguezva.rickandmortykotlin.ui.character import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.jrodriguezva.rickandmortykotlin.domain.model.Character import com.jrodriguezva.rickandmortykotlin.domain.model.Location import com.jrodriguezva.rickandmortykotlin.domain.model.Resource import com.jrodriguezva.rickandmortykotlin.domain.repository.RickAndMortyRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor( private val repository: RickAndMortyRepository, savedStateHandle: SavedStateHandle, ) : ViewModel() { private val _spinner = MutableStateFlow(false) val spinner: StateFlow<Boolean> = _spinner private var _location: MutableLiveData<Location> = MutableLiveData() val location: LiveData<Location> = _location val characterId: Int = savedStateHandle.get<Int>(CHARACTER_ID_SAVED_STATE_KEY) ?: 0 val character: Flow<Character> = repository.getCharacter(characterId) val charactersLocation: Flow<List<Character>> = repository.getCharactersLastKnownLocation(characterId) fun getLastLocation(locationId: Int) { viewModelScope.launch { repository.getLastKnownLocation(locationId).collect { when (it) { is Resource.Loading -> _spinner.value = true is Resource.Success -> { _spinner.value = false _location.value = it.data } else -> _spinner.value = false } } } } fun onClickFavorite(character: Character) { viewModelScope.launch { repository.updateFavorite(character) } } companion object { private const val CHARACTER_ID_SAVED_STATE_KEY = "characterId" } }
1
Kotlin
2
7
a704490cec9a4dac3861da5b10330d20c745ced3
2,218
RickAndMorty
Apache License 2.0
src/main/kotlin/com/example/safetynet/cache/NonceCache.kt
kkocel
114,170,403
false
null
package com.example.safetynet.cache import com.example.safetynet.nonce.UserIdentifier interface NonceCache { fun invalidate(nonce: String) fun put(nonce: String, userIdentifier: UserIdentifier) fun getIfPresent(nonce: String): UserIdentifier? }
1
Kotlin
2
6
e89216bdf91c66f22cb4ec29a8c426a8e6ca2db8
261
safetynet-spring
Apache License 2.0
blockball-api/src/main/java/com/github/shynixn/blockball/api/business/service/BossBarService.kt
Shynixn
78,865,055
false
{"Kotlin": 990306, "Dockerfile": 2558, "Shell": 2544}
package com.github.shynixn.blockball.api.business.service import com.github.shynixn.blockball.api.persistence.entity.BossBarMeta /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ interface BossBarService { /** * Adds the given [player] to this bossbar. * Does nothing if the player is already added. */ fun <B, P> addPlayer(bossBar: B, player: P) /** * Removes the given [player] from this bossbar. * Does nothing if the player is already removed. */ fun <B, P> removePlayer(bossBar: B, player: P) /** * Returns a list of all players watching thie bossbar. */ fun <B, P> getPlayers(bossBar: B): List<P> /** * Changes the style of the bossbar with given [bossBarMeta]. */ fun <B, P> changeConfiguration(bossBar: B, title: String, bossBarMeta: BossBarMeta, player: P) /** * Generates a new bossbar from the given bossBar meta values. */ fun <B> createNewBossBar(bossBarMeta: BossBarMeta): B /** * Clears all resources this [bossBar] has allocated from this service. */ fun <B> cleanResources(bossBar: B) }
2
Kotlin
23
66
798fdbe00024bc8e41a33c8df4885668ed141f87
2,286
BlockBall
Apache License 2.0
KotlinApp/app/src/main/java/com/example/kotlinapp/MainActivity.kt
avulaankith
389,128,311
false
null
package com.example.kotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.TextView import kotlin.random.Random class MainActivity : AppCompatActivity() { private lateinit var diceImage: ImageView // late init says its not a null value and initialises it beforehand override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val rollButton: Button = findViewById(R.id.roll_button) //since find view by id takes a lot of energy we declare it outside of function rollButton.text = getString(R.string.lets_roll) // rollButton.setOnClickListener { // Toast.makeText(this, "Button is Clicked!", Toast.LENGTH_SHORT).show() // } diceImage = findViewById(R.id.dice_image) rollButton.setOnClickListener { rollDice() } } private fun rollDice() { // val resultText: TextView = findViewById(R.id.result_text) // resultText.text="0" // val diceImage: ImageView = findViewById(R.id.dice_image) // resultText.text=randomInt.toString() val drawableImage = when (Random.nextInt(1,6)){ 1->R.drawable.dice_1 2->R.drawable.dice_2 3->R.drawable.dice_3 4->R.drawable.dice_4 5->R.drawable.dice_5 else->R.drawable.dice_6 } diceImage.setImageResource(drawableImage) } }
0
Kotlin
0
0
03928364b142fdb72e2141e177a56c20d1d8235d
1,576
Dice-Rolling-App
MIT License
lib/sisyphus-protobuf/src/main/kotlin/com/bybutter/sisyphus/protobuf/primitives/TypeExtension.kt
zhi-re
283,650,568
true
{"Kotlin": 970649, "ANTLR": 10895}
package com.bybutter.sisyphus.protobuf.primitives import com.bybutter.sisyphus.protobuf.Message import com.bybutter.sisyphus.protobuf.ProtoTypes fun DescriptorProto.toType(typeName: String): Type { return Type { val fileInfo = ProtoTypes.getFileDescriptorByName(typeName) this.name = [email protected] this.fields += [email protected] { it.toField() } this.fields += ProtoTypes.getTypeExtensions(typeName).mapNotNull { ProtoTypes.getExtensionDescriptor(typeName, it)?.toField() } this.oneofs += [email protected] { it.name } [email protected]?.let { this.options += it.toOptions() } this.sourceContext = fileInfo?.let { SourceContext { this.fileName = it.name } } this.syntax = when (fileInfo?.syntax) { "proto3" -> Syntax.PROTO3 else -> Syntax.PROTO2 } } } fun FieldDescriptorProto.toField(): Field { return Field { this.kind = Field.Kind([email protected]) this.cardinality = Field.Cardinality([email protected]) this.number = [email protected] this.name = [email protected] when (this.kind) { Field.Kind.TYPE_MESSAGE, Field.Kind.TYPE_ENUM -> { this.typeUrl = "types.bybutter.com/${[email protected](1)}" } else -> { } } if ([email protected]()) { this.oneofIndex = [email protected] } [email protected]?.packed?.let { this.packed = it } [email protected]?.let { this.options += it.toOptions() } this.jsonName = [email protected] if ([email protected]()) { this.defaultValue = [email protected] } } } fun EnumDescriptorProto.toEnum(typeName: String): Enum { return Enum { val fileInfo = ProtoTypes.getFileDescriptorByName(typeName) this.name = [email protected] this.enumvalue += [email protected] { it.toEnumValue() } [email protected]?.let { this.options += it.toOptions() } this.sourceContext = fileInfo?.let { SourceContext { this.fileName = it.name } } this.syntax = when (fileInfo?.syntax) { "proto3" -> Syntax.PROTO3 else -> Syntax.PROTO2 } } } fun EnumValueDescriptorProto.toEnumValue(): EnumValue { return EnumValue { this.number = [email protected] this.name = [email protected] [email protected]?.let { this.options += it.toOptions() } } } private fun Message<*, *>.toOptions(): List<Option> { val result = mutableListOf<Option>() loop@for ((field, value) in this) { when (value) { is List<*> -> { for (v in value) { val protoValue = v.wrapToProtoValue() ?: continue result += Option { this.name = field.name this.value = protoValue } } } is Map<*, *> -> continue@loop else -> { val protoValue = value.wrapToProtoValue() ?: continue@loop result += Option { this.name = field.name this.value = protoValue } } } } return result } private fun kotlin.Any?.wrapToProtoValue(): Message<*, *>? { return when (this) { is Message<*, *> -> this is String -> this.wrapper() is Int -> this.wrapper() is UInt -> this.wrapper() is Long -> this.wrapper() is ULong -> this.wrapper() is Boolean -> this.wrapper() is Float -> this.wrapper() is Double -> this.wrapper() is ByteArray -> this.wrapper() else -> null } }
0
null
0
0
67f534e9c62833d32ba93bfd03fbc3c1f81f52e6
4,079
sisyphus
MIT License
feature_browse_photo/impl/src/main/java/com/example/feature/browse/photo/impl/domain/GetPhotoByIdUseCaseImpl.kt
powerINcode
356,784,278
false
null
package com.example.feature.browse.photo.impl.domain import com.example.feature.browse.photo.api.domain.GetPhotoByIdUseCase import io.reactivex.rxjava3.core.Single import javax.inject.Inject internal class GetPhotoByIdUseCaseImpl @Inject constructor( private val photoRepository: com.example.api.PhotoRepository ): GetPhotoByIdUseCase { override fun invoke(params: Long): Single<com.example.api.entities.Photo> = photoRepository.getPhoto(params) }
0
Kotlin
0
0
f27f0a978f1abe379a8a4372b2c0109c48c2b872
457
PhotoMaker
Apache License 2.0
javalin-plugins/javalin-swagger-plugin/src/test/kotlin/io/javalin/openapi/plugin/swagger/specification/JavalinBehindProxy.kt
javalin
364,314,288
false
{"Kotlin": 174798, "Groovy": 2297}
package io.javalin.openapi.plugin.swagger.specification import io.javalin.Javalin import io.javalin.http.Context import kong.unirest.HttpRequest import kong.unirest.Unirest import java.util.concurrent.CountDownLatch import java.util.function.Supplier internal class JavalinBehindProxy( javalinSupplier: Supplier<Javalin>, private val port: Int, basePath: String ) : AutoCloseable { private val javalin = javalinSupplier .get() private val proxy = Javalin.create() .get("/") { it.html("Index") } .get(basePath) { Unirest.get(it.javalinLocation()).redirect(it) } .get("$basePath/<uri>") { Unirest.get(it.javalinLocation()).redirect(it) } .head("$basePath/<uri>") { Unirest.head(it.javalinLocation()).redirect(it) } .post("$basePath/<uri>") { Unirest.post(it.javalinLocation()).redirect(it) } .put("$basePath/<uri>") { Unirest.put(it.javalinLocation()).redirect(it) } .delete("$basePath/<uri>") { Unirest.delete(it.javalinLocation()).redirect(it) } .options("$basePath/<uri>") { Unirest.options(it.javalinLocation()).redirect(it) } init { start() } fun start(): JavalinBehindProxy = also { val awaitStart = CountDownLatch(2) javalin .events { it.serverStarted { awaitStart.countDown() } } .start(port + 1) proxy .events { it.serverStarted { awaitStart.countDown() } } .start(port) awaitStart.await() } fun stop() { proxy.stop() javalin.stop() } override fun close() { stop() } private fun <R : HttpRequest<*>> R.redirect(ctx: Context) { ctx.headerMap().forEach { (key, value) -> header(key, value) } val response = this.asBytes() response.headers.all().forEach { ctx.header(it.name, it.value) } ctx.status(response.status).result(response.body) } private fun Context.javalinLocation(): String = "http://localhost:${port + 1}/${pathParamMap()["uri"] ?: ""}" }
9
Kotlin
17
45
a8dbbc513388c01f6b6a4f3a6540a58be4fab45f
2,057
javalin-openapi
Apache License 2.0
solidfragment/src/main/java/com/mitteloupe/solid/fragment/handler/common/LayoutLifecycleHandler.kt
EranBoudjnah
223,144,820
false
null
package com.mitteloupe.solid.fragment.handler.common import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import com.mitteloupe.solid.fragment.handler.LifecycleHandler class LayoutLifecycleHandler( @LayoutRes private val layoutResourceId: Int ) : LifecycleHandler { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(layoutResourceId, container, false) }
0
Kotlin
0
35
c022a6f6d905262647da4cc737b776e5c0601a09
573
solid
MIT License
app/src/main/java/com/example/antheia_plant_manager/screens/loading/LoadingViewModel.kt
MegaBreadbox
814,871,131
false
{"Kotlin": 120448}
package com.example.antheia_plant_manager.screens.loading class LoadingViewModel { }
0
Kotlin
0
0
f9c418e22a4d3c18a4c92f7819113f743eb77e6e
85
Antheia
Apache License 2.0
src/main/kotlin/model/ServicesPrices.kt
TheChance101
597,300,348
false
null
package model data class ServicesPrices( val basicElectricityHeatingCoolingWaterGarbageFor85m2Apartment: Float?, val oneMinOfPrepaidMobileTariffLocalNoDiscountsOrPlans: Float?, val internet60MbpsOrMoreUnlimitedDataCableAdsl: Float?, val fitnessClubMonthlyFeeForOneAdult: Float?, val tennisCourtRentOneHourOnWeekend: Float?, val cinemaInternationalReleaseOneSeat: Float?, val preschoolOrKindergartenFullDayPrivateMonthlyForOneChild: Float?, val internationalPrimarySchoolYearlyForOneChild: Float?, )
25
Kotlin
25
10
31fd904e99e095b059b8b8433d6d3e96753bf2a5
532
cost-of-living
Apache License 2.0
one.irradia.opds1_2.tests/src/main/java/one/irradia/opds1_2/tests/OPDS12FeedEntryNYPLParserProviderContract.kt
irradia
177,828,518
false
{"Gradle": 12, "INI": 12, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "YAML": 1, "Markdown": 1, "XML": 36, "Kotlin": 61, "Java": 8}
package one.irradia.opds1_2.tests import one.irradia.opds1_2.api.OPDS12Acquisition import one.irradia.opds1_2.parser.api.OPDS12FeedEntryParserProviderType import one.irradia.opds1_2.api.OPDS12ParseResult import one.irradia.opds1_2.nypl.OPDS12Availability import one.irradia.opds1_2.nypl.OPDS12NYPLFeedEntryParsers import one.irradia.opds1_2.parser.api.OPDS12FeedParseRequest import one.irradia.opds1_2.parser.api.OPDS12FeedParseRequest.* import one.irradia.opds1_2.parser.api.OPDS12FeedParseTarget import one.irradia.opds1_2.parser.api.OPDS12FeedParseTarget.* import org.junit.Assert import org.junit.Before import org.junit.Test import org.slf4j.Logger import java.io.FileNotFoundException import java.io.InputStream import java.net.URI import org.joda.time.Instant abstract class OPDS12FeedEntryNYPLParserProviderContract { abstract fun logger(): Logger abstract fun parsers(): OPDS12FeedEntryParserProviderType private fun resource(name: String): InputStream { val path = "/one/irradia/opds1_2/tests/$name" val url = OPDS12FeedEntryNYPLParserProviderContract::class.java.getResource(path) ?: throw FileNotFoundException("No such resource: $path") return url.openStream() } private lateinit var parsers: OPDS12FeedEntryParserProviderType private lateinit var logger: Logger private fun <T> dumpParseResult(result: OPDS12ParseResult<T>) { return when (result) { is OPDS12ParseResult.OPDS12ParseSucceeded -> { this.logger.debug("success: {}", result.result) } is OPDS12ParseResult.OPDS12ParseFailed -> { result.errors.forEach { error -> this.logger.debug("error: {}: ", error, error.exception) } } } } @Before fun testSetup() { this.parsers = this.parsers() this.logger = this.logger() } @Test fun testEntryOKAcquisitionsAvailability() { val parser = this.parsers.createParser(OPDS12FeedParseRequest( uri = URI.create("urn:test"), acquisitionFeedEntryParsers = this.parsers, target = OPDS12FeedParseTargetStream(this.resource("entry-ok-acquisitions-availability.xml")), extensionEntryParsers = listOf(OPDS12NYPLFeedEntryParsers()))) val result = parser.parse() dumpParseResult(result) val success = result as OPDS12ParseResult.OPDS12ParseSucceeded val entry = success.result Assert.assertEquals(23, entry.acquisitions.size) val extensions = success.result.extensions.filterIsInstance(OPDS12Availability::class.java) run { val acquisition = entry.acquisitions[0] val availability = extensions.find { available -> available.acquisition == acquisition }!! logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Open-Access0") Assert.assertEquals( OPDS12Availability.OpenAccess(acquisition), availability) } run { val acquisition = entry.acquisitions[1] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Loanable") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } run { val acquisition = entry.acquisitions[2] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Loaned-Timed") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.Loaned( acquisition = acquisition, startDate = Instant.parse("2000-01-01T00:00:00Z"), endDate = Instant.parse("2010-01-01T00:00:00Z"), revokeURI = null ), availability) } run { val acquisition = entry.acquisitions[3] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Loaned-Indefinite") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.Loaned( acquisition = acquisition, startDate = Instant.parse("2000-01-01T00:00:00Z"), endDate = null, revokeURI = null ), availability) } run { val acquisition = entry.acquisitions[4] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Loanable-0") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } run { val acquisition = entry.acquisitions[5] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Holdable-0") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Holdable(acquisition), availability) } run { val acquisition = entry.acquisitions[6] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "HeldReady") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.HeldReady( acquisition = acquisition, endDate = null, revokeURI = null), availability) } run { val acquisition = entry.acquisitions[7] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "HeldReady-Timed") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.HeldReady( acquisition = acquisition, endDate = Instant.parse("2010-01-01T00:00:00Z"), revokeURI = null), availability) } run { val acquisition = entry.acquisitions[8] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Held-Ready-Specific") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.HeldReady( acquisition = acquisition, endDate = Instant.parse("2015-08-24T00:30:24.000Z"), revokeURI = null), availability) } run { val acquisition = entry.acquisitions[9] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Held-Timed") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.Held( acquisition = acquisition, startDate = Instant.parse("2000-01-01T00:00:00Z"), position = null, endDate = Instant.parse("2010-01-01T00:00:00.000Z"), revokeURI = null), availability) } run { val acquisition = entry.acquisitions[10] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Held-Timed-Queued") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.Held( acquisition = acquisition, startDate = Instant.parse("2000-01-01T00:00:00Z"), position = 3, endDate = Instant.parse("2010-01-01T00:00:00.000Z"), revokeURI = null), availability) } run { val acquisition = entry.acquisitions[11] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Held-Indefinite") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.Held( acquisition = acquisition, startDate = Instant.parse("2000-01-01T00:00:00Z"), position = null, endDate = null, revokeURI = null), availability) } run { val acquisition = entry.acquisitions[12] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Held-Indefinite-Queued") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals(OPDS12Availability.Held( acquisition = acquisition, startDate = Instant.parse("2000-01-01T00:00:00Z"), position = 3, endDate = null, revokeURI = null), availability) } run { val acquisition = entry.acquisitions[13] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Buy-Is-Loanable") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } run { val acquisition = entry.acquisitions[14] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Subscribe-Is-Loanable") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } run { val acquisition = entry.acquisitions[15] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Sample-Is-Loanable") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } run { val acquisition = entry.acquisitions[16] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Generic-Is-Loaned") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loaned( acquisition, startDate = null, endDate = null, revokeURI = null), availability) } run { val acquisition = entry.acquisitions[17] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Unavailable-Is-Holdable") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Holdable(acquisition), availability) } run { val acquisition = entry.acquisitions[18] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "OpenAccess-Is-OpenAccess") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.OpenAccess(acquisition), availability) } run { val acquisition = entry.acquisitions[19] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Buy-Available-Is-Loanable2") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } run { val acquisition = entry.acquisitions[20] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Subscribe-Available-Is-Loanable2") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } run { val acquisition = entry.acquisitions[21] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Sample-Available-Is-Loanable2") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } run { val acquisition = entry.acquisitions[22] logger.debug("acquisition: {}", acquisition) checkAcquisitionURIEndsWith(acquisition, "Generic-Nonsense-Is-Loanable") val availability = extensions.find { available -> available.acquisition == acquisition }!! Assert.assertEquals( OPDS12Availability.Loanable(acquisition), availability) } } private fun checkAcquisitionURIEndsWith(acquisition: OPDS12Acquisition, name: String) { val received = acquisition.uri.toString() Assert.assertTrue("Wanted $name but got $received", received.endsWith(name)) } }
1
null
1
1
78596ee9c5e528ec4810472f1252d844abdf7fe3
12,757
one.irradia.opds1_2
BSD Zero Clause License
app/src/main/java/com/lovenottiesmobile/lovenotties_v1/SuccessStoryModel.kt
ST10084225
727,899,202
false
{"Kotlin": 64879}
package com.lovenottiesmobile.lovenotties_v1 data class SuccessStoryModel(val SSID : String, val SSTitle : String, val SSImageID : String, val SSDescription : String)
0
Kotlin
0
0
3fbf15e56594864c6305c0c87674763daa4bacbc
196
LoveNottiesApp
MIT License
frontend/app/src/main/java/com/mobile/paozim/classes/Rating.kt
DesenvolvimentoSistemasSoftware
771,009,250
false
{"Kotlin": 108244, "HTML": 73}
package com.mobile.paozim.classes import kotlinx.serialization.Serializable @Serializable class Rating ( var id: String? = null, var productID: String, var userID: String, var rating: Int, var comment: String, var date: String )
7
Kotlin
0
0
79e076cdb5f021acd6f1dbe6ddd0c9e10c73b34f
255
Paozim
MIT License
core/ui/src/main/java/com/hellguy39/hellnotes/core/ui/components/snack/SnackAction.kt
HellGuy39
572,830,054
false
{"Kotlin": 853329}
package com.hellguy39.hellnotes.core.ui.components.snack sealed class SnackAction { object Delete : SnackAction() object Restore : SnackAction() object Archive : SnackAction() object Unarchive : SnackAction() object Pinned : SnackAction() object Unpinned : SnackAction() }
2
Kotlin
0
21
5bed2a7deeed28030c3284d482f4757b8017c31d
303
HellNotes
Apache License 2.0
app/src/main/java/cn/haohao/dbbook/presentation/activity/BookCommentActivity.kt
githubhaohao
95,271,877
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 1, "Java": 16, "XML": 52, "Kotlin": 60}
package cn.haohao.dbbook.presentation.activity import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.content.res.AppCompatResources import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.MenuItem import cn.haohao.dbbook.R import cn.haohao.dbbook.data.entity.http.BookReviewResponse import cn.haohao.dbbook.data.entity.http.BookReviewsListResponse import cn.haohao.dbbook.di.ApplicationComponent import cn.haohao.dbbook.di.subcomponent.comment.BookCommentActivityModule import cn.haohao.dbbook.domain.entity.RequestDetailParams import cn.haohao.dbbook.presentation.adapter.BookCommentAdapter import cn.haohao.dbbook.presentation.presenter.BookDetailPresenter import cn.haohao.dbbook.presentation.util.showToast import cn.haohao.dbbook.presentation.view.BookDetailView import kotlinx.android.synthetic.main.activity_book_comments_layout.* import java.util.ArrayList import javax.inject.Inject class BookCommentActivity : BaseActivity(), BookDetailView, SwipeRefreshLayout.OnRefreshListener { companion object { const val COMMENT_FIELDS = "id,rating,author,title,updated,comments,summary,votes,useless" const val TAG = "BookCommentActivity" } private var count = 20 private var page = 0 private lateinit var bookId: String private lateinit var bookName: String private lateinit var mBookCommentAdapter: BookCommentAdapter private lateinit var mBookReviewsListRes: BookReviewsListResponse private var isLoadAll = false @Inject lateinit var mBookDetailPresenter: BookDetailPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_book_comments_layout) injectToThis() initEvent() } override fun injectDependencies(applicationComponent: ApplicationComponent) { super.injectDependencies(applicationComponent) applicationComponent.plus(BookCommentActivityModule(this)) .injectTo(this) } override fun onError(error: String) { Log.e(TAG, error) showToast(error) } override fun showDetailData(data: Any) { if (data is BookReviewsListResponse) { if (data.start == 0 ) { mBookReviewsListRes.reviews = emptyList() } mBookReviewsListRes.total = data.total val newReviews = ArrayList<BookReviewResponse>() newReviews.addAll(mBookReviewsListRes.reviews) newReviews.addAll(data.reviews) mBookReviewsListRes.reviews = newReviews mBookCommentAdapter.notifyDataSetChanged() if (data.total > page * count) { page ++ isLoadAll = false } else { isLoadAll = true } } } override fun showProgressView() { swipeRefreshWidget.isRefreshing = true } override fun hideProgressView() { swipeRefreshWidget.isRefreshing = false } override fun onRefresh() { page = 0 mBookDetailPresenter.execute(RequestDetailParams(bookId, page * count, count, COMMENT_FIELDS)) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } override fun onDestroy() { mBookDetailPresenter.cancel() super.onDestroy() } private fun loadMore() { if (isLoadAll) { Snackbar.make(toolbar, R.string.no_more_comment, Snackbar.LENGTH_SHORT).show() } else { mBookDetailPresenter.execute(RequestDetailParams(bookId, page * count, count, COMMENT_FIELDS)) } } private fun initEvent() { mBookReviewsListRes = BookReviewsListResponse() mBookReviewsListRes.reviews = emptyList() swipeRefreshWidget.setColorSchemeResources(R.color.recycler_color1, R.color.recycler_color2, R.color.recycler_color3, R.color.recycler_color4) mBookCommentAdapter = BookCommentAdapter(mBookReviewsListRes) val layoutManager = LinearLayoutManager(this) layoutManager.orientation = LinearLayoutManager.VERTICAL recyclerView.layoutManager = layoutManager recyclerView.adapter = mBookCommentAdapter recyclerView.itemAnimator = DefaultItemAnimator() bookName = intent.getStringExtra("book_name") bookId = intent.getStringExtra("book_id") setSupportActionBar(toolbar) toolbar.navigationIcon = AppCompatResources.getDrawable(this, R.drawable.ic_action_navigation_arrow_back_inverted) title = "$bookName${getString(R.string.comment_of_book)}" recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { private var lastVisibleItem: Int = 0 override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mBookCommentAdapter.getItemCount()) { loadMore() } } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) lastVisibleItem = layoutManager.findLastVisibleItemPosition() } }) swipeRefreshWidget.setOnRefreshListener(this) onRefresh() } }
1
Kotlin
32
163
bc08d6dd89fc86304b2b95cc1c2b3f67b55ee451
5,774
DoubanBook
Apache License 2.0
src/main/kotlin/dev/lunarcoffee/risako/bot/exts/commands/mod/ModCommands.kt
lunarcoffee
191,968,430
false
{"Kotlin": 283896}
@file:Suppress("unused") package dev.lunarcoffee.risako.bot.exts.commands.mod import dev.lunarcoffee.risako.bot.exts.commands.mod.ban.BanController import dev.lunarcoffee.risako.bot.exts.commands.mod.kick.KickController import dev.lunarcoffee.risako.bot.exts.commands.mod.logs.AuditLogSender import dev.lunarcoffee.risako.bot.exts.commands.mod.mute.MuteController import dev.lunarcoffee.risako.bot.exts.commands.mod.mutel.MuteDetailsSender import dev.lunarcoffee.risako.bot.exts.commands.mod.mutel.MuteListSender import dev.lunarcoffee.risako.bot.exts.commands.mod.purge.ChannelPurger import dev.lunarcoffee.risako.framework.api.dsl.command import dev.lunarcoffee.risako.framework.api.extensions.* import dev.lunarcoffee.risako.framework.core.annotations.CommandGroup import dev.lunarcoffee.risako.framework.core.bot.Bot import dev.lunarcoffee.risako.framework.core.commands.transformers.* import dev.lunarcoffee.risako.framework.core.std.SplitTime import dev.lunarcoffee.risako.framework.core.std.UserNotFound import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.User @CommandGroup("Mod") class ModCommands(private val bot: Bot) { fun mute() = command("mute") { description = "Mutes a member for a specified amount of time." aliases = arrayOf("silence", "softban") extDescription = """ |`$name user time [reason]`\n |Mutes a user for a specified amount of time. I must have the permission to manage |roles. When a member is muted, they will be sent a message with `time` in a readable |format, the provided `reason` (or `(no reason)`) if none is provided, and the user |that muted them. You must be able to manage roles to use this command. """ expectedArgs = arrayOf(TrUser(), TrTime(), TrRest(true, "(no reason)")) execute { args -> val user = args.get<User>(0) if (user is UserNotFound) { sendError("I can't find that user!") return@execute } val time = args.get<SplitTime>(1) val reason = args.get<String>(2) MuteController(this).mute(user, time, reason) } } fun unmute() = command("unmute") { description = "Unmutes a currently muted member." aliases = arrayOf("unsilence", "unsoftban") extDescription = """ |`$name user`\n |Unmutes a muted user. This only works if the user was muted with the `..mute` command |from this bot. The unmuted user will be sent a message with the person who unmuted |them. You must be able to manage roles to use this command. """ expectedArgs = arrayOf(TrUser()) execute { args -> val user = args.get<User>(0) MuteController(this).unmute(user) } } fun mutel() = command("mutel") { description = "Shows the muted members on the current server." aliases = arrayOf("mutelist", "silencel", "silencelist", "softbanl", "softbanlist") extDescription = """ |`$name [user]`\n |Without arguments, this command lists all muted members of the current server, along |with the remaining time they will be muted for (without a manual unmute). When `user` |is provided, this command lists details about their mute, including the reason, the |remaining time, and their previous roles. """ expectedArgs = arrayOf(TrUser(true)) execute { args -> val user = args.get<User?>(0) if (user is UserNotFound) { sendError("I can't find that user!") return@execute } if (user != null) { send(MuteDetailsSender(user)) return@execute } send(MuteListSender()) } } fun kick() = command("kick") { description = "Kicks a member from the current server." extDescription = """ |`$name user [reason]`\n |Kicks a user from the current server. I must be have the permission to kick members. |When a member is kicked, they will be sent a message with `reason` (or `(no reason)`) |if no reason is specified and the user that kicked them. You must be able to kick |members to use this command. """ expectedArgs = arrayOf(TrUser(), TrRest(true, "(no reason)")) execute { args -> val user = args.get<User>(0) if (user is UserNotFound) { sendError("I can't find that user!") return@execute } val reason = args.get<String>(1) KickController(this).kick(user, reason) } } fun ban() = command("ban") { description = "Permanently bans a member from a server." extDescription = """ |`$name user [reason]`\n |Bans a user from the current server. I must be have the permission to ban members. |When a member is banned, they will be sent a message with `reason` (or `(no reason)`) |if no reason is specified and the user that banned them. You must be able to ban |members to use this command. """ expectedArgs = arrayOf(TrUser(), TrRest(true, "(no reason)")) execute { args -> val user = args.get<User>(0) if (user is UserNotFound) { sendError("I can't find that user!") return@execute } val reason = args.get<String>(1) BanController(this).ban(user, reason) } } fun unban() = command("unban") { description = "Unbans a member from the current server." extDescription = """ |`$name name|id`\n |Unbans a banned user from the current server. I must have the permission to ban |members. When a member is unbanned, they might be sent a message with the person who |unbanned them. This only happens if I am in a server that they are also in. You must |be able to ban members to use this command. """ expectedArgs = arrayOf(TrWord()) execute { args -> val nameOrId = args.get<String>(0) val user = event .guild .retrieveBanList() .await() .find { nameOrId in arrayOf(it.user.id, it.user.name, it.user.asTag) } ?.user if (user == null) { sendError("Either that user is not banned, or doesn't exist!") return@execute } BanController(this).unban(user) } } fun purge() = command("purge") { description = "Deletes a certain amount of messages from a channel." aliases = arrayOf("clear", "massdelete") extDescription = """ |`$name limit [user]`\n |Deletes the past `limit` messages from the current channel, the message containing the |command exempt. If `user` is specified, this command deletes the past `limit` messages |from only that user. You must be able to manage messages to use this command. """ expectedArgs = arrayOf(TrInt(), TrUser(true)) execute { args -> val limit = args.get<Int>(0) val user = args.get<User?>(1) val purger = ChannelPurger(this, limit) when (user) { is UserNotFound -> { sendError("I can't find that user!") return@execute } null -> purger.purgeAll() else -> purger.purgeFromUser(user, user == event.author) } } } fun slow() = command("slow") { description = "Sets the current text channel's slowmode." aliases = arrayOf("cooldown", "slowmode") extDescription = """ |`$name time` |When setting the slowmode cooldown of a channel in the Discord client's channel |settings, the only options available are at fixed lengths of time. This command lets |you change it to any arbitrary time between none to six hours. The `time` argument |should look something like `2m 30s`, `1h`, or `0s`, to give some examples. """ expectedArgs = arrayOf(TrTime()) execute { args -> val slowmode = args.get<SplitTime>(0) val slowmodeSeconds = slowmode.totalMs.toInt() / 1_000 if (!event.guild.getMember(event.author)!!.hasPermission(Permission.MANAGE_CHANNEL)) { sendError("You need to be able to manage channels to use this command!") return@execute } if (slowmodeSeconds !in 0..21_600) { sendError("I can't set this channel's slowmode to that amount of time!") return@execute } val channel = event.guild.getTextChannelById(event.channel.id)!! channel.manager.setSlowmode(slowmodeSeconds).queue() val slowmodeRepr = if (slowmode.totalMs > 0) "`$slowmode`" else "disabled" sendSuccess("This channel's slowmode time is now $slowmodeRepr!") } } fun logs() = command("logs") { description = "Gets this server's audit log history." aliases = arrayOf("audits", "auditlogs") extDescription = """ |`$name [limit]`\n |This command retrieves the last `limit` entries in the audit log. If `limit` is not |given, I will get the last ten entries. For each audit log entry, I'll show the type |of the audit, the user that initiated it, the affected target type and name, the time |at which it took place, and the reason (when a user is banned, for example). |&{Limitations:} |I won't show you what actually changed, since that would require more effort for me to |do than for you to open up the audit logs in the server settings. You need to be able |to view the logs already to use this command, anyway. """ expectedArgs = arrayOf(TrInt(true, 10)) execute { args -> val limit = args.get<Int>(0) if (limit !in 1..100) { sendError("I can't get that many log entries!") return@execute } send(AuditLogSender(limit)) } } }
0
Kotlin
0
0
8ae6c0fa0f85c90725667055493276116a0c0870
10,607
Risako
MIT License
wallet-kit/src/main/kotlin/bitcoin/wallet/kit/network/TestNet.kt
knyghtryda
152,536,499
true
{"Kotlin": 342789, "Java": 82146}
package bitcoin.wallet.kit.network import bitcoin.wallet.kit.blocks.BlockValidator import bitcoin.wallet.kit.blocks.BlockValidatorException import bitcoin.wallet.kit.models.Block import bitcoin.wallet.kit.models.Header import bitcoin.walllet.kit.utils.HashUtils open class TestNet : NetworkParameters() { // private val diffDate = Date(1329264000000L) // February 16th 2012 private val diffDate = 1329264000L // February 16th 2012 override var id: String = ID_TESTNET override var port: Int = 18333 override var packetMagic: Long = 0x0b110907 override var bip32HeaderPub: Int = 0x043587CF override var bip32HeaderPriv: Int = 0x04358394 override var addressVersion: Int = 111 override var addressSegwitHrp: String = "tb" override var addressScriptVersion: Int = 196 override var coinType: Int = 1 override var dnsSeeds: Array<String> = arrayOf( "testnet-seed.bitcoin.petertodd.org", // Peter Todd "testnet-seed.bitcoin.jonasschnelli.ch", // Jonas Schnelli "testnet-seed.bluematt.me", // Matt Corallo "testnet-seed.bitcoin.schildbach.de", // Andreas Schildbach "bitcoin-testnet.bloqseeds.net" // Bloq ) override val checkpointBlock = Block( Header().apply { version = 536870912 prevHash = HashUtils.toBytesAsLE("000000000000032d74ad8eb0a0be6b39b8e095bd9ca8537da93aae15087aafaf") merkleHash = HashUtils.toBytesAsLE("dec6a6b395b29be37f4b074ed443c3625fac3ae835b1f1080155f01843a64268") timestamp = 1533498326 bits = 436270990 nonce = 205753354 }, 1380960) override fun validate(block: Block, previousBlock: Block) { BlockValidator.validateHeader(block, previousBlock) if (isDifficultyTransitionEdge(block.height)) { checkDifficultyTransitions(block) } else { BlockValidator.validateBits(block, previousBlock) } } override fun checkDifficultyTransitions(block: Block) { var previousBlock = checkNotNull(block.previousBlock) { throw BlockValidatorException.NoPreviousBlock() } val previousBlockHeader = checkNotNull(previousBlock.header) { throw BlockValidatorException.NoHeader() } if (previousBlockHeader.timestamp > diffDate) { val blockHeader = checkNotNull(block.header) { throw BlockValidatorException.NoHeader() } val timeDelta = blockHeader.timestamp - previousBlockHeader.timestamp if (timeDelta >= 0 && timeDelta <= targetSpacing * 2) { var cursor = block var cursorHeader = checkNotNull(cursor.header) while (cursor.height != 0 && (cursor.height % heightInterval.toInt()) != 0 && cursorHeader.bits == maxTargetBits.toLong()) { previousBlock = checkNotNull(cursor.previousBlock) { throw BlockValidatorException.NoPreviousBlock() } val header = checkNotNull(previousBlock.header) { throw BlockValidatorException.NoHeader() } cursor = previousBlock cursorHeader = header } if (cursorHeader.bits != blockHeader.bits) { BlockValidatorException.NotEqualBits() } } } else super.checkDifficultyTransitions(block) } }
0
Kotlin
1
0
a7ee0e75d50796e31f2f0d7953bf18942917eb13
3,592
wallet-kit-android
MIT License
src/main/kotlin/com/deflatedpickle/marvin/api/Appliable.kt
DeflatedPickle
282,412,324
false
null
/* Copyright (c) 2021 DeflatedPickle under the MIT license */ package com.deflatedpickle.marvin.api interface Appliable { fun apply() }
2
Kotlin
0
0
be7c68d3ecf4415fa01e98bd74b16b23d6a9f412
142
marvin
MIT License
src/main/kotlin/de/sambalmueslie/padlet/sender/db/TeamsWallConfigRepository.kt
sambalmueslie
370,110,224
false
null
package de.sambalmueslie.padlet.sender.db import io.micronaut.data.annotation.Repository import io.micronaut.data.repository.PageableRepository @Repository interface TeamsWallConfigRepository : PageableRepository<TeamsWallConfig, Long> { fun findByWallId(wallId: Long): TeamsWallConfig? }
0
Kotlin
0
0
9db6d0c8049792027422160c65cbc2ba0b64fc6a
295
padlet-notifier
Apache License 2.0
engine/src/main/kotlin/io/rsbox/engine/model/entity/DynamicObject.kt
TheProdigy94
199,138,033
false
null
package io.rsbox.engine.model.entity import io.rsbox.engine.model.EntityType import io.rsbox.engine.model.RSTile /** * A [DynamicObject] is a game object that can be spawned by the [io.rsbox.engine.model.RSWorld]. * * @author Tom <<EMAIL>> */ class DynamicObject(id: Int, type: Int, rot: Int, tile: RSTile) : RSGameObject(id, type, rot, tile) { constructor(other: RSGameObject) : this(other.id, other.type, other.rot, RSTile(other.tile as RSTile)) constructor(other: RSGameObject, id: Int) : this(id, other.type, other.rot, RSTile(other.tile as RSTile)) override val entityType: EntityType = EntityType.DYNAMIC_OBJECT }
0
Kotlin
0
0
b83537fb4cb39be1a9fb22354477b9063d518d0d
640
rsbox
Apache License 2.0
src/main/kotlin/ar/edu/unq/pds03backend/dto/subject/SubjectWithCoursesResponseDTO.kt
cassa10
478,695,193
false
{"Kotlin": 387344, "Shell": 2326, "Dockerfile": 168}
package ar.edu.unq.pds03backend.dto.subject import ar.edu.unq.pds03backend.dto.course.SimpleCourseResponseDTO data class SubjectWithCoursesResponseDTO( val subject: SimpleSubjectResponseDTO, val courses: List<SimpleCourseResponseDTO>, ) { override fun equals(other: Any?): Boolean { other as SubjectWithCoursesResponseDTO return subject.id == other.subject.id } }
0
Kotlin
1
0
2e61373e3b06ba75399dc429683eec6281f405e9
399
pds03-backend
MIT License
src/main/kotlin/icu/windea/pls/core/search/ParadoxQuery.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.core.search import com.intellij.util.* import icu.windea.pls.* import icu.windea.pls.core.* import icu.windea.pls.core.collections.* import icu.windea.pls.core.selector.* import icu.windea.pls.core.selector.chained.* import java.util.function.* /** * 可对查询结果进行进一步的处理。 * * 进一步的过滤、排序和去重。 * * 可处理查找单个和查找所有的路基有所不同的情况。 * * 可处理存在默认值的情况。 * @see ParadoxSearchParameters * @see ParadoxSelector * @see ChainedParadoxSelector */ class ParadoxQuery<T, P : ParadoxSearchParameters<T>>( private val original: Query<T>, private val searchParameters: P ) : AbstractQuery<T>() { override fun processResults(consumer: Processor<in T>): Boolean { return delegateProcessResults(original, CommonProcessors.UniqueProcessor(consumer)) } fun find(exact: Boolean): T? { return if(exact) find() else findFirst() } fun find(): T? { val preferOverridden = getSettings().preferOverridden val selector = searchParameters.selector var result: T? = null delegateProcessResults(original) { if(selector.select(it)) { result = it preferOverridden } else { true } } return result ?: selector.defaultValue } override fun findFirst(): T? { val selector = searchParameters.selector var result: T? = null delegateProcessResults(original) { if(selector.select(it)) { result = it false } else { true } } return result ?: selector.defaultValue } override fun findAll(): Set<T> { val selector = searchParameters.selector val result = MutableSet(selector.comparator()) delegateProcessResults(original) { if(selector.selectAll(it)) { result.add(it) } true } return result } override fun forEach(consumer: Processor<in T>): Boolean { //这里不进行排序 val selector = searchParameters.selector return delegateProcessResults(original) { if(selector.selectAll(it)) { val r = consumer.process(it) if(!r) return@delegateProcessResults false } true } } override fun toString(): String { return "ParadoxQuery: $original" } } fun <R : Any, P : ParadoxSearchParameters<R>> QueryFactory<R, P>.createParadoxQuery(parameters: P): ParadoxQuery<R, P> { return ParadoxQuery(createQuery(parameters), parameters) }
2
Kotlin
2
13
420d29dfe90a863155d022367fd60e8b33babac4
2,223
Paradox-Language-Support
MIT License
app/src/main/java/com/whl/testflow/testKT/testHeighterOrderFun/testlambdaandfunction.kt
wanghailong0526
614,267,321
false
{"Kotlin": 72161, "Java": 1155}
package com.whl /** * * @date : * @author : wanghailong * * @description: TODO * */ /** * 1.Unit 等于 java 的 void * 2.?表示可空 * 3.Any 非空类型的超类,包含 int 等基本数据类型,不包含 null,如果要包含 null ,使用 Any? * 4.java 中的 Object 是引用类型的超类,不包含基本数据类型。基本数据类型想要使用引用必须使用包装类,如:Java.lang.Integer * 5. :: 操作符 ::aa (aa 是个函数,::aa 意思是将一个函数作为函数引用赋值给一个变量) * fun aa(){} * var a4 = ::aa; * 6.使用 lambda 表示函数声明 ()->Unit 其中 ()表示方法的参数,这里是无参,有参数使用逗号隔开, Unit 表示无返回值 * 7.若方法只有一个参数 在实现处默认使用 it 代替,可以复写修改参数名 * 8.函数最后一行是返回值 可以没有 return 关键字 * 9._ 表示拒收,如: 一个方法不接收某个位置的参数 fun( _ , value : Int) * 10.==_值的比较 ===_是否是同一个对象 java 中 ==_是否是同一个对象或同一个引用 equals_值的比较 * 11.给类添加匿名函数 类.() 如: String.() 给 String 添加匿名函数,lambda 内部会持有 String 的 this * 12.函数中的 lambda 就是高阶函数,函数中的函数 * 13.只要是高阶函数,必须用inline修饰(作用是内联),为什么,因为内部会对lambda做优化 * 14.crossinline 你的这个lambda不要给我内联 优化 */ fun main() { //使用 lambda 表示函数声明 var method1: () -> Unit var method2: (Int, Int) -> Any var method3: (String, Double) -> Int // method1()//无法调用,需要初始化 //使用 lambda 表示函数声明与实现结合 var method6: () -> Unit = { println("我是method6") } //{ println("我是method6") } 匿名函数,将这个匿名函数赋值给 method6 这个变量 method6() method6.invoke() var method7 = { println("我是method7") } method7() var method8: (String) -> Unit = { str: String -> println("method8 传入参数值为${str}") } method8("kwg kwg ") var method9: (String) -> Unit = { println("method9 传入参数为$it") } method9("****") var method10 = { value: Any? -> println("method10 传入参数为$value") } method10(10) method10("3333333") var method11: (Int, Int) -> Any? = { n1: Int, n2: Int -> n1.toString() + n2.toString() } println(method11(1, 1)) //先声明 var method12: (Int) -> String //再实现 method12 = fun(value) = value.toString() println(method12(34567)) //声明+实现结合 var method13: (Int) -> String = { it.toString() } println(method13(444444)) var method14: (Int) -> Unit = { when (it) {//when 表达式 1 -> println("传递的是1") in 1..20 -> println("传递的是1-20之间的值") else -> println("啥也不是") } } method14(16) method14(1) method14(40) var method15: (Int, Int) -> Unit = { _, n2 -> println("第二个参数的值为$n2") } method15(2, 5) var method17 = { str: Any? -> println("method17 你传入了 $str") str//最后一行是返回值 } var str = method17("wl") println("接收到 " + str) var method18: String.() -> Unit = { println("你是$this") } "1111111".method18() var method19: Int.(Int) -> String = { "$this+$it=${this + it}" } println(method19(1, 2)) println(1.method19(2)) //输出 fun t1() { println(1) }//返回值类型为 Unit 除非指定类型 fun t2() { 22222 }//默认 Unit //返回值为 String 类型 fun t3(): String { return "" } fun t4() { // return 11111 //报错 因为声明时没有指定类型,此时返回 int 报错 } //run返回 实现{}里面的函数返回类型 fun t5(): Boolean = run { true } t5() //函数返回值是函数 fun t6(): () -> Boolean = { true } t6()()//执行函数返回的函数 fun t7() = { data: Any? -> println("你输入的类型${if (data is Int) "是 Int 类型 $data" else "不是 int 类型 $data"}") } t7()(88) t7()('a') fun aa() {}// 标准的函数 var ab = {}//接收匿名函数的变量 var ac = ::aa//使用 :: 将 aa 变成函数引用 }
0
Kotlin
0
0
f3b9971464ba2458251e6151dad2441913b5b891
3,305
testKotlin
Apache License 2.0
examples/real-estate/editor/src/main/kotlin/realestateeditor/data/ApplicationState.kt
FHNW-IP5-IP6
462,228,811
false
null
package realestateeditor.data data class ApplicationState(val isDialogOpen: Boolean = false, val realEstates: List<RealEstateData>)
0
Kotlin
0
1
57e4ecb262807e4dc131b4f0d01d25af787687e4
132
ComposeWorkbench
Apache License 2.0
app/src/main/java/me/bakumon/moneykeeper/ui/typesort/TypeSortViewModel.kt
githubzoujiayun
139,397,411
true
{"Kotlin": 349013}
/* * Copyright 2018 Bakumon. https://github.com/Bakumon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.bakumon.moneykeeper.ui.typesort import io.reactivex.Completable import io.reactivex.Flowable import me.bakumon.moneykeeper.base.BaseViewModel import me.bakumon.moneykeeper.database.entity.RecordType import me.bakumon.moneykeeper.datasource.AppDataSource /** * 类型排序 ViewModel * * @author Bakumon https://bakumon.me */ class TypeSortViewModel(dataSource: AppDataSource) : BaseViewModel(dataSource) { fun getRecordTypes(type: Int): Flowable<List<RecordType>> { return mDataSource.getRecordTypes(type) } fun sortRecordTypes(recordTypes: List<RecordType>): Completable { return mDataSource.sortRecordTypes(recordTypes) } }
0
Kotlin
0
0
fbb1f3e3698c24c1ad004f3bf9ba67000da1f675
1,289
MoneyKeeper
Apache License 2.0