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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/fragment/di/SettingFragmentViewModelModule.kt
|
rei-m
| 45,727,691
| false
| null |
/*
* Copyright (c) 2017. <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hbfavmaterial.viewmodel.widget.fragment.di
import dagger.Module
import dagger.Provides
import me.rei_m.hbfavmaterial.di.ForFragment
import me.rei_m.hbfavmaterial.model.UserModel
import me.rei_m.hbfavmaterial.viewmodel.widget.fragment.SettingFragmentViewModel
@Module
class SettingFragmentViewModelModule {
@Provides
@ForFragment
internal fun provideViewModelFactory(userModel: UserModel): SettingFragmentViewModel.Factory =
SettingFragmentViewModel.Factory(userModel)
}
| 0
|
Kotlin
|
7
| 21
|
79ebe1d902212c681df05182bc4e0958b5767be7
| 1,096
|
HBFav_material
|
Apache License 2.0
|
sdk/backend/src/main/kotlin/com/supertokens/sdk/recipes/thirdparty/providers/bitbucket/BitbucketGetUserResponse.kt
|
Appstractive
| 656,572,792
| false
|
{"Kotlin": 415391, "Ruby": 2302}
|
package com.supertokens.sdk.recipes.thirdparty.providers.bitbucket
import kotlinx.serialization.Serializable
@Serializable
data class BitbucketGetUserResponse(
val uuid: String,
val email: String?,
)
| 5
|
Kotlin
|
1
| 3
|
e4d0ff3664034d1c4981a0a2cdf58c3a053da2a7
| 210
|
supertokens-kt
|
Apache License 2.0
|
app/src/main/java/cn/starrah/thu_course_helper/data/database/CalendarDatabase.kt
|
Starrah
| 258,453,814
| false
| null |
package cn.starrah.thu_course_helper.data.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import cn.starrah.thu_course_helper.data.declares.calendarEntity.CalendarItemData
import cn.starrah.thu_course_helper.data.declares.calendarEntity.CalendarRemindData
import cn.starrah.thu_course_helper.data.declares.calendarEntity.CalendarTimeData
import cn.starrah.thu_course_helper.data.declares.calendarEntity.FastSearchTable
import cn.starrah.thu_course_helper.data.declares.calendarEnum.*
import cn.starrah.thu_course_helper.data.declares.time.TimeInCourseSchedule
import cn.starrah.thu_course_helper.data.declares.time.TimeInHour
@TypeConverters(
CalendarItemType.TC::class,
CalendarItemLegalDetailKey.TC::class,
CalendarTimeType.TC::class,
CalendarRemindType.TC::class,
CalendarRemindMethodType.TC::class,
CalendarItemData.TC::class,
CalendarTimeData.TC::class,
CalendarRemindData.TC::class,
TimeInCourseSchedule.TC::class,
TimeInHour.TC::class,
FastSearchTable.TC::class
)
@Database(
entities = [CalendarItemData::class, CalendarTimeData::class, FastSearchTable::class],
version = 1
)
abstract class CalendarDatabase : RoomDatabase() {
abstract fun Dao(): CalendarDao
companion object {
fun getDatabaseInstance(context: Context, name: String): CalendarDatabase {
return Room.databaseBuilder(
context,
CalendarDatabase::class.java,
name
).build()
}
}
}
| 7
|
Kotlin
|
2
| 20
|
64a543518f9007e2b5a615582bd049acf5d2ada9
| 1,622
|
THUCourseHelper
|
MIT License
|
llama-stack-client-kotlin-core/src/main/kotlin/com/llama_stack_client/api/services/blocking/ShieldService.kt
|
meta-llama
| 854,913,926
| false
|
{"Kotlin": 2020773, "Shell": 2562}
|
// File generated from our OpenAPI spec by Stainless.
@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102
package com.llama_stack_client.api.services.blocking
import com.llama_stack_client.api.core.RequestOptions
import com.llama_stack_client.api.models.ShieldGetParams
import com.llama_stack_client.api.models.ShieldListParams
import com.llama_stack_client.api.models.ShieldSpec
interface ShieldService {
fun list(
params: ShieldListParams,
requestOptions: RequestOptions = RequestOptions.none()
): ShieldSpec
fun get(
params: ShieldGetParams,
requestOptions: RequestOptions = RequestOptions.none()
): ShieldSpec?
}
| 0
|
Kotlin
|
2
| 0
|
ee76c5aec1d582dbbd2759d084ba16b8b74f04ea
| 710
|
llama-stack-client-kotlin
|
Apache License 2.0
|
app/src/main/java/com/kl3jvi/animity/data/repository/NotificationsRepositoryImpl.kt
|
kl3jvi
| 286,457,139
| false
| null |
package com.kl3jvi.animity.data.repository
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.kl3jvi.animity.data.network.anilist_service.AniListGraphQlClient
import com.kl3jvi.animity.data.paging.NotificationPagingSource
import com.kl3jvi.animity.data.paging.PagingDataItem
import com.kl3jvi.animity.domain.repositories.NotificationsRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import javax.inject.Inject
class NotificationsRepositoryImpl @Inject constructor(
private val aniListGraphQlClient: AniListGraphQlClient,
private val ioDispatcher: CoroutineDispatcher
) : NotificationsRepository {
override fun getNotifications(): Flow<PagingData<PagingDataItem>> {
val pager = Pager(
config = PagingConfig(enablePlaceholders = true, pageSize = 20),
pagingSourceFactory = { NotificationPagingSource(aniListGraphQlClient) }
).flow
return pager.flowOn(ioDispatcher)
}
}
| 4
|
Kotlin
|
31
| 729
|
f86d279827fd59974078676a03ec6a6a737f6740
| 1,076
|
animity
|
MIT License
|
shared/src/commonMain/kotlin/repository/SessionRepository.kt
|
sdercolin
| 708,470,210
| false
| null |
package repository
import androidx.compose.runtime.staticCompositionLocalOf
import exception.SessionRenameExistingException
import exception.SessionRenameInvalidException
import io.Paths
import io.sessionsDirectory
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import model.Reclist
import model.Session
import model.SessionParams
import model.toParams
import util.DateTime
import util.isValidFileName
import util.parseJson
import util.stringifyJson
/**
* A repository to manage sessions.
*/
class SessionRepository(private val reclistRepository: ReclistRepository) {
private val folder = Paths.sessionsDirectory.also {
if (!it.exists()) {
it.mkdirs()
}
}
private val _items = MutableStateFlow(emptyList<String>())
/**
* The list of existing session names.
*/
val items: StateFlow<List<String>> = _items
/**
* Fetches the list of sessions.
*/
fun fetch() {
val items = folder.listFiles()
.filter { it.isDirectory }
.filter { it.resolve(SESSION_PARAMS_FILE_NAME).isFile }
.map { it.name }
_items.value = items
}
/**
* Creates a new session with the given reclist.
*/
fun create(reclist: Reclist): Result<Session> =
runCatching {
val timeSuffix = DateTime.getNowReadableString(withTime = false)
val defaultName = "${reclist.name} $timeSuffix"
var name = defaultName
var repeat = 0
while (name in _items.value) {
repeat++
name = "$defaultName ($repeat)"
}
Session(
name,
reclist,
folder.resolve(name).absolutePath,
)
}.onSuccess {
_items.value = listOf(it.name) + _items.value
save(it)
}
/**
* Gets the session with the given name.
*/
fun get(name: String): Result<Session> =
runCatching {
val directory = folder.resolve(name)
val file = directory.resolve(SESSION_PARAMS_FILE_NAME)
val params = file.readText().parseJson<SessionParams>()
val reclist = reclistRepository.get(params.reclistName)
Session(
name,
reclist,
directory.absolutePath,
)
}
/**
* Rename the session with the given [oldName] to [newName]. This will cause the session folder to be renamed as
* well.
*/
fun rename(
oldName: String,
newName: String,
): Result<Session> =
runCatching {
if (oldName == newName) {
return@runCatching get(oldName).getOrThrow()
}
if (newName.isValidFileName().not()) {
throw SessionRenameInvalidException(newName)
}
val oldDirectory = folder.resolve(oldName)
val newDirectory = folder.resolve(newName)
if (newDirectory.exists()) {
throw SessionRenameExistingException(newName)
}
oldDirectory.copyTo(newDirectory)
oldDirectory.delete()
val file = newDirectory.resolve(SESSION_PARAMS_FILE_NAME)
val params = file.readText().parseJson<SessionParams>()
val reclist = reclistRepository.get(params.reclistName)
Session(
newName,
reclist,
newDirectory.absolutePath,
)
}.onSuccess {
_items.value = _items.value.map { name ->
if (name == oldName) {
newName
} else {
name
}
}
}
/**
* Deletes the sessions with the given names.
*/
fun delete(names: List<String>) {
names.forEach { name ->
val directory = folder.resolve(name)
directory.delete()
}
_items.value = _items.value.filterNot { it in names }
}
private fun save(session: Session) {
val directory = folder.resolve(session.name)
if (directory.exists().not()) {
directory.mkdirs()
}
val file = directory.resolve(SESSION_PARAMS_FILE_NAME)
val params = session.toParams()
file.writeText(params.stringifyJson())
}
}
private const val SESSION_PARAMS_FILE_NAME = "session.json"
val LocalSessionRepository = staticCompositionLocalOf<SessionRepository> {
error("No SessionRepository provided")
}
| 1
| null |
1
| 9
|
8ed61865b56192b1e484f2e36ddc0a33ec79e8e5
| 4,608
|
recstar
|
Apache License 2.0
|
androidapp/app/src/main/java/eu/miaounyan/isthereanynetwork/utils/PermittedToast.kt
|
Tordesillas
| 150,395,855
| false
|
{"Java": 40088, "Kotlin": 24332, "JavaScript": 16705, "Dockerfile": 380, "HTML": 176, "CSS": 111}
|
package eu.miaounyan.isthereanynetwork.utils
import android.content.Context
import android.widget.Toast
import eu.miaounyan.isthereanynetwork.MainActivity.PERMISSIONS
import eu.miaounyan.isthereanynetwork.service.PermissionManager
class PermittedToast(context: Context) : Toast(context) {
companion object {
val permissionManager = PermissionManager()
fun makeText(context: Context?, text: CharSequence, duration: Int): Toast? {
if (context == null)
return null
// missing permissions, don't show Toasts that may overlay
if (!permissionManager.checkPermissions(context, *PERMISSIONS))
return null
return Toast.makeText(context, text, duration)
}
}
}
| 1
| null |
1
| 1
|
bcb2e9e86f72e6986ea683052c0c678d9927e60c
| 766
|
IsThereAnyNetwork
|
MIT License
|
travis-interface/src/main/java/com/kevalpatel2106/greenbuild/travisInterface/entities/TravisAuthor.kt
|
kevalpatel2106
| 129,620,378
| false
| null |
/*
* Copyright 2018 <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.kevalpatel2106.greenbuild.travisInterface.entities
import com.google.gson.annotations.SerializedName
import com.kevalpatel2106.grrenbuild.entities.Author
/**
* Created by Kevalpatel2106 on 18-Apr-18.
*
* @author <a href="https://github.com/kevalpatel2106">kevalpatel2106</a>
*/
internal data class TravisAuthor(
@field:SerializedName("id")
val id: Int,
@field:SerializedName("login")
val login: String,
@field:SerializedName("@href")
val href: String
){
fun toAuthor() = Author(
username = login,
avatar = null
)
}
| 6
|
Kotlin
|
14
| 75
|
da9f2e64cd09848528f313d0e3188b7c40f4b3f7
| 1,215
|
green-build
|
Apache License 2.0
|
data-app-data/src/main/java/com/melonhead/data_app_data/AppDataService.kt
|
taffyrat
| 542,405,576
| false
| null |
package com.melonhead.mangadexfollower.services
import android.content.Context
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.melonhead.mangadexfollower.db.firebase.FirebaseDbUser
import com.melonhead.mangadexfollower.extensions.addValueEventListenerFlow
import com.melonhead.mangadexfollower.models.auth.AuthToken
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
enum class RenderStyle {
Native, WebView, Browser
}
interface AppDataService {
val token: Flow<AuthToken?>
val installDateSeconds: Flow<Long?>
val lastRefreshDateSeconds: Flow<Long?>
val userIdFlow: Flow<String?>
val renderStyle: RenderStyle
val useDataSaver: Boolean
val chapterTapAreaSize: Dp
val showReadChapterCount: Int
suspend fun updateToken(token: AuthToken?)
suspend fun updateInstallTime()
suspend fun updateLastRefreshDate()
suspend fun updateUserId(id: String)
suspend fun updateRenderStyle(renderStyle: RenderStyle)
suspend fun setUseDataSaver(useDataSaver: Boolean)
suspend fun setShowReadChapterCount(readChapterCount: Int)
}
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "auth")
class AppDataServiceImpl(
private val appContext: Context,
externalScope: CoroutineScope,
): AppDataService {
private val firebaseDb = Firebase.database
private val AUTH_TOKEN = stringPreferencesKey("auth_token")
private val REFRESH_TOKEN = stringPreferencesKey("refresh_token")
private val USER_ID = stringPreferencesKey("user_id")
private var hasFetchedDbUser = false
private val authTokenFlow: Flow<String> = appContext.dataStore.data.map { preferences ->
// No type safety.
preferences[AUTH_TOKEN] ?: ""
}.distinctUntilChanged()
init {
externalScope.launch(IO) {
userIdFlow.collectLatest {
val userDb = userDb()
if (userDb != null) {
userDb.addValueEventListenerFlow(FirebaseDbUser::class.java).collectLatest { user ->
mutableCurrentFirebaseDBUser.value = user
if (user == null) updateInstallTime()
hasFetchedDbUser = true
}
} else {
mutableCurrentFirebaseDBUser.value = null
}
}
}
}
private val refreshTokenFlow: Flow<String> = appContext.dataStore.data.map { preferences ->
// No type safety.
preferences[REFRESH_TOKEN] ?: ""
}.distinctUntilChanged()
override val userIdFlow: Flow<String> = appContext.dataStore.data.map { preferences ->
// No type safety.
preferences[USER_ID] ?: ""
}.distinctUntilChanged()
private val mutableCurrentFirebaseDBUser = MutableStateFlow<FirebaseDbUser?>(null)
private val currentFirebaseDBUser = mutableCurrentFirebaseDBUser.asStateFlow()
override val installDateSeconds: Flow<Long?> = currentFirebaseDBUser.map {
it?.installDateSeconds
}.distinctUntilChanged()
override val lastRefreshDateSeconds: Flow<Long?> = currentFirebaseDBUser.map {
it?.lastRefreshDateSeconds
}.distinctUntilChanged()
override var token: Flow<AuthToken?> = authTokenFlow.combine(refreshTokenFlow) { auth, refresh ->
if (auth.isBlank() || refresh.isBlank()) return@combine null
AuthToken(auth, refresh)
}.distinctUntilChanged()
override val renderStyle: RenderStyle
get() = RenderStyle.Native
override val useDataSaver: Boolean
get() = false
override val chapterTapAreaSize: Dp
get() = 60.dp
override val showReadChapterCount: Int
get() = 3
override suspend fun updateToken(token: AuthToken?) {
appContext.dataStore.edit { settings ->
if (settings[AUTH_TOKEN] != token?.session)
settings[AUTH_TOKEN] = token?.session ?: ""
if (settings[REFRESH_TOKEN] != token?.refresh)
settings[REFRESH_TOKEN] = token?.refresh ?: ""
}
}
private suspend fun userDb(): DatabaseReference? {
val userId = userIdFlow.firstOrNull() ?: return null
if (userId.isBlank()) return null
return firebaseDb.getReference("users").child(userId)
}
private fun currentDbUser(): FirebaseDbUser {
return currentFirebaseDBUser.value ?: FirebaseDbUser()
}
override suspend fun updateInstallTime() {
val userDb = userDb() ?: return
val new = currentDbUser()
if (new.installDateSeconds != null || !hasFetchedDbUser) return
userDb.setValue(new.copy(installDateSeconds = Clock.System.now().epochSeconds))
}
override suspend fun updateLastRefreshDate() {
val userDb = userDb() ?: return
val new = currentDbUser().copy(lastRefreshDateSeconds = Clock.System.now().epochSeconds)
userDb.setValue(new)
}
override suspend fun updateUserId(id: String) {
appContext.dataStore.edit { settings ->
settings[USER_ID] = id
}
}
override suspend fun updateRenderStyle(renderStyle: RenderStyle) {
TODO("Not yet implemented")
}
override suspend fun setUseDataSaver(useDataSaver: Boolean) {
TODO("Not yet implemented")
}
override suspend fun setShowReadChapterCount(readChapterCount: Int) {
TODO("Not yet implemented")
}
}
| 8
|
Kotlin
|
0
| 0
|
ee2deda19aa43f7480da66f65ad7409cfe1c53a9
| 6,277
|
mangadexdroid
|
Do What The F*ck You Want To Public License
|
data-app-data/src/main/java/com/melonhead/data_app_data/AppDataService.kt
|
taffyrat
| 542,405,576
| false
| null |
package com.melonhead.mangadexfollower.services
import android.content.Context
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.melonhead.mangadexfollower.db.firebase.FirebaseDbUser
import com.melonhead.mangadexfollower.extensions.addValueEventListenerFlow
import com.melonhead.mangadexfollower.models.auth.AuthToken
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
enum class RenderStyle {
Native, WebView, Browser
}
interface AppDataService {
val token: Flow<AuthToken?>
val installDateSeconds: Flow<Long?>
val lastRefreshDateSeconds: Flow<Long?>
val userIdFlow: Flow<String?>
val renderStyle: RenderStyle
val useDataSaver: Boolean
val chapterTapAreaSize: Dp
val showReadChapterCount: Int
suspend fun updateToken(token: AuthToken?)
suspend fun updateInstallTime()
suspend fun updateLastRefreshDate()
suspend fun updateUserId(id: String)
suspend fun updateRenderStyle(renderStyle: RenderStyle)
suspend fun setUseDataSaver(useDataSaver: Boolean)
suspend fun setShowReadChapterCount(readChapterCount: Int)
}
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "auth")
class AppDataServiceImpl(
private val appContext: Context,
externalScope: CoroutineScope,
): AppDataService {
private val firebaseDb = Firebase.database
private val AUTH_TOKEN = stringPreferencesKey("auth_token")
private val REFRESH_TOKEN = stringPreferencesKey("refresh_token")
private val USER_ID = stringPreferencesKey("user_id")
private var hasFetchedDbUser = false
private val authTokenFlow: Flow<String> = appContext.dataStore.data.map { preferences ->
// No type safety.
preferences[AUTH_TOKEN] ?: ""
}.distinctUntilChanged()
init {
externalScope.launch(IO) {
userIdFlow.collectLatest {
val userDb = userDb()
if (userDb != null) {
userDb.addValueEventListenerFlow(FirebaseDbUser::class.java).collectLatest { user ->
mutableCurrentFirebaseDBUser.value = user
if (user == null) updateInstallTime()
hasFetchedDbUser = true
}
} else {
mutableCurrentFirebaseDBUser.value = null
}
}
}
}
private val refreshTokenFlow: Flow<String> = appContext.dataStore.data.map { preferences ->
// No type safety.
preferences[REFRESH_TOKEN] ?: ""
}.distinctUntilChanged()
override val userIdFlow: Flow<String> = appContext.dataStore.data.map { preferences ->
// No type safety.
preferences[USER_ID] ?: ""
}.distinctUntilChanged()
private val mutableCurrentFirebaseDBUser = MutableStateFlow<FirebaseDbUser?>(null)
private val currentFirebaseDBUser = mutableCurrentFirebaseDBUser.asStateFlow()
override val installDateSeconds: Flow<Long?> = currentFirebaseDBUser.map {
it?.installDateSeconds
}.distinctUntilChanged()
override val lastRefreshDateSeconds: Flow<Long?> = currentFirebaseDBUser.map {
it?.lastRefreshDateSeconds
}.distinctUntilChanged()
override var token: Flow<AuthToken?> = authTokenFlow.combine(refreshTokenFlow) { auth, refresh ->
if (auth.isBlank() || refresh.isBlank()) return@combine null
AuthToken(auth, refresh)
}.distinctUntilChanged()
override val renderStyle: RenderStyle
get() = RenderStyle.Native
override val useDataSaver: Boolean
get() = false
override val chapterTapAreaSize: Dp
get() = 60.dp
override val showReadChapterCount: Int
get() = 3
override suspend fun updateToken(token: AuthToken?) {
appContext.dataStore.edit { settings ->
if (settings[AUTH_TOKEN] != token?.session)
settings[AUTH_TOKEN] = token?.session ?: ""
if (settings[REFRESH_TOKEN] != token?.refresh)
settings[REFRESH_TOKEN] = token?.refresh ?: ""
}
}
private suspend fun userDb(): DatabaseReference? {
val userId = userIdFlow.firstOrNull() ?: return null
if (userId.isBlank()) return null
return firebaseDb.getReference("users").child(userId)
}
private fun currentDbUser(): FirebaseDbUser {
return currentFirebaseDBUser.value ?: FirebaseDbUser()
}
override suspend fun updateInstallTime() {
val userDb = userDb() ?: return
val new = currentDbUser()
if (new.installDateSeconds != null || !hasFetchedDbUser) return
userDb.setValue(new.copy(installDateSeconds = Clock.System.now().epochSeconds))
}
override suspend fun updateLastRefreshDate() {
val userDb = userDb() ?: return
val new = currentDbUser().copy(lastRefreshDateSeconds = Clock.System.now().epochSeconds)
userDb.setValue(new)
}
override suspend fun updateUserId(id: String) {
appContext.dataStore.edit { settings ->
settings[USER_ID] = id
}
}
override suspend fun updateRenderStyle(renderStyle: RenderStyle) {
TODO("Not yet implemented")
}
override suspend fun setUseDataSaver(useDataSaver: Boolean) {
TODO("Not yet implemented")
}
override suspend fun setShowReadChapterCount(readChapterCount: Int) {
TODO("Not yet implemented")
}
}
| 8
|
Kotlin
|
0
| 0
|
ee2deda19aa43f7480da66f65ad7409cfe1c53a9
| 6,277
|
mangadexdroid
|
Do What The F*ck You Want To Public License
|
src/main/kotlin/io/github/ydwk/ydwk/evm/event/events/user/GenericUserUpdateEvent.kt
|
YDWK
| 527,250,343
| false
| null |
/*
* Copyright 2022 YDWK inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.ydwk.ydwk.evm.event.events.user
import io.github.ydwk.yde.entities.User
import io.github.ydwk.ydwk.YDWK
import io.github.ydwk.ydwk.evm.backend.update.IEventUpdate
/**
* This event is triggered when a user is updated.
*
* @param ydwk The [YDWK] instance.
* @param entity The user whose avatar was updated.
* @param oldValue The user's old value.
* @param newValue The user's new value.
*/
open class GenericUserUpdateEvent<T>(
override val ydwk: YDWK,
override val entity: User,
override val oldValue: T,
override val newValue: T
) : IEventUpdate<User, T>
| 9
| null |
1
| 2
|
7e479b29ddca2e0d9093ab8c5dae6892f5640d80
| 1,198
|
YDWK
|
Apache License 2.0
|
src/main/kotlin/no/nav/navnosearchapi/service/search/queries/filterQueries.kt
|
navikt
| 654,102,354
| false
|
{"Kotlin": 80618, "Dockerfile": 257}
|
package no.nav.navnosearchapi.service.search.queries
import org.opensearch.index.query.ExistsQueryBuilder
import org.opensearch.index.query.RangeQueryBuilder
import org.opensearch.index.query.TermQueryBuilder
import java.time.ZonedDateTime
fun termQuery(field: String, value: String): TermQueryBuilder {
return TermQueryBuilder(field, value)
}
fun existsQuery(field: String): ExistsQueryBuilder {
return ExistsQueryBuilder(field)
}
fun rangeQuery(field: String, gte: ZonedDateTime? = null, lte: ZonedDateTime? = null): RangeQueryBuilder {
return RangeQueryBuilder(field).from(gte).to(lte)
}
| 8
|
Kotlin
|
0
| 0
|
c427296c1b74c2ea53022d8799a6e35806228c33
| 606
|
navno-search-api
|
MIT License
|
store/src/commonTest/kotlin/earth/levi/batterybird/store/commonTest.kt
|
levibostian
| 640,550,940
| false
| null |
package earth.levi.batterybird.store
import kotlin.test.Test
import kotlin.test.assertTrue
class CommonGreetingTest {
@Test
fun testExample() {
assertTrue(true)
}
}
| 0
|
Kotlin
|
0
| 0
|
a060baeb7b5abf3d0069d932ed44dd339cc3bc57
| 187
|
BatteryBird
|
MIT License
|
codyze-backends/cpg/src/main/kotlin/de/fraunhofer/aisec/codyze/backends/cpg/coko/dsl/ImplementationDsl.kt
|
Fraunhofer-AISEC
| 233,193,643
| false
|
{"Kotlin": 531673, "Java": 30004, "C++": 2542, "ANTLR": 1935, "Go": 1398, "Python": 617, "Dockerfile": 607}
|
/*
* Copyright (c) 2022, Fraunhofer AISEC. 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.
*/
@file:Suppress("TooManyFunctions")
package de.fraunhofer.aisec.codyze.backends.cpg.coko.dsl
import de.fraunhofer.aisec.codyze.backends.cpg.coko.Nodes
import de.fraunhofer.aisec.codyze.backends.cpg.coko.dsl.Result.*
import de.fraunhofer.aisec.codyze.specificationLanguages.coko.core.CokoBackend
import de.fraunhofer.aisec.codyze.specificationLanguages.coko.core.CokoMarker
import de.fraunhofer.aisec.codyze.specificationLanguages.coko.core.dsl.*
import de.fraunhofer.aisec.codyze.specificationLanguages.coko.core.modelling.DataItem
import de.fraunhofer.aisec.codyze.specificationLanguages.coko.core.modelling.Definition
import de.fraunhofer.aisec.codyze.specificationLanguages.coko.core.modelling.ParameterGroup
import de.fraunhofer.aisec.codyze.specificationLanguages.coko.core.modelling.Signature
import de.fraunhofer.aisec.cpg.TranslationResult
import de.fraunhofer.aisec.cpg.graph.*
import de.fraunhofer.aisec.cpg.graph.declarations.ValueDeclaration
import de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression
import de.fraunhofer.aisec.cpg.graph.statements.expressions.ConstructExpression
import de.fraunhofer.aisec.cpg.graph.statements.expressions.Expression
import de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberExpression
import de.fraunhofer.aisec.cpg.query.*
//
// all functions/properties defined here must use CokoBackend
// when they should be available in Coko
//
val CokoBackend.cpg: TranslationResult
get() = this.backendData as TranslationResult
/** Get all [Nodes] that are associated with this [Op]. */
context(CokoBackend)
fun Op.cpgGetAllNodes(): Collection<CallExpression> =
when (this@Op) {
is FunctionOp ->
this@Op.definitions.flatMap { def -> this@CokoBackend.cpgCallFqn(def.fqn) }
is ConstructorOp -> this@CokoBackend.cpgConstructor(this.classFqn)
is GroupingOp -> this@Op.ops.flatMap { it.cpgGetAllNodes() }
is ConditionalOp -> {
val resultNodes = resultOp.cpgGetAllNodes()
val conditionNodes = conditionOp.cpgGetAllNodes()
resultNodes.filter { resultNode ->
conditionNodes.any { conditionNode ->
dataFlow(conditionNode, resultNode).value
}
}
}
}
/**
* Get all [Nodes] that are associated with this [Op] and fulfill the [Signature]s of the
* [Definition]s.
*/
context(CokoBackend)
fun Op.cpgGetNodes(): Map<CallExpression, Result> =
when (this@Op) {
is FunctionOp -> {
val results = mutableListOf<Result>()
val fqn = this@Op.definitions.flatMap { def ->
this@CokoBackend.cpgCallFqn(def.fqn) {
def.signatures.any { sig ->
// We consider a result when both the signature and the flow are not invalid
// However, if at least one of them is OPEN we propagate this information to the caller
val signature = cpgSignature(*sig.parameters.toTypedArray())
val flow = sig.unorderedParameters.allResult { it?.cpgFlowsTo(arguments) }
if (signature != INVALID && flow != INVALID) {
results.add(signature.and(flow))
} else {
false
}
}
}
}
fqn.zip(results).toMap()
}
is ConstructorOp -> {
val results = mutableListOf<Result>()
val fqn = this@Op.signatures.flatMap { sig ->
this@CokoBackend.cpgConstructor(this@Op.classFqn) {
val signature = cpgSignature(*sig.parameters.toTypedArray())
val flow = sig.unorderedParameters.allResult { it?.cpgFlowsTo(arguments) }
if (signature != INVALID && flow != INVALID) {
results.add(signature.and(flow))
} else {
false
}
}
}
fqn.zip(results).toMap()
}
is GroupingOp -> this@Op.ops.flatMap { it.cpgGetNodes().entries }.associate { it.toPair() }
is ConditionalOp -> {
val resultNodes = resultOp.cpgGetNodes()
val conditionNodes = conditionOp.cpgGetNodes()
resultNodes.filter { resultNode ->
conditionNodes.any { conditionNode ->
// TODO: Is it correct to use the EOG relationship here?
val result = executionPath(conditionNode.key, resultNode.key)
result.value
}
}
}
}
/** Returns a list of [ValueDeclaration]s with the matching name. */
fun CokoBackend.cpgVariable(name: String): List<ValueDeclaration> {
return cpg.allChildren { it.name.lastPartsMatch(name) }
}
/** Returns a list of [ValueDeclaration]s with the matching [fqn]. */
fun CokoBackend.cpgVariableFqn(fqn: String): List<ValueDeclaration> {
return cpg.allChildren { it.name.toString() == fqn }
}
/** Returns a list of [ConstructExpression]s with the matching [classFqn] and fulfilling [predicate]. */
fun CokoBackend.cpgConstructor(
classFqn: String,
predicate: (@CokoMarker CallExpression).() -> Boolean = { true }
): List<ConstructExpression> {
return cpg.calls.filterIsInstance<ConstructExpression>().filter {
it.type.typeName == classFqn && predicate(it)
}
}
/** Returns a list of [CallExpression]s with the matching [name] and fulfilling [predicate]. */
fun CokoBackend.cpgCall(
name: String,
predicate: (@CokoMarker CallExpression).() -> Boolean = { true }
): List<CallExpression> {
return cpg.calls { it.name.lastPartsMatch(name) && predicate(it) }
}
/**
* Returns a list of [CallExpression]s with the matching [fqn] (fully-qualified name) and fulfilling
* [predicate].
*/
fun CokoBackend.cpgCallFqn(
fqn: String,
predicate: (@CokoMarker CallExpression).() -> Boolean = { true }
): List<CallExpression> {
return cpg.calls { it.name.toString() == fqn && predicate(it) }
}
/** Returns a list of [MemberExpression]s with the matching something. */
fun CokoBackend.cpgMemberExpr(
predicate: (@CokoMarker MemberExpression).() -> Boolean
): List<MemberExpression> {
return cpg.allChildren(predicate)
}
// this extension function should only be available in the context of a CallExpression
context(CallExpression)
/**
* Checks if there's a data flow path from "this" to [that].
* - If this is a String, we evaluate it as a regex.
* - If this is a Collection, we check if at least one of the elements flows to [that]
* - If this is a [Node], we use the DFG of the CPG.
*/
infix fun Any.cpgFlowsTo(that: Node): Result =
this.cpgFlowsTo(listOf(that))
// it should only be available in the context of a CallExpression
context(CallExpression)
/**
* Checks if there's a data flow path from "this" to any of the elements in [that].
* - If this is a String, we evaluate it as a regex.
* - If this is a Collection, we check if at least one of the elements flows to [that]
* - If this is a [Node], we use the DFG of the CPG.
*/
infix fun Any.cpgFlowsTo(that: Collection<Node>): Result =
Result.convert(
when (this) {
is Wildcard -> true
is String -> that.any {
val regex = Regex(this)
regex.matches((it as? Expression)?.evaluate()?.toString().orEmpty()) || regex.matches(it.code.orEmpty())
}
// Separate cases for IntRange and LongRange result in a huge performance boost for large ranges
is LongRange, is IntRange -> checkRange(that)
is Iterable<*> -> this.anyResult { it?.cpgFlowsTo(that) }
is Array<*> -> this.anyResult { it?.cpgFlowsTo(that) }
is Node -> that.any { dataFlow(this, it).value }
is ParameterGroup -> this.parameters.allResult { it?.cpgFlowsTo(that) }
else -> this in that.map { (it as Expression).evaluate() }
}
)
private fun Any.checkRange(that: Collection<Node>): Boolean {
when (this) {
// I would love to combine the following two cases, but any implementation loses the benefit of
// quickly reading the last value of the range, therefore making the whole distinction useless.
is IntRange -> {
return that.all {
val minValue = min(it).value.toInt()
val maxValue = max(it).value.toInt()
minValue > this.first && maxValue < this.last
}
}
is LongRange -> {
return that.all {
val minValue = min(it).value.toInt()
val maxValue = max(it).value.toInt()
minValue > this.first && maxValue < this.last
}
}
else -> throw IllegalArgumentException("Unexpected type")
}
}
context(CokoBackend)
// TODO: better description
// TODO: in mark there is "..." to symbolize that the last arguments don't matter
// TODO: how to model return value assignments
/**
* Checks if the [CallExpression] matches the signature specified with [parameters]. Returns false
* if there are nulls in [parameters],
*
* @param parameters specifies the order of the parameters of the function.
*
* If a parameter is a [Type] object, the function will check if the argument has the same type.
*
* If a parameter is a [ParamWithType] object, the function will check if the argument has
* the same type and if the [Any] object flows to the argument
*
* @param hasVarargs specifies if the function has a variable number of arguments at the end which
* are not important to the analysis
*/
@Suppress("UnsafeCallOnNullableType")
fun CallExpression.cpgSignature(vararg parameters: Any?, hasVarargs: Boolean = false): Result {
// checks if amount of parameters is the same as amount of arguments of this CallExpression
if (cpgCheckArgsSize(parameters, hasVarargs)) {
// checks if the CallExpression matches with the parameters
return parameters.withIndex().allResult { (i: Int, parameter: Any?) ->
when (parameter) {
// if any parameter is null, signature returns false
null -> INVALID
is ParamWithType ->
// if `parameter` is a `ParamWithType` object we want to check the type and
// if there is dataflow
if (cpgCheckType(parameter.type, i)) parameter.param cpgFlowsTo arguments[i] else INVALID
// checks if the type of the argument is the same
is Type -> Result.convert(cpgCheckType(parameter, i))
// check if any of the Nodes of the Op flow to the argument
is Op -> parameter.cpgGetNodes() cpgFlowsTo arguments[i]
// check if any of the Nodes of the DataItem flow to the argument
is DataItem<*> -> parameter.cpgGetNodes() cpgFlowsTo arguments[i]
// checks if there is dataflow from the parameter to the argument in the same position
else -> parameter cpgFlowsTo arguments[i]
}
}
}
return INVALID
}
/** Checks the [type] against the type of the argument at [index] for the Call Expression */
private fun CallExpression.cpgCheckType(type: Type, index: Int) = arguments[index].type.typeName.endsWith(type.fqn)
/** Checks if the number of parameters matches the number of arguments of [CallExpression] */
private fun CallExpression.cpgCheckArgsSize(parameters: Array<*>, hasVarargs: Boolean) =
if (hasVarargs) {
parameters.size <= arguments.size
} else {
parameters.size == arguments.size
}
/**
* To generate more interesting Findings
* we want to find key points where the forbidden operation influences other code.
* For this we traverse the DFG for a fixed amount of steps and search for all usages of declared values.
*/
fun Node.findUsages(depth: Int = 5): Collection<Node> {
val currentNodes: MutableSet<Node> = mutableSetOf(this)
val usages = mutableSetOf<Node>()
for (i in 0..depth) {
// The set will be empty if we found a usage or no further DFG for all branches
if (currentNodes.isEmpty()) {
break
}
for (current in currentNodes) {
currentNodes.remove(current)
when (current) {
is ValueDeclaration -> usages += current.usages
else -> currentNodes += current.nextDFG
}
}
}
return usages
}
| 30
|
Kotlin
|
18
| 86
|
2485254a467b6815a66268f1983a00fb59194390
| 13,237
|
codyze
|
Apache License 2.0
|
app/src/main/java/com/aman/calculator/MainActivity.kt
|
officially-aman
| 832,038,884
| false
|
{"Kotlin": 14193}
|
package com.aman.calculator
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aman.calculator.ui.theme.CalculatorTheme
import net.objecthunter.exp4j.ExpressionBuilder
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CalculatorTheme {
CalculatorApp()
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CalculatorApp() {
var input by remember { mutableStateOf("") }
var result by remember { mutableStateOf("") }
var memory by remember { mutableStateOf(0.0) }
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopAppBar(
title = { Text(text = "Calculator") },
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primary,
titleContentColor = Color.White
)
)
}
) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
.padding(16.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.SpaceBetween
) {
Column(
modifier = Modifier
.weight(1f)
.fillMaxWidth(),
verticalArrangement = Arrangement.Bottom
) {
Text(
text = input,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
fontSize = 32.sp,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground,
textAlign = TextAlign.End
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = result,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
fontSize = 24.sp,
fontWeight = FontWeight.Normal,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),
textAlign = TextAlign.End
)
}
Divider(
color = MaterialTheme.colorScheme.onBackground,
thickness = 2.dp
)
Column(
modifier = Modifier
.weight(3f)
.fillMaxWidth()
) {
val mainButtons = listOf(
listOf("7", "8", "9", "/"),
listOf("4", "5", "6", "*"),
listOf("1", "2", "3", "-"),
listOf("0", ".", "=", "+")
)
val sciButtons = listOf(
listOf("sin", "cos", "tan", "√", "%")
)
val memButtons = listOf(
listOf("MR", "MC", "M+", "M-")
)
val topButtons = listOf(
listOf("AC", "C", "(", ")")
)
// Top Buttons
topButtons.forEach { row ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceEvenly
) {
row.forEach { button ->
CalculatorButton(button) {
when (button) {
"AC" -> {
input = ""
result = ""
}
"C" -> {
if (input.isNotEmpty()) {
input = input.dropLast(1)
}
}
else -> {
input += button
}
}
}
}
}
}
// Memory Buttons
memButtons.forEach { row ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceEvenly
) {
row.forEach { button ->
CalculatorButton(button) {
when (button) {
"MR" -> input += memory.toString()
"MC" -> memory = 0.0
"M+" -> {
try {
val expr = ExpressionBuilder(input).build()
memory += expr.evaluate()
input = ""
} catch (e: Exception) {
result = "Error"
}
}
"M-" -> {
try {
val expr = ExpressionBuilder(input).build()
memory -= expr.evaluate()
input = ""
} catch (e: Exception) {
result = "Error"
}
}
}
}
}
}
}
// Scientific Buttons
sciButtons.forEach { row ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceEvenly
) {
row.forEach { button ->
CalculatorButton(button) {
when (button) {
"sin", "cos", "tan", "√", "%" -> input += button + "("
}
}
}
}
}
// Main Buttons
mainButtons.forEach { row ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceEvenly
) {
row.forEach { button ->
CalculatorButton(button) {
when (button) {
"=" -> {
try {
val expr = ExpressionBuilder(input).build()
val evalResult = expr.evaluate()
result = evalResult.toString()
} catch (e: Exception) {
result = "Error"
}
}
else -> {
input += button
}
}
}
}
}
}
}
}
}
}
@Composable
fun CalculatorButton(symbol: String, onClick: () -> Unit) {
val backgroundColor = MaterialTheme.colorScheme.secondaryContainer
Box(
modifier = Modifier
.size(80.dp)
.background(backgroundColor, CircleShape)
.clickable(onClick = onClick),
contentAlignment = Alignment.Center
) {
when (symbol) {
"AC" -> {
Icon(
painter = painterResource(id = R.drawable.ic_clear_all),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer
)
}
"C" -> {
Icon(
painter = painterResource(id = R.drawable.ic_backspace),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer
)
}
else -> {
Text(text = symbol, fontSize = 24.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSecondaryContainer)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun CalculatorAppPreview() {
CalculatorTheme {
CalculatorApp()
}
}
| 0
|
Kotlin
|
0
| 0
|
bdaac99e01bc952177656574245198720885e208
| 10,213
|
Calculator
|
MIT License
|
app/src/main/java/com/nikola/jakshic/dagger/profile/peers/PeerFragment.kt
|
nikolajakshic
| 113,763,638
| false
| null |
package com.nikola.jakshic.dagger.profile.peers
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.nikola.jakshic.dagger.R
import com.nikola.jakshic.dagger.common.Status
import com.nikola.jakshic.dagger.common.hasNetworkConnection
import com.nikola.jakshic.dagger.common.toast
import com.nikola.jakshic.dagger.databinding.FragmentPeerBinding
import com.nikola.jakshic.dagger.profile.ProfileFragmentArgs
import com.nikola.jakshic.dagger.profile.ProfileFragmentDirections
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class PeerFragment : Fragment(R.layout.fragment_peer), PeerSortDialog.OnSortListener {
private val viewModel by viewModels<PeerViewModel>()
private var adapter: PeerAdapter? = null
private var id: Long = -1
private var _binding: FragmentPeerBinding? = null
private val binding get() = _binding!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentPeerBinding.bind(view)
id = ProfileFragmentArgs.fromBundle(requireParentFragment().requireArguments()).accountId
viewModel.initialFetch(id)
adapter = PeerAdapter {
findNavController().navigate(ProfileFragmentDirections.profileAction(accountId = it))
}
binding.recView.layoutManager = LinearLayoutManager(context)
binding.recView.addItemDecoration(
DividerItemDecoration(
context,
DividerItemDecoration.VERTICAL
)
)
binding.recView.adapter = adapter
binding.recView.setHasFixedSize(true)
viewModel.list.observe(viewLifecycleOwner, Observer(adapter!!::addData))
viewModel.status.observe(viewLifecycleOwner) {
when (it) {
Status.LOADING -> binding.swipeRefresh.isRefreshing = true
else -> binding.swipeRefresh.isRefreshing = false
}
}
val sortDialog = PeerSortDialog()
sortDialog.setTargetFragment(this, 300)
binding.btnSort.setOnClickListener {
if (!sortDialog.isAdded) sortDialog.show(parentFragmentManager, null)
}
binding.swipeRefresh.setOnRefreshListener {
if (hasNetworkConnection())
viewModel.fetchPeers(id)
else {
toast(getString(R.string.error_network_connection))
binding.swipeRefresh.isRefreshing = false
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
adapter = null
}
override fun onSort(sort: Int) {
val adapter = adapter ?: return // make it non-null
// Remove previous observers b/c we are attaching new LiveData
viewModel.list.removeObservers(viewLifecycleOwner)
when (sort) {
0 -> viewModel.sortByGames(id)
else -> viewModel.sortByWinRate(id)
}
// Set to null first, to delete all the items otherwise the list wont be scrolled to the first item
adapter.addData(null)
// Attach the observer to the new LiveData
viewModel.list.observe(viewLifecycleOwner, Observer(adapter::addData))
}
}
| 3
|
Kotlin
|
2
| 9
|
b7e3c87cf68bdcc537cf0c56834eb72178c6be99
| 3,542
|
dagger
|
MIT License
|
app/src/main/java/cc/sovellus/vrcaa/api/vrchat/models/Notifications.kt
|
Nyabsi
| 745,635,224
| false
|
{"Kotlin": 581921}
|
package cc.sovellus.vrcaa.api.vrchat.models
class Notifications : ArrayList<Notification>()
| 0
|
Kotlin
|
3
| 38
|
b45497cd686df2583ceb7b9cdefdd7ac2ee39b14
| 92
|
VRCAA
|
Apache License 2.0
|
privacypolicygenerator/src/main/java/com/livin/privacypolicygenerator/WebViewFragment.kt
|
Livinlawrence
| 332,658,293
| false
| null |
package com.livin.privacypolicygenerator
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import com.livin.privacypolicygenerator.Utils.shareFile
import kotlinx.android.synthetic.main.fragment_web_view.*
import kotlinx.coroutines.*
import java.io.File
private const val HTML_STRING = "html_string"
class WebViewFragment : Fragment() {
private var htmlString: String? = null
val job = Job()
val uiScope = CoroutineScope(Dispatchers.Main + job)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
htmlString = it.getString(HTML_STRING)
}
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_web_view, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
htmlString?.let {
webView.loadDataWithBaseURL("", it, "text/html", "UTF-8", "")
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.webview_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_share) {
uiScope.launch(Dispatchers.Main) {
val file = saveTextFile()
shareFile(file, requireContext())
}
}
return super.onOptionsItemSelected(item)
}
private suspend fun saveTextFile(): File {
return withContext(Dispatchers.IO) {
val file =
File(requireContext().filesDir, System.currentTimeMillis().toString() + ".html")
try {
file.printWriter().use { out ->
out.println(htmlString)
}
} catch (e: Exception) {
e.printStackTrace()
}
file
}
}
companion object {
const val TAG = "WebViewFragment"
@JvmStatic
fun newInstance(param1: String) =
WebViewFragment().apply {
arguments = Bundle().apply {
putString(HTML_STRING, param1)
}
}
}
}
| 0
|
Kotlin
|
1
| 3
|
5b4d5a6f263626740dd4895c1db6a6ef38159e61
| 2,516
|
Privacy-Policy-Generator-Android-Library
|
MIT License
|
app/src/test/java/hr/hofman/composednews/TestInject.kt
|
tomislavhofman
| 244,845,184
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 64, "JSON": 1, "XML": 24, "Java": 1}
|
package hr.hofman.composednews
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import dagger.Component
import dagger.Module
import dagger.Provides
import hr.hofman.composednews.data.remote.NewsApiService
import hr.hofman.composednews.data.remote.NewsApiServiceTest
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockWebServer
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Singleton
@Singleton
@Component(modules = [TestDataSourceModule::class])
interface TestComponent {
fun inject(test: NewsApiServiceTest)
}
@Module
object TestDataSourceModule {
@JvmStatic
@Singleton
@Provides
fun provideMockWebServer(): MockWebServer = MockWebServer()
@Singleton
@Provides
fun provideMoshi(): Moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
@JvmStatic
@Singleton
@Provides
fun provideOkHttpClient(): OkHttpClient =
OkHttpClient.Builder().build()
@JvmStatic
@Singleton
@Provides
fun provideMoshiConverterFactory(moshi: Moshi): Converter.Factory =
MoshiConverterFactory.create(moshi)
@JvmStatic
@Singleton
@Provides
fun provideNewsApiService(
okHttpClient: OkHttpClient,
converterFactory: Converter.Factory,
mockWebServer: MockWebServer
): NewsApiService = Retrofit.Builder()
.baseUrl(mockWebServer.url("/"))
.callFactory(okHttpClient)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(NewsApiService::class.java)
}
| 1
| null |
1
| 1
|
5f8004a708ef5e2f21df5196689ee30fb5dc6526
| 1,764
|
Composed-News
|
MIT License
|
androidApp/src/main/java/com/nkuppan/todo/ui/viewmodel/TaskCreateViewModel.kt
|
nkuppan
| 315,671,446
| false
|
{"Kotlin": 101459, "Swift": 4233, "Ruby": 2126}
|
package com.nkuppan.todo.ui.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.nkuppan.todo.R
import com.nkuppan.todo.ToDoApplication
import com.nkuppan.todo.db.SubTask
import com.nkuppan.todo.db.Task
import com.nkuppan.todo.db.TaskGroup
import com.nkuppan.todo.extention.Event
import com.nkuppan.todo.shared.utils.CommonUtils
import com.nkuppan.todo.utils.AppUIUtils
import com.nkuppan.todo.utils.SettingPrefManager
import kotlinx.coroutines.launch
import java.util.*
class TaskCreateViewModel(private val aApplication: Application) : AndroidViewModel(aApplication) {
var title: MutableLiveData<String> = MutableLiveData()
var description: MutableLiveData<String> = MutableLiveData()
var showDescription: MutableLiveData<Boolean> = MutableLiveData()
private val _changeTaskGroup: MutableLiveData<Event<Unit>> = MutableLiveData()
val changeTaskGroup: LiveData<Event<Unit>> = _changeTaskGroup
private val _success: MutableLiveData<Event<Unit>> = MutableLiveData()
val success: LiveData<Event<Unit>> = _success
private val _silentSuccess: MutableLiveData<Event<Unit>> = MutableLiveData()
val silentSuccess: LiveData<Event<Unit>> = _silentSuccess
private val _deleted: MutableLiveData<Event<Unit>> = MutableLiveData()
val deleted: LiveData<Event<Unit>> = _deleted
private val _updateMenu: MutableLiveData<Event<Unit>> = MutableLiveData()
val updateMenu: LiveData<Event<Unit>> = _updateMenu
private val _selectDateTime: MutableLiveData<Event<Unit>> = MutableLiveData()
val selectDateTime: LiveData<Event<Unit>> = _selectDateTime
private val _snackBarText: MutableLiveData<Event<String>> = MutableLiveData()
val snackBarMessage: LiveData<Event<String>> = _snackBarText
private val _taskGroupName: MutableLiveData<Event<String>> = MutableLiveData()
val taskGroupName: LiveData<Event<String>> = _taskGroupName
private var allTaskGroupList: MutableList<TaskGroup>? = null
var subTaskList: MutableLiveData<List<SubTask>?> = MutableLiveData()
val taskEndDateString: MutableLiveData<String> = MutableLiveData()
val taskCompleted: MutableLiveData<Boolean> = MutableLiveData()
var taskEndDate: Long? = null
var taskGroupId: String? = null
private var taskValue: Task? = null
init {
taskCompleted.value = false
taskEndDateString.value = aApplication.getString(R.string.add_date_time)
}
fun loadTaskDetails(aTaskId: String?) {
if (aTaskId.isNullOrEmpty()) {
return
}
viewModelScope.launch {
val task = (aApplication as ToDoApplication).repository.findThisTask(
aTaskId
)
if (task != null) {
taskValue = task
title.value = task.title
description.value = task.description
taskEndDate = task.task_end_date?.toLong()
taskGroupId = task.group_id
_updateMenu.value = Event(Unit)
updateTaskEndDate()
taskCompleted.value = task.status == 2L
if (taskCompleted.value == false) {
val subTaskList = aApplication.repository.getSubTaskList(
aTaskId
)
this@TaskCreateViewModel.subTaskList.value = subTaskList
}
}
}
}
private fun updateTaskEndDate() {
if (taskEndDate != null && taskEndDate!! > 0) {
taskEndDateString.value = AppUIUtils.getTaskEndDate(taskEndDate?.toDouble())
}
}
fun loadTaskGroupList() {
viewModelScope.launch {
val taskGroupList = (aApplication as ToDoApplication).repository.findAllGroups()
if (taskGroupList.isNotEmpty()) {
allTaskGroupList = taskGroupList.toMutableList()
var groupName: String = aApplication.getString(R.string.my_list)
taskGroupList.forEach {
if (it.id == SettingPrefManager.getSelectedTaskGroup()) {
groupName = it.group_name
}
}
_taskGroupName.value = Event(groupName)
}
}
}
fun saveTaskDetails(saveSilently: Boolean = false) {
if (saveSilently && taskValue == null) {
return
}
val title = title.value
val description = description.value
if (title.isNullOrBlank()) {
return
}
viewModelScope.launch {
val newConstructedTask = Task(
if (taskValue != null) taskValue!!.id else CommonUtils.getRandomUUID(),
group_id = if (taskGroupId != null)
taskGroupId!!
else
SettingPrefManager.getSelectedTaskGroup(),
title = title,
description = description,
task_end_date = taskEndDate?.toDouble(),
status = if (taskValue != null) taskValue!!.status else 1,
created_on = if (taskValue != null)
taskValue!!.created_on
else
CommonUtils.getDateTime().toDouble(),
updated_on = CommonUtils.getDateTime().toDouble()
)
(aApplication as ToDoApplication).repository.insertTask(newConstructedTask)
if (!saveSilently) {
_success.value = Event(Unit)
_snackBarText.value = Event(aApplication.getString(R.string.successfully_added))
} else {
_silentSuccess.value = Event(Unit)
}
if (saveSilently) {
taskValue = newConstructedTask
}
}
}
fun selectDateTimeClick() {
_selectDateTime.value = Event(Unit)
}
fun addDescriptionClick() {
showDescription.value = true
}
fun updateDateTime(aDate: Long) {
taskEndDate = aDate
updateTaskEndDate()
saveTaskDetails(saveSilently = true)
}
fun markThisTaskAsCompleted() {
viewModelScope.launch {
taskValue?.let {
(aApplication as ToDoApplication).repository.markThisTaskAsCompleted(it)
_success.value = Event(Unit)
}
}
}
fun revertThisTask() {
viewModelScope.launch {
taskValue?.let {
(aApplication as ToDoApplication).repository.revertThisTask(it)
_success.value = Event(Unit)
}
}
}
fun isCompleted(): Boolean {
return if (taskValue != null) {
taskValue!!.status == 2L
} else {
false
}
}
fun deleteThisTask() {
viewModelScope.launch {
taskValue?.let {
(aApplication as ToDoApplication).repository.removeTask(it)
_success.value = Event(Unit)
}
}
}
fun changeTaskGroup() {
_changeTaskGroup.value = Event(Unit)
}
fun updateTaskGroup(aTaskGroup: TaskGroup) {
viewModelScope.launch {
taskValue?.let { aTask ->
(aApplication as ToDoApplication).repository.updateTaskGroup(aTask, aTaskGroup)
taskGroupId = aTaskGroup.id
_taskGroupName.value = Event(aTaskGroup.group_name)
_silentSuccess.value = Event(Unit)
saveTaskDetails(saveSilently = true)
}
}
}
fun getSelectedTaskGroupId(): String {
return taskValue!!.group_id
}
fun getTaskId(): String {
return taskValue!!.id
}
fun deleteSubTask(aSubTask: SubTask?) {
aSubTask ?: return
viewModelScope.launch {
(aApplication as ToDoApplication).repository.removeSubTask(aSubTask)
}
}
fun createSubTask(aSubTask: SubTask?) {
aSubTask ?: return
viewModelScope.launch {
(aApplication as ToDoApplication).repository.insertSubTask(aSubTask)
}
}
fun updateSubTask(aSubTask: SubTask?, aDescription: String?) {
aSubTask ?: return
viewModelScope.launch {
(aApplication as ToDoApplication).repository.updateSubTask(aSubTask, aDescription)
}
}
fun updateSubTaskStatus(aSubTask: SubTask?) {
aSubTask ?: return
viewModelScope.launch {
(aApplication as ToDoApplication).repository.updateSubTask(aSubTask, 2L)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
afec61eb4aae7d95ba324885a799ccc0289c2d45
| 8,718
|
todo-kmm
|
Apache License 2.0
|
app/src/main/java/com/josealfonsomora/lastfmmusic/repository/RepositoryModule.kt
|
josealfonsomora
| 274,365,689
| false
| null |
package com.josealfonsomora.lastfmmusic.repository
import org.koin.dsl.module
fun provideRepositoryModule() = module {
single { AlbumRepository(get()) }
}
| 0
|
Kotlin
|
0
| 0
|
60ff459a7e4168750dac8ab55a9337cece133349
| 161
|
last-fm-music
|
Apache License 2.0
|
src/Day02.kt
|
MisterTeatime
| 560,956,854
| false
| null |
fun main() {
/*
A, X = Rock
B, Y = Paper
C, Z = Scissors
*/
fun part1(input: List<String>): Int {
val duelPoints = mapOf(
"AX" to 3 + 1, //Rock, Rock, Draw
"AY" to 6 + 2, //Rock, Paper, Win
"AZ" to 0 + 3, //Rock, Scissors, Loss
"BX" to 0 + 1, //Paper, Rock, Loss
"BY" to 3 + 2, //Paper, Paper, Draw
"BZ" to 6 + 3, //Paper, Scissors, Win
"CX" to 6 + 1, //Scissors, Rock, Win
"CY" to 0 + 2, //Scissors, Paper, Loss
"CZ" to 3 + 3 //Scissors, Scissors, Draw
)
return input
.map { it.split(" ") }
.sumOf { (elf, me) -> duelPoints[elf + me]!! }
}
fun part2(input: List<String>): Int {
val duelPoints = mapOf(
"AX" to 0 + 3, //Rock, Loss, Scissors
"AY" to 3 + 1, //Rock, Draw, Rock
"AZ" to 6 + 2, //Rock, Win, Paper
"BX" to 0 + 1, //Paper, Loss, Rock
"BY" to 3 + 2, //Paper, Draw, Paper
"BZ" to 6 + 3, //Paper, Win, Scissors
"CX" to 0 + 2, //Scissors, Loss, Paper
"CY" to 3 + 3, //Scissors, Draw, Scissors
"CZ" to 6 + 1 //Scissors, Win, Rock
)
return input
.map { it.split(" ") }
.sumOf { (elf, outcome) -> duelPoints[elf + outcome]!! }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0
|
Kotlin
|
0
| 0
|
8ba0c36992921e1623d9b2ed3585c8eb8d88718e
| 1,672
|
AoC2022
|
Apache License 2.0
|
promptkt/src/test/kotlin/tri/ai/openai/OpenAiTest.kt
|
aplpolaris
| 663,584,917
| false
| null |
/*-
* #%L
* tri.promptfx:promptkt
* %%
* Copyright (C) 2023 - 2024 Johns Hopkins University Applied Physics Laboratory
* %%
* 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.
* #L%
*/
package tri.ai.openai
import com.aallam.openai.api.chat.*
import com.aallam.openai.api.embedding.EmbeddingRequest
import com.aallam.openai.api.embedding.EmbeddingResponse
import com.aallam.openai.api.model.ModelId
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import tri.ai.embedding.cosineSimilarity
import tri.ai.openai.OpenAiModels.EMBEDDING_ADA
class OpenAiTest {
val client = OpenAiClient.INSTANCE.client
@Test
fun testModelLibrary() {
println(OpenAiModels.MODEL_INDEX)
}
@Test
@Disabled("Requires apikey")
fun testModels() = runTest {
val res = client.models()
println(res)
println("-".repeat(50))
println("OpenAI API models not in local index: " +
(res.map { it.id.id }.toSet() - OpenAiModels.MODEL_INDEX.values.map { it.id }.toSet()))
println("-".repeat(50))
println("Local index models not in OpenAI API: " +
(OpenAiModels.MODEL_INDEX.values.map { it.id }.toSet() - res.map { it.id.id }.toSet()))
}
@Test
@Disabled("Requires apikey")
fun testChat() = runTest {
val res = client.chatCompletion(
ChatCompletionRequest(
ModelId("gpt-3.5-turbo"),
listOf(userMessage {
content = "Give me a haiku about Kotlin."
})
)
)
println(res.choices[0].message.content!!.trim())
}
@Test
@Disabled("Requires apikey")
fun testChatImage() = runTest {
val res = client.chatCompletion(
chatCompletionRequest {
model = ModelId("gpt-4-vision-preview")
maxTokens = 2000
messages {
user {
content {
text("Describe everything you see in this image. Provide a detailed list of contents.")
image(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAAFmCAYAAAA/G0V9AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABbASURBVHhe7d3Pax3X3cfxr9LuSretDPYDcrMr3XhliUJBkF03lpDB0uohy+xEIA9I9sKWIIGgnZcmKylgI/cPCGjztPdq5U23iQWPDVIhkIVpCKHtfb7fmTn3Ho3uj7kzZ2bOWO9Xmd6Zq6uRkpyP5pwz58xZGCgBrrkPslfgWiMIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgKp1Yg5zflDGwsJCttecIEGgwKMJdQakVBAo+IhByGDMFYRJHyUYaMKkgh8iEIWDkP/YrGMgpHxhn3U8r0JBmFTo/fcnfQYoY1pBd/shwzAzCOMK+6xXJ38MFDGpgM96Nf7+PKYGwf+S27fX/L5/7L8CVYwr8G7zj92+4+8XNTEI/tt+AR+35b/m+PtAUflC7bb8sb+5rzn+fhGFgzBp+89//nPlPfc9vvwx4MsXXL9w+9sHH3xw5T1/c/z9IsYGwX/L9sdtFgAXgqJhAIpwhdgv4La5ENjrtEA4/v4sU4Pgv9rmF/x8ENy+v7nvBYpyhdcv2Lb5hd/t+8fuc+57/dciZgbB31xh//e//53s//rXv04+BzTp3bt3SeH/xS9+cSUIbjPutYjCo0/zYbANaEMdZfFKENxJ/ZP7P8xe7RewDWiDK39+mXT7xn+/qKlXhHE/wG0EAW1xIXCbkz+eR6Gqkf9D/Q1ow7iyaFsVc81QC/mDgbLqKIdzNZadkL8AMK98+QtRFmcGIf9D3HGIHw6UMakMVimTl4Iw6UT5H1zlBwIhFC2TRcvqXG0EH2FAW+ooe6WDALxP5g4CVwLEImRZ5IoAKIIAKIIAKIIAKIIAqE4Hof9kNBFj/zR7Eyihu0E43ZcvPzxPutAGg57IwZFcZF8C5tXZIPS/eSXr8iy7IqyIbG/KYvY1YF6X5iz7NyjSv7Sj2Wi22Vzlf/3rX8PX3/72t9mnm2fVohXpyeDhsh3J/sKJrA52xI7+9re/yV//+tfkc85vfvMb+dOf/pQdhXH79u+yvWpev/4u27tebt++ne3N5x//+If88pe/TOYsu1c3mT8/kd/4+5N0OAjrcvbfx7J5<KEY>Kwuju8vrXfTm6b3ecsy+Nla6Uk/YuzfosMF0kQbBCnX8a9kvZ2p6yhtrpMzm+l/YqDfp3ZOsr7jSgvEiC4NZQc92oS7J5cChr09ZQu7tDrxKCiWR9BLsijFkLbeNQzqcuH+W+b7RIiJm0UMhn//M/2V41r79LF/ZgoZBqYlofwQr7kBb24aaFfaCFffDzzz8Pfvrpp8GPP/44ePfu3eCHH34YfP/994OLi4vsu0LpDfbSFTOybU/fKep8cLgx/fOff/65xTzMNmT7Ibbr57vvvsv25mdlz8qglUUrk1Y2rYxaWbUya2XXL8tFRFI1soaythEe90alQ6v8K1PGGNkYpNEYJataZbtACXF1nz5a0ctYsQF2iw+eyvpf3BilFc0S45FQXkRB0Hp+XxvItuK+dYfOXGnclqQd1S8Yj4Qq4roi3NyU44Gtt/xStjavLi0I1CWuICTSSTosIo4mRRIEN1MtO1S2QCAz1NCUloPA5H3EIcKqEdC8loPA5H3EgSsCoCIIQto+2D8d7dM+QNNaDsJo+PWrswvpP/GHYu/Kyv0pw7CBgFoOQjpGyJ5WcfzgTE4e6Vs24lTbB8lw7GnDsIGAomgj3FlaFDk9Sa4Ga/dWpwy7BurR8nyE/DwEm1fwVGQ7e89Goz4M02/0xRdfBJuPoP9isp0C49wLyc73f4GG0P7XRrYTr9evX0c1H6H9iTlvj2T91pbYCmp<KEY>86O1wV4/OxicDw439ga97KiKzz//PNsLg/OFZ2XPyqCVRSuTVjatjFpZtTJrZdcvy0V0tmq0uHRHdr/JFp99eyLHsqT/A8rpbmP57o42lVfSy+CtY1k/YLEQlNfp7tPlh2k7ZjBI2wZAWZ0OQh3++Mc/ZnthcL5uuDZPscD7g6dYADUhCM7pfvqX5Ek/Gbqxf5q9X9Jo+Ifb9iXr4yon6O/Xl309V9V/xpHQ52seQUjof8hlkd6bQ1nTo+WHPf2/KgW3LyeP9qQ36MnexqGc2+vjVcnug5cQ+vdblh2t9q5+k4X0ftXhKaHP1zyCUCu7t2FDP/T17ycVCm49hr1uByKfWAGu+Fc99Pkapb/4kLsTZ1vsd5aD6+9ZT8FwG921LsfufMvjXvpq59T9SgL/fqb3ODvfxuHgPHmn2h360OebpI47y/QaXUtWp1/Rl0E2Vquq0Oebjl6j4NJGnvsXd3mr2LiNnbZdPg5ZaEOfr2HXPAhpI89d/S5vOxUatxqxoL1GkwNbug7+YktuXDpXxeCHPl/DqBrVwgruiaxWDNOIDTN/JkvP3fn0/PfP5OPnS/Is6M/pBqpGdXL99NlWrbdjSZY2st0gzuTsRbbrvKgyEcmCFLKLM/T5mkcQEvof0vrps6vgYFC1n94K7q6seMGqVlXQKpx+8+h81jDdEXmyIq+OPi53NaBqdAlVo0z/yb7Iw3zVg6HdMaJqV<KEY>p<KEY>"
)
}
}
}
}
)
println(res.choices[0].message.content!!.trim())
}
@Test
@Disabled("Requires apikey")
fun testEmbedding() = runTest {
val res = client.embeddings(
EmbeddingRequest(
ModelId(EMBEDDING_ADA),
listOf(
"Give me a haiku about Kotlin.",
"Tell me a joke.",
"Input text to get embeddings for, encoded as a string or array of tokens. To get embeddings for multiple inputs in a single request, pass an array of strings or array of token arrays. Each input must not exceed 8192 tokens in length.",
"Playing bridge on a starship"
)
)
)
// ada size is 1536
println("Embedding size = ${res.embeddings[0].embedding.size}")
res.embeddings.forEach { println(it.embedding) }
val max = res.embeddings.size - 1
(0..max).forEach { i ->
(i+1..max).forEach { j ->
println("Similarity between $i and $j: ${res.similarity(i, j)}")
}
}
}
private fun EmbeddingResponse.similarity(i: Int, j: Int): String {
val resp1 = embeddings[i].embedding
val resp2 = embeddings[j].embedding
val sim = cosineSimilarity(resp1, resp2)
return "%.2f".format(sim)
}
}
| 41
| null |
1
| 9
|
5fe1926c11bd425b9db2053da5a921994668737e
| 6,874
|
promptfx
|
Apache License 2.0
|
native/swift/sir/gen/org/jetbrains/kotlin/sir/SirDeclaration.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
// This file was generated automatically. See native/swift/sir/tree-generator/Readme.md.
// DO NOT MODIFY IT MANUALLY.
package org.jetbrains.kotlin.sir
/**
* Generated from: [org.jetbrains.kotlin.sir.tree.generator.SwiftIrTree.declaration]
*/
sealed interface SirDeclaration : SirElement {
val origin: SirOrigin
val visibility: SirVisibility
val documentation: String?
var parent: SirDeclarationParent
}
| 184
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 634
|
kotlin
|
Apache License 2.0
|
projects/wotw-server/src/jsMain/kotlin/wotw/web/ui/bingo/BingoCardComponents.kt
|
toadettexmushina
| 323,713,503
| true
|
{"C": 48200095, "C++": 47718744, "C#": 1321323, "Kotlin": 174656, "Scala": 116016, "AutoHotkey": 76512, "CMake": 40937, "Objective-C": 9352, "Batchfile": 2888, "CSS": 1766, "JavaScript": 1623, "Shell": 622, "HTML": 262}
|
package wotw.web.ui.bingo
import io.ktor.client.request.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.css.*
import kotlinx.css.properties.border
import kotlinx.html.js.onClickFunction
import react.*
import react.dom.p
import styled.css
import styled.styledDiv
import styled.styledP
import wotw.io.messages.protobuf.*
import wotw.io.messages.protobuf.Position
import wotw.web.io.WebSocketComponent
import wotw.web.main.Application
import wotw.web.util.BACKEND_HOST
import wotw.web.util.BACKEND_PORT
import wotw.web.util.hbox
import wotw.web.util.vbox
external interface GameIdProps : RProps {
var gameId: Long
}
external interface PlayerIdProps : RProps {
var playerId: Long?
}
external interface BingoCardProps : GameIdProps {
var useLatest: Boolean?
var playerId: Long?
}
external interface BingoCardState : RState {
var board: BingoBoard
}
external interface BingoSquareProps : RProps {
var gridPosition: Position
var size: Pair<LinearDimension?, LinearDimension?>?
var boardSize: Int
var text: String
var completed: Boolean
var goals: List<BingoGoal>
var xEdge: Boolean
var yEdge: Boolean
}
external interface BingoSquareState : RState {
var marked: Boolean
}
external interface BingoGoalProps : RProps {
var text: String
var completed: Boolean
}
class BingoView : RComponent<GameIdProps, RState>() {
override fun RBuilder.render() {
vbox {
hbox {
css {
gap = Gap("10px")
}
child(BingoCardComponent::class) {
attrs.gameId = props.gameId
}
child(BingoPlayersComponent::class) {
attrs.gameId = props.gameId
}
}
}
}
}
val labelSize = 20.px
val gapSize = 5.px
class BingoCardComponent(props: BingoCardProps) : RComponent<BingoCardProps, BingoCardState>(props) {
override fun BingoCardState.init(props: BingoCardProps) {
board = BingoBoard(size = 5)
}
override fun componentDidMount() {
GlobalScope.launch {
val path = when {
props.useLatest != true -> "bingo/${props.gameId}"
props.playerId == null -> "bingo/latest"
else -> "bingo/latest/${props.playerId}"
}
val boardData = Application.api.get<BingoData>(path = path)
setState {
this.board = boardData.board
}
Application.eventBus.send(SyncBingoPlayersMessage(boardData.players))
}
Application.eventBus.register(this, SyncBoardMessage::class) {
setState {
if (it.replace)
board = it.board
else board += it.board
}
}
}
override fun componentWillUnmount() {
Application.eventBus.unregisterAll(this)
}
override fun RBuilder.render() {
styledDiv {
css {
border(width = 2.px, style = BorderStyle.solid, color = Color.aqua)
marginRight = 3.em
position = kotlinx.css.Position.relative
width = LinearDimension("min(80%, 95vh)")
before {
content = QuotedString("")
float = Float.left
paddingTop = 100.pct
}
}
vbox {
css {
gap = Gap(gapSize.toString())
float = Float.left
width = 100.pct
height = 100.pct
}
val size = state.board.size
val cardRange = 1..size
for (y: Int in 0..size + 1) {
hbox {
css {
gap = Gap(gapSize.toString())
width = 100.pct
height =
if (y !in cardRange) labelSize else LinearDimension("calc((100% - 2 * $labelSize - ${size + 1} * $gapSize) / $size)")
textAlign = TextAlign.center
}
for (x: Int in 0..size + 1) {
//why are grids not 0-based again? :<
val gridPos = Position(x + 1, y + 1)
val width = if (x !in cardRange) labelSize else null
val height = if (y !in cardRange) labelSize else null
val square = state.board[Position(x, y)]
val text = when {
square != null -> square.text
x == 0 && y == 0 || x > size && y > size -> "X"
x == 0 && y > size || x > size && y == 0 -> "Y"
x !in cardRange -> y.toString()
else -> (x + 64).toChar().toString()
}
val completed = when {
square != null -> square.completed
x == 0 && y == 0 || x > size && y > size -> cardRange.all {
state.board[Position(it, it)]?.completed == true
}
x == 0 && y > size || x > size && y == 0 -> cardRange.all {
state.board[Position(size + 1 - it, it)]?.completed == true
}
x !in cardRange -> cardRange.all {
state.board[Position(it, y)]?.completed == true
}
else -> cardRange.all {
state.board[Position(x, it)]?.completed == true
}
}
child(BingoSquareComponent::class) {
attrs.xEdge = x !in cardRange
attrs.yEdge = y !in cardRange
attrs.gridPosition = gridPos
attrs.size = width to height
attrs.boardSize = size
attrs.completed = completed
attrs.goals = square?.goals ?: emptyList()
attrs.text = text
}
}
}
}
}
child(WebSocketComponent::class) {
if (props.useLatest == true) {
attrs.url = "wss://$BACKEND_HOST:$BACKEND_PORT/api/bingosync/latest"
if (props.playerId != null)
attrs.url += "/${props.playerId}"
} else {
attrs.url = "wss://$BACKEND_HOST:$BACKEND_PORT/api/bingosync/${props.gameId}"
}
}
}
}
}
class BingoSquareComponent : RComponent<BingoSquareProps, BingoSquareState>() {
override fun BingoSquareState.init() {
marked = false
}
override fun RBuilder.render() {
styledDiv {
css {
width = props.size?.first
?: LinearDimension("calc((100% - 2 * $labelSize - ${props.boardSize + 1} * $gapSize) / ${props.boardSize})")
height = 100.pct
textAlign = TextAlign.center
fontWeight = FontWeight.bold
backgroundColor =
if (props.completed) Color.green else if (state.marked) Color.lightBlue else Color.lightGray
}
when {
props.xEdge && !props.yEdge -> styledP {
css {
fontWeight = FontWeight.normal
marginTop = 0.em
paddingTop = 4.em // TODO: actually center
}
+props.text
}
props.xEdge || props.yEdge -> styledP {
css {
fontWeight = FontWeight.normal
marginTop = 0.em
paddingTop = 0.em
}
+props.text
}
else -> p {
+props.text
}
}
attrs {
onClickFunction = {
it.preventDefault()
setState {
marked = !marked
}
}
}
for (it in props.goals) {
child(BingoGoalComponent::class) {
attrs.text = it.text
attrs.completed = it.completed
}
}
}
}
}
class BingoGoalComponent(props: BingoGoalProps) : RComponent<BingoGoalProps, RState>(props) {
override fun RBuilder.render() {
styledP {
css {
fontWeight = FontWeight.normal
}
+props.text
if (props.completed) {
css {
backgroundColor = Color.greenYellow
}
}
}
}
}
| 0
| null |
0
| 0
|
bc61f913fa87ad7e38b87d2f109eb47bf98fa24c
| 9,421
|
OriWotwRandomizerClient
|
MIT License
|
shared/src/commonMain/kotlin/AbstractRowBuilder.kt
|
fcopardo
| 643,314,635
| false
| null |
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.ui.Alignment
abstract class AbstractRowBuilder<T>(id : String) : composable<T>(id) where T : composable<T> {
protected var horizontalArrangement: Arrangement.Horizontal = Arrangement.Start
protected var verticalAlignment: Alignment.Vertical = Alignment.Top
fun horizontalArrangement(horizontalArrangement: Arrangement.Horizontal) : T {
this.horizontalArrangement = horizontalArrangement
return this as T
}
fun verticalAlignment(verticalAlignment: Alignment.Vertical): T {
this.verticalAlignment = verticalAlignment
return this as T
}
}
| 0
|
Kotlin
|
0
| 0
|
163b5d8d3988b17ec2e2df75131b90c5e68abb2d
| 674
|
kmm-compose-playground
|
Apache License 2.0
|
src/test/kotlin/org/incava/mmonkeys/trials/rand/StrGenList.kt
|
jpace
| 483,382,354
| false
|
{"Kotlin": 263784, "Ruby": 674}
|
package org.incava.mmonkeys.trials.rand
import org.incava.mmonkeys.trials.rand.StrRand.Constants.NUM_CHARS
import org.incava.rando.RandSlottedGenList
import kotlin.random.Random
class StrGenList : StrLenRand() {
private val lengthRand = RandSlottedGenList(NUM_CHARS + 1, 100, 10000)
override fun randomLength() = lengthRand.nextInt()
override fun randInt(limit: Int) = Random.nextInt(limit)
override fun getString(length: Int) = StringFactory.buildString(length, ::randCharAz)
}
| 0
|
Kotlin
|
0
| 0
|
b359710848fa9e5126eadd20bb66e1f1d900ac24
| 498
|
mmonkeys
|
MIT License
|
vector/src/test/java/im/vector/app/features/onboarding/RegistrationWizardActionDelegateTest.kt
|
tchapgouv
| 340,329,238
| false
| null |
/*
* Copyright (c) 2022 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.app.features.onboarding
import im.vector.app.test.fakes.FakeAuthenticationService
import im.vector.app.test.fakes.FakeRegistrationWizard
import im.vector.app.test.fakes.FakeSession
import im.vector.app.test.fixtures.a401ServerError
import io.mockk.coVerifyAll
import kotlinx.coroutines.test.runTest
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Test
import org.matrix.android.sdk.api.auth.registration.RegisterThreePid
import org.matrix.android.sdk.api.auth.registration.RegistrationWizard
import org.matrix.android.sdk.api.auth.registration.RegistrationResult as MatrixRegistrationResult
private const val IGNORED_DELAY = 0L
private val AN_ERROR = RuntimeException()
private val A_SESSION = FakeSession()
private val AN_EXPECTED_RESULT = RegistrationResult.Complete(A_SESSION)
private const val A_USERNAME = "a username"
private const val A_PASSWORD = "<PASSWORD>"
private const val AN_INITIAL_DEVICE_NAME = "a device name"
private const val A_CAPTCHA_RESPONSE = "a captcha response"
private const val A_PID_CODE = "a pid code"
private const val EMAIL_VALIDATED_DELAY = 10000L
private val AN_EMAIL_PID_TO_REGISTER = RegisterThreePid.Email("an email")
private val A_PHONE_PID_TO_REGISTER = RegisterThreePid.Msisdn("+11111111111", countryCode = "GB")
class RegistrationWizardActionDelegateTest {
private val fakeRegistrationWizard = FakeRegistrationWizard()
private val fakeAuthenticationService = FakeAuthenticationService().also {
it.givenRegistrationWizard(fakeRegistrationWizard)
}
private val registrationActionHandler = RegistrationWizardActionDelegate(fakeAuthenticationService)
@Test
fun `when handling register action then delegates to wizard`() = runTest {
val cases = listOf(
case(RegisterAction.StartRegistration) { getRegistrationFlow() },
case(RegisterAction.CaptchaDone(A_CAPTCHA_RESPONSE)) { performReCaptcha(A_CAPTCHA_RESPONSE) },
case(RegisterAction.AcceptTerms) { acceptTerms() },
case(RegisterAction.RegisterDummy) { dummy() },
case(RegisterAction.AddThreePid(AN_EMAIL_PID_TO_REGISTER)) { addThreePid(AN_EMAIL_PID_TO_REGISTER) },
case(RegisterAction.SendAgainThreePid) { sendAgainThreePid() },
case(RegisterAction.ValidateThreePid(A_PID_CODE)) { handleValidateThreePid(A_PID_CODE) },
case(RegisterAction.CheckIfEmailHasBeenValidated(EMAIL_VALIDATED_DELAY)) { checkIfEmailHasBeenValidated(EMAIL_VALIDATED_DELAY) },
case(RegisterAction.CreateAccount(A_USERNAME, A_PASSWORD, AN_INITIAL_DEVICE_NAME)) {
createAccount(A_USERNAME, A_PASSWORD, AN_INITIAL_DEVICE_NAME)
}
)
cases.forEach { testSuccessfulActionDelegation(it) }
}
@Test
fun `given adding an email ThreePid fails with 401, when handling register action, then infer EmailSuccess`() = runTest {
fakeRegistrationWizard.givenAddThreePidErrors(
cause = a401ServerError(),
threePid = AN_EMAIL_PID_TO_REGISTER
)
val result = registrationActionHandler.executeAction(RegisterAction.AddThreePid(AN_EMAIL_PID_TO_REGISTER))
result shouldBeEqualTo RegistrationResult.SendEmailSuccess(AN_EMAIL_PID_TO_REGISTER)
}
@Test
fun `given email verification errors with 401 then fatal error, when checking email validation, then continues to poll until non 401 error`() = runTest {
val errorsToThrow = listOf(
a401ServerError(),
a401ServerError(),
a401ServerError(),
AN_ERROR
)
fakeRegistrationWizard.givenCheckIfEmailHasBeenValidatedErrors(errorsToThrow)
val result = registrationActionHandler.executeAction(RegisterAction.CheckIfEmailHasBeenValidated(IGNORED_DELAY))
fakeRegistrationWizard.verifyCheckedEmailedVerification(times = errorsToThrow.size)
result shouldBeEqualTo RegistrationResult.Error(AN_ERROR)
}
@Test
fun `given email verification errors with 401 and succeeds, when checking email validation, then continues to poll until success`() = runTest {
val errorsToThrow = listOf(
a401ServerError(),
a401ServerError(),
a401ServerError()
)
fakeRegistrationWizard.givenCheckIfEmailHasBeenValidatedErrors(errorsToThrow, finally = MatrixRegistrationResult.Success(A_SESSION))
val result = registrationActionHandler.executeAction(RegisterAction.CheckIfEmailHasBeenValidated(IGNORED_DELAY))
fakeRegistrationWizard.verifyCheckedEmailedVerification(times = errorsToThrow.size + 1)
result shouldBeEqualTo RegistrationResult.Complete(A_SESSION)
}
@Test
fun `given adding an Msisdn ThreePid fails with 401, when handling register action, then infer EmailSuccess`() = runTest {
fakeRegistrationWizard.givenAddThreePidErrors(
cause = a401ServerError(),
threePid = A_PHONE_PID_TO_REGISTER
)
val result = registrationActionHandler.executeAction(RegisterAction.AddThreePid(A_PHONE_PID_TO_REGISTER))
result shouldBeEqualTo RegistrationResult.SendMsisdnSuccess(A_PHONE_PID_TO_REGISTER)
}
private suspend fun testSuccessfulActionDelegation(case: Case) {
val fakeRegistrationWizard = FakeRegistrationWizard()
val authenticationService = FakeAuthenticationService().also { it.givenRegistrationWizard(fakeRegistrationWizard) }
val registrationActionHandler = RegistrationWizardActionDelegate(authenticationService)
fakeRegistrationWizard.givenSuccessFor(result = A_SESSION, case.expect)
val result = registrationActionHandler.executeAction(case.action)
coVerifyAll { case.expect(fakeRegistrationWizard) }
result shouldBeEqualTo AN_EXPECTED_RESULT
}
}
private fun case(action: RegisterAction, expect: suspend RegistrationWizard.() -> MatrixRegistrationResult) = Case(action, expect)
private class Case(val action: RegisterAction, val expect: suspend RegistrationWizard.() -> MatrixRegistrationResult)
| 4
|
Kotlin
|
6
| 9
|
02c555858daab03fd2bdac159efd55961f3b6ebe
| 6,784
|
tchap-android
|
Apache License 2.0
|
src/main/kotlin/dev/paulshields/aoc/day14/Bitmask.kt
|
Pkshields
| 318,658,287
| false
| null |
package dev.paulshields.aoc.day14
data class Bitmask(val onesMask: Long, val zerosMask: Long) {
companion object {
val zero = Bitmask(0, 0)
fun fromString(input: String) =
Bitmask(createMaskFromString(input, 0), createMaskFromString(input, 1))
private fun createMaskFromString(maskString: String, paddingDefault: Long) = maskString
.replace("X", paddingDefault.toString())
.toLong(2)
}
fun mask(input: Long) = (input or onesMask) and zerosMask
}
| 0
|
Kotlin
|
0
| 0
|
a7bd42ee17fed44766cfdeb04d41459becd95803
| 521
|
AdventOfCode2020
|
MIT License
|
sdk/analytics/src/test/java/com/klaviyo/analytics/networking/requests/BaseRequestTest.kt
|
klaviyo
| 282,284,680
| false
| null |
package com.klaviyo.analytics.networking.requests
import com.klaviyo.analytics.DeviceProperties
import com.klaviyo.fixtures.BaseTest
import io.mockk.every
import io.mockk.mockkObject
import org.junit.Before
internal open class BaseRequestTest : BaseTest() {
@Before
override fun setup() {
super.setup()
mockkObject(DeviceProperties)
every { DeviceProperties.userAgent } returns "Mock User Agent"
every { DeviceProperties.model } returns "Mock Model"
every { DeviceProperties.applicationLabel } returns "Mock Application Label"
every { DeviceProperties.appVersion } returns "Mock App Version"
every { DeviceProperties.appVersionCode } returns "Mock Version Code"
every { DeviceProperties.sdkName } returns "Mock SDK"
every { DeviceProperties.sdkVersion } returns "Mock SDK Version"
every { DeviceProperties.backgroundData } returns true
every { DeviceProperties.notificationPermission } returns true
every { DeviceProperties.applicationId } returns "Mock App ID"
every { DeviceProperties.platform } returns "Android"
every { DeviceProperties.deviceId } returns "Mock Device ID"
every { DeviceProperties.manufacturer } returns "Mock Manufacturer"
every { DeviceProperties.osVersion } returns "Mock OS Version"
}
}
| 0
|
Kotlin
|
2
| 6
|
a8b4f5751f5f204c0f5a9548148f4b6a138f5ce7
| 1,355
|
klaviyo-android-sdk
|
MIT License
|
core/platform-services/interactor/src/androidMain/kotlin/org/michaelbel/movies/platform/analytics/AnalyticsService.kt
|
michaelbel
| 115,437,864
| false
|
{"Kotlin": 908384, "Swift": 692, "HTML": 606, "Shell": 235}
|
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package org.michaelbel.movies.platform.analytics
import android.os.Bundle
actual interface AnalyticsService {
val screenView: String
val screenName: String
fun logEvent(name: String, params: Bundle)
}
| 8
|
Kotlin
|
36
| 271
|
1da1d67e093ecb76057a06da0ef17f746ca06888
| 282
|
movies
|
Apache License 2.0
|
app/src/main/java/galaxy/qiitaviewer/type/FragmentType.kt
|
galaxyginx
| 126,269,424
| false
| null |
package galaxy.qiitaviewer.type
import galaxy.qiitaviewer.R
enum class FragmentType(val navigation: NavigationType, var title: String, val menu: Int) {
HOME(NavigationType.USER, "Home", R.menu.home_menu),
ARTICLE(NavigationType.USER, "Article", R.menu.home_menu),
STOCKS(NavigationType.NONE, "Stocks", R.menu.empty),
LECTURES(NavigationType.NONE, "Lectures", R.menu.empty),
SEARCH(NavigationType.BACK, "Search", R.menu.search_menu),
BROWSER(NavigationType.BACK, "BROWSER", R.menu.webview_menu),
USERINFO(NavigationType.BACK, "User", R.menu.empty)
}
| 0
|
Kotlin
|
0
| 0
|
e27389f63e267d04bd0ab76a62d2d6a83c917ccb
| 578
|
QiitaViewer-Android
|
Apache License 2.0
|
src/test/kotlin/io/openfuture/api/component/web3/TransactionHandlerTests.kt
|
ag68
| 189,033,602
| true
|
{"Kotlin": 209202, "JavaScript": 168887, "CSS": 46474, "FreeMarker": 23569, "HTML": 2076, "Dockerfile": 167}
|
package io.openfuture.api.component.web3
import io.openfuture.api.component.web3.event.ProcessorEventDecoder
import io.openfuture.api.config.UnitTest
import io.openfuture.api.config.any
import io.openfuture.api.entity.auth.OpenKey
import io.openfuture.api.entity.auth.User
import io.openfuture.api.entity.scaffold.Scaffold
import io.openfuture.api.entity.scaffold.ScaffoldVersion.V1
import io.openfuture.api.entity.scaffold.Transaction
import io.openfuture.api.repository.ScaffoldRepository
import io.openfuture.api.service.TransactionService
import org.junit.Before
import org.junit.Test
import org.mockito.BDDMockito.given
import org.mockito.BDDMockito.verify
import org.mockito.Mock
import org.mockito.Mockito.never
import org.springframework.context.ApplicationEventPublisher
import org.web3j.protocol.core.methods.response.Log
internal class TransactionHandlerTests : UnitTest() {
@Mock private lateinit var transactionService: TransactionService
@Mock private lateinit var scaffoldRepository: ScaffoldRepository
@Mock private lateinit var eventDecoder: ProcessorEventDecoder
@Mock private lateinit var publisher: ApplicationEventPublisher
@Mock private lateinit var log: Log
private lateinit var transactionHandler: TransactionHandler
@Before
fun setUp() {
transactionHandler = TransactionHandler(transactionService, scaffoldRepository, eventDecoder, publisher)
given(log.transactionHash).willReturn("hash")
given(log.address).willReturn("0xba37163625b3f2e96112562858c12b75963af138")
given(log.data).willReturn("data")
given(log.logIndexRaw).willReturn("index")
}
@Test
fun handleTest() {
val user = User("104113085667282103363")
val scaffold = Scaffold("0xba37163625b32e96112562858c12b75963af138", OpenKey(user), "abi", "developerAddress",
"description", "fiatAmount", 1, "conversionAmount", V1.getId(), "https://test.com", mutableListOf())
given(scaffoldRepository.findByAddressIgnoreCase(log.address)).willReturn(scaffold)
given(transactionService.save(any(Transaction::class.java))).will { invocation -> invocation.arguments[0] }
transactionHandler.handle(log)
}
@Test
fun handleWhenEmptyScaffoldShouldNotSaveTransactionTest() {
given(scaffoldRepository.findByAddressIgnoreCase(log.address)).willReturn(null)
transactionHandler.handle(log)
verify(transactionService, never()).save(any(Transaction::class.java))
}
}
| 0
|
Kotlin
|
0
| 0
|
08de820966c15f54ee19c47c435acb025016157b
| 2,517
|
open-api
|
Apache License 2.0
|
app/src/test/java/io/github/mklkj/filmowy/api/repository/FilmRepositoryTest.kt
|
mklkj
| 166,846,534
| false
|
{"HTML": 181836, "Kotlin": 179891}
|
package io.github.mklkj.filmowy.api.repository
import io.github.mklkj.filmowy.api.BaseApiTest
import io.github.mklkj.filmowy.api.pojo.FilmPerson
import okhttp3.JavaNetCookieJar
import okhttp3.mockwebserver.MockResponse
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import retrofit2.create
import java.net.CookieManager
class FilmRepositoryTest : BaseApiTest() {
private val filmRepository by lazy { FilmRepository(getRetrofit().create(), getRetrofitScrapper().create(), JavaNetCookieJar(CookieManager())) }
@Test
fun getFilmDescription() {
server.enqueue(MockResponse().setBody(getResource("film-description.txt")!!))
server.start()
val desc = filmRepository.getFilmDescription(1).blockingGet()
assertEquals("W systemie edukacji znajdującym się na krawędzi upadku, jeden człowiek został doprowadzony do ostateczności.", desc.description)
}
@Test
fun getFilmImages() {
server.enqueue(MockResponse().setBody(getResource("film-images.txt")!!))
server.start()
val images = filmRepository.getFilmImages(1, 5).blockingGet()
assertEquals(50, images.size)
images[0].run {
assertEquals(1, filmId)
assertEquals("/16/34/771634/708447.0.jpg", imagePath)
}
}
@Test
fun getFilmInfoFull_noVideos() {
server.enqueue(MockResponse().setBody(getResource("film-info-full_no-videos.txt")!!))
server.start()
val info = filmRepository.getFilmInfoFull(2).blockingGet()
info.run {
assertEquals("Paragraf 187", title)
assertEquals(7.32363, avgRate, .0)
assertEquals(7796, votesCount)
assertEquals(4136, wantSee)
assertEquals(1997, year)
assertEquals(120, duration)
assertEquals("/00/01/1/7003079.2.jpg", imagePath)
filmInfo?.run {
assertEquals("One Eight Seven", originalTitle)
assertEquals("Thriller", genres)
assertEquals("0", commentsCount)
assertEquals("https://www.filmweb.pl/film/Paragraf+187-1997-1/discussion", forumUrl)
assertEquals(true, hasReview)
assertEquals(true, hasDescription)
assertEquals(null, videoImageUrl)
assertEquals(null, videoUrl)
assertEquals(null, videoHDUrl)
assertEquals(null, video480pUrl)
assertEquals(null, ageRestriction)
assertEquals("1997-07-30", premiereWorld)
assertEquals("1998-02-27", premiereCountry)
assertEquals(0, filmType)
assertEquals(0, seasonsCount)
assertEquals(0, episodesCount)
assertEquals("USA", countriesString)
assertEquals("Napadnięty nauczyciel postanawia wrócić do pracy w innej szkole, aby walczyć z agresją i przemocą.", synopsis)
assertEquals(false, recommends)
assertEquals(LocalDate.of(1997, 7, 30), premiereWorldPublic)
assertEquals(LocalDate.of(1998, 2, 27), premiereCountryPublic)
}
}
}
@Test
fun getFilmPersons() {
server.enqueue(MockResponse().setBody(getResource("film-persons.txt")!!))
server.start()
val persons = filmRepository.getFilmPersons(2, FilmPerson.AssocType.ACTOR, 0).blockingGet()
persons.run {
assertEquals(1, size)
}
}
@Test
fun getFilmPersons_null() {
server.enqueue(MockResponse().setBody(getResource("exc-npe.txt")!!))
server.start()
val persons = filmRepository.getFilmPersons(2, FilmPerson.AssocType.ACTOR, 0).blockingGet()
assertEquals(0, persons.size)
}
@Test
fun getFilmPersonsLead() {
server.enqueue(MockResponse().setBody(getResource("film-persons-lead.txt")!!))
server.start()
val persons = filmRepository.getFilmPersonsLead(3, 50).blockingGet()
assertEquals(15, persons.size)
persons[0].run {
assertEquals(3, filmId)
assertEquals(606018, personId)
assertEquals(null, assocAttributes)
assertEquals(null, assocName)
assertEquals(FilmPerson.AssocType.DIRECTOR, assocType)
assertEquals("Reed Morano", personName)
assertEquals("/60/18/606018/291795.1.jpg", personImagePath)
}
}
@Test
fun getFilmProfessionCounts() {
server.enqueue(MockResponse().setBody(getResource("film-profession-counts.txt")!!))
server.start()
val professions = filmRepository.getFilmProfessionCounts(3).blockingGet()
assertEquals(8, professions.size)
professions[0].run {
assertEquals(3, filmId)
assertEquals(7, assocCount)
assertEquals(FilmPerson.AssocType.DIRECTOR, assocType)
}
}
@Test
fun getFilmReview() {
server.enqueue(MockResponse().setBody(getResource("film-review.txt")!!))
server.start()
val review = filmRepository.getFilmReview(3).blockingGet()
review.run {
assertEquals("SQNboy", authorName)
assertEquals(163588, authorUserId)
assertEquals("/35/88/163588/163588.0.jpg", authorImagePath)
assertTrue(content.startsWith("\"Paragraf 187\" to dowód na to, że"))
assertEquals(3533, content.length)
assertEquals("Szkolna rzeczywistość", title)
}
}
@Test
fun getFilmVideos() {
server.enqueue(MockResponse().setBody(getResource("film-videos.txt")!!))
server.start()
val videos = filmRepository.getFilmVideos(4, 0).blockingGet()
assertEquals(1, videos.size)
videos[0].run {
assertEquals(4, filmId)
assertEquals("https://1.fwcdn.pl/wv/34/10/13410/snap2.13410.1.jpg", imagePath)
assertEquals("https://mm.filmweb.pl/2/the_devil_s_advocate__1997____official_movie_trailer.iphone.mp4", videoPath)
}
}
@Test
fun getFilmVideos_empty() {
server.enqueue(MockResponse().setBody(getResource("empty.txt")!!))
server.start()
val videos = filmRepository.getFilmVideos(5, 0).blockingGet()
assertEquals(0, videos.size)
}
@Test
fun getFilmsInfoShort() {
server.enqueue(MockResponse().setBody(getResource("film-info-short.txt")!!))
server.start()
val infos = filmRepository.getFilmsInfoShort(1, 2).blockingGet()
assertEquals(1, infos.size)
infos[0].run {
assertEquals("Paragraf 187", title)
assertEquals(1997, year)
assertEquals(7.32566, avgRate, .0)
assertEquals(7689, votesCount)
assertEquals(120, duration)
assertEquals("/00/01/1/7003079.2.jpg", imagePath)
assertEquals(null, filmInfo)
}
}
@Test
fun getFilmsNearestBroadcasts() {
server.enqueue(MockResponse().setBody(getResource("film-nearest-broadcasts.txt")!!))
server.start()
val broadcasts = filmRepository.getFilmsNearestBroadcasts(1, 0).blockingGet()
assertEquals(3, broadcasts.size)
broadcasts[0].run {
assertEquals(9, filmId)
assertEquals(29, tvChannelId)
assertEquals(LocalDateTime.of(2019, 6, 29, 17, 55, 0), dateTime)
assertEquals(61600719, id)
assertEquals("film SF", description)
}
}
@Test
fun getFilmSeasonEpisodes() {
server.enqueue(MockResponse().setBody(getResource("film-season-episodes.html")!!))
server.start()
val episodes = filmRepository.getFilmSeasonEpisodes("Nazwa", 1).blockingGet()
assertEquals(2, episodes.size)
episodes[0].run {
assertEquals(1659645, id)
assertEquals(4, season)
assertEquals(1, number)
assertEquals(LocalDate.of(2014, 9, 23), premiereDate)
assertEquals("Panopticon", title)
assertEquals("8,1", avgRate)
}
episodes[1].run {
assertEquals(1703094, id)
assertEquals(4, season)
assertEquals(2, number)
assertEquals(LocalDate.of(2014, 9, 30), premiereDate)
assertEquals("Nautilus", title)
assertEquals("8,1", avgRate)
}
}
@Test
fun getFilmVote() {
server.enqueue(MockResponse().setBody(getResource("film-vote.json")!!))
server.start()
val vote = filmRepository.getFilmVote(1, 1).blockingGet()
assertEquals(0, vote.a)
}
}
| 1
|
HTML
|
0
| 7
|
e7f01ad5d0771254e907e59aa4df4ef0e6fd7293
| 8,756
|
filmowy
|
Apache License 2.0
|
app/src/main/java/top/easelink/lcg/ui/main/source/local/SPConstants.kt
|
cnandroidlib
| 229,791,673
| true
|
{"Kotlin": 176842, "Java": 158327, "HTML": 533}
|
package top.easelink.lcg.ui.main.source.local
const val SP_KEY_LOGGED_IN = "sp_key_logged_in"
const val SP_KEY_AUTO_SIGN_IN = "sp_key_auto_sign_in"
const val SP_KEY_SYNC_FAVORITE = "sp_key_sync_favorite"
const val SP_KEY_USER_NAME = "sp_key_user_name"
| 0
| null |
0
| 0
|
46c21834111c3eaca4e986f49390313320dfef84
| 253
|
lcg
|
MIT License
|
src/commonMain/kotlin/exception/InvalidWorldException.kt
|
drakon64
| 586,358,669
| false
| null |
package cloud.drakon.ktuniversalis.exception
/**
* The world requested is invalid.
*/
class InvalidWorldException(message: String = "The world requested is invalid"):
Throwable(message)
| 3
|
Kotlin
|
0
| 0
|
7b2b2297404f82c6cd80a7254b361a39561a3565
| 193
|
KtUniversalis
|
MIT License
|
libraries/navigation/src/nonAndroidMain/kotlin/com/hoc081098/compose_multiplatform_kmpviewmodel_sample/navigation/internal/MultiStackNavigationExecutor.kt
|
hoc081098
| 675,918,221
| false
|
{"Kotlin": 173732, "Swift": 580, "Shell": 228, "Ruby": 143}
|
/**
* Copied from [com.freeletics.khonshu.navigation.internal.MultiStackNavigationExecutor.kt](https://github.com/freeletics/khonshu/blob/1e7732b44e1abf04e2e7468c99300dc140132da1/navigation-experimental/src/main/kotlin/com/freeletics/khonshu/navigation/compose/internal/MultiStackNavigationExecutor.kt).
*/
package com.hoc081098.compose_multiplatform_kmpviewmodel_sample.navigation.internal
import androidx.compose.runtime.State
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.navigation.BaseRoute
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.navigation.NavRoot
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.navigation.NavRoute
import com.hoc081098.kmp.viewmodel.SavedStateHandle
import kotlin.jvm.JvmField
import kotlinx.collections.immutable.ImmutableList
@InternalNavigationApi
internal class MultiStackNavigationExecutor(
private val stack: MultiStack,
@JvmField internal val viewModel: StoreViewModel,
) : NavigationExecutor {
@Suppress("unused") // TODO
val visibleEntries: State<ImmutableList<StackEntry<*>>>
get() = stack.visibleEntries
@Suppress("unused") // TODO
val canNavigateBack: State<Boolean>
get() = stack.canNavigateBack
override fun navigate(route: NavRoute) {
stack.push(route)
}
override fun navigate(root: NavRoot, restoreRootState: Boolean) {
stack.push(root, clearTargetStack = !restoreRootState)
}
override fun navigateUp() {
stack.popCurrentStack()
}
override fun navigateBack() {
stack.pop()
}
override fun <T : BaseRoute> navigateBackTo(
destinationId: DestinationId<T>,
isInclusive: Boolean,
) {
stack.popUpTo(destinationId, isInclusive)
}
override fun resetToRoot(root: NavRoot) {
stack.resetToRoot(root)
}
override fun <T : BaseRoute> routeFor(destinationId: DestinationId<T>): T {
return entryFor(destinationId).route
}
override fun <T : BaseRoute> savedStateHandleFor(destinationId: DestinationId<T>): SavedStateHandle {
val entry = entryFor(destinationId)
return viewModel.provideSavedStateHandle(entry.id)
}
override fun <T : BaseRoute> storeFor(destinationId: DestinationId<T>): NavigationExecutor.Store {
val entry = entryFor(destinationId)
return storeFor(entry.id)
}
override fun <T : BaseRoute> extra(destinationId: DestinationId<T>): Any {
val entry = entryFor(destinationId)
return entry.destination.extra!!
}
internal fun storeFor(entryId: StackEntry.Id): NavigationExecutor.Store {
return viewModel.provideStore(entryId)
}
private fun <T : BaseRoute> entryFor(destinationId: DestinationId<T>): StackEntry<T> {
return stack.entryFor(destinationId)
?: throw IllegalStateException("Route $destinationId not found on back stack")
}
}
| 12
|
Kotlin
|
4
| 8
|
b5ab12979e96f40ade3b64324e3f8f9f18ea806a
| 2,787
|
Compose-Multiplatform-KmpViewModel-Unsplash-Sample
|
Apache License 2.0
|
src/test/kotlin/no/nav/bidrag/stonad/BidragStonadTest.kt
|
navikt
| 360,850,317
| false
| null |
package no.nav.bidrag.stonad
import no.nav.bidrag.stonad.BidragStonadTest.Companion.TEST_PROFILE
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.FilterType
import org.springframework.test.context.ActiveProfiles
@SpringBootApplication
@ActiveProfiles(TEST_PROFILE)
@ComponentScan(excludeFilters = [ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = [BidragStonad::class, BidragStonadLocal::class])])
class BidragStonadTest {
companion object {
const val TEST_PROFILE = "test"
}
}
fun main(args: Array<String>) {
val profile = if (args.isEmpty()) TEST_PROFILE else args[0]
val app = SpringApplication(BidragStonadTest::class.java)
app.setAdditionalProfiles(profile)
app.run(*args)
}
| 7
|
Kotlin
|
0
| 0
|
f6e31fbcc14b71789837a54b022bbbbad7fb53cf
| 888
|
bidrag-stonad
|
MIT License
|
RenameTest/rename-annotation/src/main/java/nl/peperzaken/renameannotation/Rename.kt
|
peperzaken
| 139,128,693
| false
|
{"Text": 1, "Gradle": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "Proguard": 1, "Kotlin": 6, "XML": 9, "Java": 1}
|
package nl.peperzaken.renameannotation
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
annotation class Rename
| 0
|
Kotlin
|
0
| 0
|
6d59d38a9733d2172a85b0ac7f61aaaec8652b04
| 137
|
kotlin-annotation-rename-test
|
MIT License
|
app/src/main/java/org/rfcx/incidents/view/report/deployment/detail/edit/EditDeploymentSiteActivity.kt
|
rfcx
| 104,899,135
| false
|
{"Kotlin": 1176262, "Java": 1049}
|
package org.rfcx.incidents.view.report.deployment.detail.edit
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import org.rfcx.incidents.R
import org.rfcx.incidents.databinding.ActivityEditLocationBinding
import org.rfcx.incidents.entity.stream.Stream
import org.rfcx.incidents.view.guardian.checklist.site.MapPickerFragment
class EditDeploymentSiteActivity : AppCompatActivity(), EditDeploymentSiteListener {
lateinit var binding: ActivityEditLocationBinding
private var streamId: Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_edit_location)
binding.lifecycleOwner = this
setContentView(binding.root)
setupToolbar()
initIntent()
startFragment(
EditDeploymentSiteFragment.newInstance(streamId ?: -1)
)
}
private fun initIntent() {
intent.extras?.let {
streamId = it.getInt(EXTRA_STREAM_ID)
}
}
override fun startMapPickerPage(
site: Stream
) {
startFragment(MapPickerFragment.newInstance(site))
}
override fun backToEditPage(site: Stream) {
startFragment(
EditDeploymentSiteFragment.newInstance(site.id, site.name, site.latitude, site.longitude)
)
}
override fun finishEdit() {
finish()
}
private fun startFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.replace(binding.container.id, fragment)
.commit()
}
private fun setupToolbar() {
setSupportActionBar(binding.toolbarLayout.toolbarDefault)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
title = getString(R.string.edit_location_title)
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
companion object {
const val EXTRA_STREAM_ID = "EXTRA_STREAM_ID"
fun startActivity(
context: Context,
streamId: Int
) {
val intent = Intent(context, EditDeploymentSiteActivity::class.java)
intent.putExtra(EXTRA_STREAM_ID, streamId)
(context as Activity).startActivity(intent)
}
}
}
| 30
|
Kotlin
|
0
| 0
|
cbcb9402733a959104aff97f26d04244b73bc109
| 2,677
|
guardian-app-android
|
Apache License 2.0
|
database/src/main/java/com/allsoftdroid/database/common/AudioBookDatabase.kt
|
pravinyo
| 209,936,085
| false
| null |
package com.allsoftdroid.database.common
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.allsoftdroid.database.bookListDB.AudioBookDao
import com.allsoftdroid.database.bookListDB.DatabaseAudioBook
import com.allsoftdroid.database.listenLaterDB.ListenLaterDao
import com.allsoftdroid.database.listenLaterDB.entity.DatabaseListenLaterEntity
import com.allsoftdroid.database.metadataCacheDB.MetadataDao
import com.allsoftdroid.database.metadataCacheDB.entity.DatabaseAlbumEntity
import com.allsoftdroid.database.metadataCacheDB.entity.DatabaseMetadataEntity
import com.allsoftdroid.database.metadataCacheDB.entity.DatabaseTrackEntity
import com.allsoftdroid.database.networkCacheDB.DatabaseNetworkResponseEntity
import com.allsoftdroid.database.networkCacheDB.NetworkCacheDao
/**
* Contains Database definition
*/
@Database(
entities = [
DatabaseAudioBook::class,
DatabaseMetadataEntity::class,
DatabaseAlbumEntity::class,
DatabaseTrackEntity::class,
DatabaseNetworkResponseEntity::class,
DatabaseListenLaterEntity::class
],
version = 8 ,
exportSchema = false)
abstract class AudioBookDatabase : RoomDatabase(){
//Books DAO
abstract fun audioBooksDao() : AudioBookDao
//Metadata DAO
abstract fun metadataDao() : MetadataDao
//NetworkCache DAO
abstract fun networkDao(): NetworkCacheDao
//ListenLater DAO
abstract fun listenLaterDao() : ListenLaterDao
/**
* Uses singleton approach to avoid multiple instance creation
*/
companion object {
@Volatile
private var INSTANCE : AudioBookDatabase? = null
fun getDatabase(context: Context): AudioBookDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AudioBookDatabase::class.java,
"audio_book_db"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
return instance
}
}
}
}
| 3
| null |
4
| 12
|
8358f69c0cf8dbde18904b0c3a304ec89b518c9b
| 2,336
|
AudioBook
|
MIT License
|
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/FakeOverrideFun.kt
|
ingokegel
| 72,937,917
| false
| null |
interface <lineMarker>A</lineMarker> {
fun <lineMarker>f</lineMarker>() {}
}
interface <lineMarker>B</lineMarker> : A
interface <lineMarker>C</lineMarker> : B, A
class SomeClass() : C {
override fun <lineMarker descr="Overrides function in A Press ... to navigate">f</lineMarker>() {}
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 293
|
intellij-community
|
Apache License 2.0
|
shared/src/androidMain/kotlin/dev/sasikanth/rss/reader/network/AndroidAtomParser.kt
|
msasikanth
| 632,826,313
| false
| null |
/*
* Copyright 2023 Sasikanth Miriyampalli
*
* 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 dev.sasikanth.rss.reader.network
import android.net.Uri
import android.util.Xml
import dev.sasikanth.rss.reader.models.FeedPayload
import dev.sasikanth.rss.reader.models.PostPayload
import io.github.aakira.napier.Napier
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
internal class AndroidAtomParser(private val parser: XmlPullParser, private val feedUrl: String) :
Parser() {
private val atomDateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME
override fun parse(): FeedPayload {
return readAtomFeed(parser, feedUrl)
}
private fun readAtomFeed(parser: XmlPullParser, feedUrl: String): FeedPayload {
parser.require(XmlPullParser.START_TAG, namespace, "feed")
val posts = mutableListOf<PostPayload>()
var title: String? = null
var description: String? = null
var link: String? = null
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) continue
when (parser.name) {
"title" -> title = readTagText("title", parser)
"link" ->
if (link.isNullOrBlank()) {
link = readAtomLink(parser)
}
"subtitle" -> description = readTagText("subtitle", parser)
"entry" -> posts.add(readAtomEntry(parser))
else -> skip(parser)
}
}
val domain = Uri.parse(link).host!!
val iconUrl = FeedParser.feedIcon(domain)
return FeedPayload(
name = title!!,
icon = iconUrl,
description = FeedParser.cleanText(description).orEmpty(),
homepageLink = link!!,
link = feedUrl,
posts = posts
)
}
private fun readAtomEntry(parser: XmlPullParser): PostPayload {
parser.require(XmlPullParser.START_TAG, null, "entry")
var title: String? = null
var link: String? = null
var content: String? = null
var date: String? = null
var image: String? = null
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) continue
when (val tagName = parser.name) {
"title" -> title = readTagText(tagName, parser)
"link" -> link = readAtomLink(parser)
"content" -> {
val atomContent = readAtomContent(tagName, parser)
if (content.isNullOrBlank()) {
content = atomContent.content
}
if (image.isNullOrBlank()) {
image = atomContent.imageUrl
}
}
"published" -> date = readTagText(tagName, parser)
else -> skip(parser)
}
}
val dateLong: Long =
date?.let {
try {
ZonedDateTime.parse(date, atomDateFormat).toEpochSecond() * 1000
} catch (e: Throwable) {
Napier.e("Parse date error: ${e.message}")
null
}
}
?: System.currentTimeMillis()
return PostPayload(
title = FeedParser.cleanText(title).orEmpty(),
link = FeedParser.cleanText(link).orEmpty(),
description = FeedParser.cleanTextCompact(content).orEmpty(),
imageUrl = image,
date = dateLong
)
}
private fun readAtomContent(tagName: String, parser: XmlPullParser): AtomContent {
parser.require(XmlPullParser.START_TAG, namespace, tagName)
val rawContent = readTagText(tagName, parser)
val contentBuilder = StringBuilder()
var imageUrl: String? = null
try {
val contentParser =
Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false) }
contentParser.setInput(rawContent.reader())
var parsedContent = false
var currentEventType = contentParser.eventType
var currentTag: String? = null
while (!parsedContent && currentEventType != XmlPullParser.END_DOCUMENT) {
when (currentEventType) {
XmlPullParser.START_TAG -> {
currentTag = contentParser.name
if (currentTag == "img") {
imageUrl = contentParser.getAttributeValue(namespace, "src")
}
}
XmlPullParser.TEXT -> {
val text = contentParser.text.trim()
when {
text.isNotBlank() &&
(currentTag == "p" ||
currentTag == "a" ||
currentTag == "span" ||
currentTag == "em") -> {
contentBuilder.append("$text ")
}
}
}
XmlPullParser.END_TAG -> {
if (contentParser.name == tagName) {
parsedContent = true
}
}
}
currentEventType = contentParser.next()
}
} catch (e: XmlPullParserException) {
contentBuilder.append(rawContent)
}
return AtomContent(imageUrl = imageUrl, content = contentBuilder.toString())
}
private fun readAtomLink(parser: XmlPullParser): String? {
var link: String? = null
parser.require(XmlPullParser.START_TAG, namespace, "link")
val relType = parser.getAttributeValue(namespace, "rel")
if (relType == "alternate" || relType.isNullOrBlank()) {
link = parser.getAttributeValue(namespace, "href")
}
parser.nextTag()
parser.require(XmlPullParser.END_TAG, namespace, "link")
return link
}
}
private data class AtomContent(val imageUrl: String?, val content: String)
| 9
| null |
15
| 257
|
f09d0e88ac4f611fe88b7022abf5781b81dcb48c
| 6,000
|
reader
|
Apache License 2.0
|
app/src/main/kotlin/learnopengl/App.kt
|
ludovig
| 787,352,861
| false
|
{"Kotlin": 103535, "GLSL": 3219}
|
package learnopengl
import learnopengl.a_getting_started.HelloWindow
fun main() {
println()
println("Current available tasks:")
println("------------------------")
println("\nGetting Started")
println("---------------")
println("\n\t1. Hello Window")
println("\t---------------")
println("\tgradlew hello_window")
println("\tgradlew hello_window_clear")
println("\n\t2. Hello Triangle")
println("\t-----------------")
println("\tgradlew hello_triangle")
println("\tgradlew hello_triangle_indexed")
println("\n\t3. Shaders")
println("\t----------")
println("\tgradlew shaders_uniform")
println("\tgradlew shaders_interpolation")
println("\n\t4. Textures")
println("\t-----------")
println("\tgradlew textures")
println("\n\t5. Transformations")
println("\t------------------")
println("\tgradlew transformations")
println("\n\t6. Coordinate Systems")
println("\t---------------------")
println("\tgradlew coordinate_systems")
println("\tgradlew coordinate_systems_depth")
println("\tgradlew coordinate_systems_multiple")
println("\n\t7. Camera")
println("\t---------------------")
println("\tgradlew camera_circle")
}
| 0
|
Kotlin
|
0
| 1
|
afb7d529a690ba81570389161a1f99937a7e0b25
| 1,243
|
learnopengl
|
MIT License
|
data/src/main/java/com/ttstranslate/data/storage/dao/FavoritesDao.kt
|
yiva93
| 510,226,294
| false
|
{"Kotlin": 188705}
|
package com.ttstranslate.data.storage.dao
import androidx.paging.DataSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.ttstranslate.data.storage.entity.FavoritesEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface FavoritesDao {
@Query("SELECT * FROM favorites ORDER BY dateAdded DESC")
fun observeAll(): Flow<List<FavoritesEntity>>
@Query("SELECT * FROM favorites ORDER BY dateAdded")
fun pagingSource(): DataSource.Factory<Int, FavoritesEntity>
@Query("SELECT * FROM favorites where LOWER(textFrom) LIKE LOWER(:textFrom) LIMIT 1")
suspend fun getByFromField(textFrom: String): FavoritesEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun add(favoriteEntity: FavoritesEntity): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addAll(favorites: List<FavoritesEntity>)
@Query("SELECT * FROM favorites WHERE id=:id")
suspend fun getById(id: Long): FavoritesEntity
@Query("DELETE FROM favorites")
suspend fun drop()
@Query("DELETE FROM favorites WHERE id = :id")
suspend fun deleteById(id: Long)
}
| 0
|
Kotlin
|
0
| 0
|
7025799cf3288b6f982074ed956edfdc4677f5e0
| 1,194
|
TTSTranslateSample
|
Apache License 2.0
|
moneyedittext-kotlin/src/main/kotlin/com/shuhart/moneyedittext/MoneyTextUtils.kt
|
shuhart
| 107,895,930
| false
| null |
package com.shuhart.moneyedittext
import android.text.InputType
import android.text.method.DigitsKeyListener
import android.text.method.KeyListener
import java.text.NumberFormat
import java.util.*
object MoneyTextUtils {
@Suppress("DEPRECATION")
fun buildKeyListener(acceptedChars: CharArray): KeyListener {
return object : DigitsKeyListener() {
override fun getAcceptedChars(): CharArray = acceptedChars
override fun getInputType(): Int = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
}
}
fun buildSupportedCryptoSymbols(currencies: List<String>): CharArray {
val result = mutableListOf<Char>()
currencies
.map { getCurrencyInfo(it).formattedSymbol.toCharArray() }
.forEach { it.forEach { result.add(it) } }
return result.distinct().toCharArray()
}
private fun extractCurrency(text: String): CurrencyTextInfo {
val index = text.indexOf("1")
var formattedSymbol = ""
return when (index) {
0 -> {
(text.length - 1 downTo 0)
.takeWhile { !text[it].isDigit() }
.forEach { formattedSymbol += text[it] }
CurrencyTextInfo(position = CurrencyTextInfo.CURRENCY_POSITION_END, formattedSymbol = formattedSymbol.reversed())
}
else -> {
(0 until text.length)
.takeWhile { !text[it].isDigit() }
.forEach { formattedSymbol += text[it] }
CurrencyTextInfo(position = CurrencyTextInfo.CURRENCY_POSITION_START, formattedSymbol = formattedSymbol)
}
}
}
fun getCurrencyInfo(currency: String): CurrencyTextInfo {
val stub = prettyMoney(1.0, currency, 0)
return extractCurrency(stub)
}
fun prettyMoney(number: Double, currency: String, precision: Int): String {
val numberFormat = NumberFormat.getCurrencyInstance(Locale.getDefault())
numberFormat.currency = Currency.getInstance(currency.toUpperCase())
numberFormat.minimumFractionDigits = precision
numberFormat.maximumFractionDigits = precision
val text = numberFormat.format(number)
return replaceRussianRublesToOwn(text)
}
private fun replaceRussianRublesToOwn(text: String): String {
val indexEnUs = text.indexOf("RUB")
val indexRu = text.indexOf("руб.")
if (indexEnUs >= 0) {
return text.replace("RUB", "\u20BD")
}
return if (indexRu >= 0) {
text.replace("руб.", "\u20BD")
} else text
}
}
class CurrencyTextInfo(val position: Int, val formattedSymbol: String) {
companion object {
val CURRENCY_POSITION_START = 0
val CURRENCY_POSITION_END = 1
}
}
| 1
|
Kotlin
|
2
| 9
|
5f34c950ae134de96dfca99417dad5e58842b62e
| 2,858
|
MoneyEditText
|
Apache License 2.0
|
extension/junit5-platform-8/src/main/kotlin/org/camunda/community/process_test_coverage/junit5/platform8/ProcessEngineCoverageExtension.kt
|
camunda-community-hub
| 43,815,708
| false
| null |
/*-
* #%L
* Camunda Process Test Coverage JUnit5 Platform 8
* %%
* Copyright (C) 2019 - 2024 Camunda
* %%
* 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.
* #L%
*/
package org.camunda.community.process_test_coverage.junit5.platform8
import io.camunda.zeebe.process.test.assertions.BpmnAssert
import mu.KLogging
import org.assertj.core.api.Condition
import org.camunda.community.process_test_coverage.core.engine.ExcludeFromProcessCoverage
import org.camunda.community.process_test_coverage.core.model.DefaultCollector
import org.camunda.community.process_test_coverage.engine.platform8.ZeebeModelProvider
import org.camunda.community.process_test_coverage.engine.platform8.createEvents
import org.camunda.community.process_test_coverage.junit5.common.ProcessEngineCoverageExtensionBuilder
import org.camunda.community.process_test_coverage.junit5.common.ProcessEngineCoverageExtensionHelper
import org.junit.jupiter.api.extension.AfterAllCallback
import org.junit.jupiter.api.extension.AfterTestExecutionCallback
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback
import org.junit.jupiter.api.extension.ExtensionContext
/**
* Extension for JUnit 5 which allows the tracking of coverage information for Camunda Platform 8 (Zeebe) process tests.
*
* @author <NAME>
*/
class ProcessEngineCoverageExtension(
/**
* Log class and test method coverages?
*/
private val detailedCoverageLogging: Boolean = false,
/**
* Is method coverage handling needed?
*/
private val handleTestMethodCoverage: Boolean = true,
/**
* A list of process definition keys excluded from the test run.
*/
private val excludedProcessDefinitionKeys: List<String> = listOf(),
) : BeforeAllCallback, AfterAllCallback, BeforeTestExecutionCallback, AfterTestExecutionCallback {
companion object : KLogging() {
@JvmStatic
fun builder() = Builder()
}
/**
* The state of the current run (class and current method).
*/
private val coverageCollector = DefaultCollector(ZeebeModelProvider())
/**
* Conditions to be asserted on the class coverage percentage.
*/
private val classCoverageAssertionConditions: MutableList<Condition<Double>> = mutableListOf()
/**
* Conditions to be asserted on the individual test method coverages.
*/
private val testMethodNameToCoverageConditions: MutableMap<String, MutableList<Condition<Double>>> = mutableMapOf()
/**
* Map of test method to last event time, when test method was started.
*/
private val methodRecordPosition = mutableMapOf<String, Long>()
private val processEngineCoverageExtensionHelper = ProcessEngineCoverageExtensionHelper(coverageCollector,
detailedCoverageLogging, handleTestMethodCoverage, excludedProcessDefinitionKeys,
classCoverageAssertionConditions, testMethodNameToCoverageConditions)
/**
* Handles creating the run if a relevant test method is called.
*/
override fun beforeTestExecution(context: ExtensionContext) {
if (!isTestMethodExcluded(context)) {
processEngineCoverageExtensionHelper.beforeTestExecution(context)
methodRecordPosition[context.requiredTestMethod.name] = BpmnAssert.getRecordStream().records().maxOfOrNull { it.position } ?: -1
}
}
/**
* Handles evaluating the test method coverage after a relevant test method is finished.
*/
override fun afterTestExecution(context: ExtensionContext) {
if (!isTestMethodExcluded(context)) {
createEvents(coverageCollector, methodRecordPosition[context.requiredTestMethod.name]!!)
processEngineCoverageExtensionHelper.afterTestExecution(context)
}
}
private fun isTestMethodExcluded(context: ExtensionContext) =
context.requiredTestClass.annotations.any { it is ExcludeFromProcessCoverage }
|| context.requiredTestMethod.annotations.any { it is ExcludeFromProcessCoverage }
/**
* Initializes the suite for all upcoming tests.
*/
override fun beforeAll(context: ExtensionContext) {
processEngineCoverageExtensionHelper.beforeAll(context)
}
/**
* If the extension is registered on the class level, log and assert the coverage and create a
* graphical report. For the class coverage to work all the test method
* deployments have to be equal.
*/
override fun afterAll(context: ExtensionContext) {
processEngineCoverageExtensionHelper.afterAll(context)
}
fun addTestMethodCoverageCondition(methodName: String, condition: Condition<Double>) =
testMethodNameToCoverageConditions.getOrPut(methodName) { mutableListOf() }.add(condition)
private fun addClassCoverageAtLeast(percentage: Double) =
classCoverageAssertionConditions.add(
Condition<Double>({ p -> p >= percentage }, "matches if the coverage ratio is at least $percentage")
)
class Builder : ProcessEngineCoverageExtensionBuilder<ProcessEngineCoverageExtension>() {
override fun build(): ProcessEngineCoverageExtension {
return ProcessEngineCoverageExtension(
detailedCoverageLogging = detailedCoverageLogging,
handleTestMethodCoverage = handleTestMethodCoverage,
excludedProcessDefinitionKeys = excludedProcessDefinitionKeys
).apply {
coverageFromSystemProperty(this@Builder.optionalAssertCoverageAtLeastProperty)?.let {
addClassCoverageAtLeast(it)
}
this@Builder.coverageAtLeast?.let { addClassCoverageAtLeast(it) }
}
}
}
}
| 9
| null |
47
| 76
|
f984f9cd2b15ef33528d0d50d147a0004dc2d79e
| 6,369
|
camunda-process-test-coverage
|
Apache License 2.0
|
extension/junit5-platform-8/src/main/kotlin/org/camunda/community/process_test_coverage/junit5/platform8/ProcessEngineCoverageExtension.kt
|
camunda-community-hub
| 43,815,708
| false
| null |
/*-
* #%L
* Camunda Process Test Coverage JUnit5 Platform 8
* %%
* Copyright (C) 2019 - 2024 Camunda
* %%
* 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.
* #L%
*/
package org.camunda.community.process_test_coverage.junit5.platform8
import io.camunda.zeebe.process.test.assertions.BpmnAssert
import mu.KLogging
import org.assertj.core.api.Condition
import org.camunda.community.process_test_coverage.core.engine.ExcludeFromProcessCoverage
import org.camunda.community.process_test_coverage.core.model.DefaultCollector
import org.camunda.community.process_test_coverage.engine.platform8.ZeebeModelProvider
import org.camunda.community.process_test_coverage.engine.platform8.createEvents
import org.camunda.community.process_test_coverage.junit5.common.ProcessEngineCoverageExtensionBuilder
import org.camunda.community.process_test_coverage.junit5.common.ProcessEngineCoverageExtensionHelper
import org.junit.jupiter.api.extension.AfterAllCallback
import org.junit.jupiter.api.extension.AfterTestExecutionCallback
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback
import org.junit.jupiter.api.extension.ExtensionContext
/**
* Extension for JUnit 5 which allows the tracking of coverage information for Camunda Platform 8 (Zeebe) process tests.
*
* @author <NAME>
*/
class ProcessEngineCoverageExtension(
/**
* Log class and test method coverages?
*/
private val detailedCoverageLogging: Boolean = false,
/**
* Is method coverage handling needed?
*/
private val handleTestMethodCoverage: Boolean = true,
/**
* A list of process definition keys excluded from the test run.
*/
private val excludedProcessDefinitionKeys: List<String> = listOf(),
) : BeforeAllCallback, AfterAllCallback, BeforeTestExecutionCallback, AfterTestExecutionCallback {
companion object : KLogging() {
@JvmStatic
fun builder() = Builder()
}
/**
* The state of the current run (class and current method).
*/
private val coverageCollector = DefaultCollector(ZeebeModelProvider())
/**
* Conditions to be asserted on the class coverage percentage.
*/
private val classCoverageAssertionConditions: MutableList<Condition<Double>> = mutableListOf()
/**
* Conditions to be asserted on the individual test method coverages.
*/
private val testMethodNameToCoverageConditions: MutableMap<String, MutableList<Condition<Double>>> = mutableMapOf()
/**
* Map of test method to last event time, when test method was started.
*/
private val methodRecordPosition = mutableMapOf<String, Long>()
private val processEngineCoverageExtensionHelper = ProcessEngineCoverageExtensionHelper(coverageCollector,
detailedCoverageLogging, handleTestMethodCoverage, excludedProcessDefinitionKeys,
classCoverageAssertionConditions, testMethodNameToCoverageConditions)
/**
* Handles creating the run if a relevant test method is called.
*/
override fun beforeTestExecution(context: ExtensionContext) {
if (!isTestMethodExcluded(context)) {
processEngineCoverageExtensionHelper.beforeTestExecution(context)
methodRecordPosition[context.requiredTestMethod.name] = BpmnAssert.getRecordStream().records().maxOfOrNull { it.position } ?: -1
}
}
/**
* Handles evaluating the test method coverage after a relevant test method is finished.
*/
override fun afterTestExecution(context: ExtensionContext) {
if (!isTestMethodExcluded(context)) {
createEvents(coverageCollector, methodRecordPosition[context.requiredTestMethod.name]!!)
processEngineCoverageExtensionHelper.afterTestExecution(context)
}
}
private fun isTestMethodExcluded(context: ExtensionContext) =
context.requiredTestClass.annotations.any { it is ExcludeFromProcessCoverage }
|| context.requiredTestMethod.annotations.any { it is ExcludeFromProcessCoverage }
/**
* Initializes the suite for all upcoming tests.
*/
override fun beforeAll(context: ExtensionContext) {
processEngineCoverageExtensionHelper.beforeAll(context)
}
/**
* If the extension is registered on the class level, log and assert the coverage and create a
* graphical report. For the class coverage to work all the test method
* deployments have to be equal.
*/
override fun afterAll(context: ExtensionContext) {
processEngineCoverageExtensionHelper.afterAll(context)
}
fun addTestMethodCoverageCondition(methodName: String, condition: Condition<Double>) =
testMethodNameToCoverageConditions.getOrPut(methodName) { mutableListOf() }.add(condition)
private fun addClassCoverageAtLeast(percentage: Double) =
classCoverageAssertionConditions.add(
Condition<Double>({ p -> p >= percentage }, "matches if the coverage ratio is at least $percentage")
)
class Builder : ProcessEngineCoverageExtensionBuilder<ProcessEngineCoverageExtension>() {
override fun build(): ProcessEngineCoverageExtension {
return ProcessEngineCoverageExtension(
detailedCoverageLogging = detailedCoverageLogging,
handleTestMethodCoverage = handleTestMethodCoverage,
excludedProcessDefinitionKeys = excludedProcessDefinitionKeys
).apply {
coverageFromSystemProperty(this@Builder.optionalAssertCoverageAtLeastProperty)?.let {
addClassCoverageAtLeast(it)
}
this@Builder.coverageAtLeast?.let { addClassCoverageAtLeast(it) }
}
}
}
}
| 9
| null |
47
| 76
|
f984f9cd2b15ef33528d0d50d147a0004dc2d79e
| 6,369
|
camunda-process-test-coverage
|
Apache License 2.0
|
src/main/kotlin/turniplabs/industry/blocks/entities/TileEntityCompressor.kt
|
FatherCheese
| 673,567,283
| false
|
{"Kotlin": 207937, "Java": 3827}
|
package turniplabs.industry.blocks.entities
import com.mojang.nbt.CompoundTag
import com.mojang.nbt.ListTag
import net.minecraft.core.entity.player.EntityPlayer
import net.minecraft.core.item.ItemStack
import net.minecraft.core.player.inventory.IInventory
import sunsetsatellite.energyapi.impl.ItemEnergyContainer
import sunsetsatellite.sunsetutils.util.Connection
import sunsetsatellite.sunsetutils.util.Direction
import turniplabs.industry.blocks.IndustryBlocks
import turniplabs.industry.blocks.machines.BlockCompressor
import turniplabs.industry.recipes.RecipesCompressor
class TileEntityCompressor : TileEntityEnergyConductorDamageable(), IInventory {
var active = false
private var contents: Array<ItemStack?>
private var currentCompression = 0
private val maxCompression = 160
init {
contents = arrayOfNulls(4)
setCapacity(1024)
setTransfer(32)
setMaxReceive(32)
for (dir in Direction.values())
setConnection(dir, Connection.INPUT)
}
override fun getSizeInventory(): Int {
return contents.size
}
override fun getStackInSlot(i: Int): ItemStack? {
return contents[i]
}
override fun decrStackSize(i: Int, j: Int): ItemStack? {
return if (contents[i] != null) {
if (contents[i]!!.stackSize <= j) {
val itemStack: ItemStack? = contents[i]
contents[i] = null
onInventoryChanged()
return itemStack!!
}
val itemStack: ItemStack = contents[i]!!.splitStack(j)
if (contents[i]!!.stackSize == 0) {
contents[i] = null
}
onInventoryChanged()
itemStack
} else
return null
}
override fun setInventorySlotContents(i: Int, itemStack: ItemStack?) {
contents[i] = itemStack
if (itemStack != null && itemStack.stackSize > inventoryStackLimit)
itemStack.stackSize = inventoryStackLimit
onInventoryChanged()
}
override fun getInvName(): String {
return "Compressor"
}
override fun getInventoryStackLimit(): Int {
return 64
}
override fun canInteractWith(entityPlayer: EntityPlayer?): Boolean {
if (worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this)
return false
return entityPlayer!!.distanceToSqr(
(xCoord + 0.5f).toDouble(),
(yCoord + 0.5f).toDouble(),
(zCoord + 0.5f).toDouble()
) <= 64.0f
}
override fun updateEntity() {
super.updateEntity()
val hasEnergy: Boolean = energy > 0
var machineUpdated = false
if (getStackInSlot(0) != null && getStackInSlot(0)?.item is ItemEnergyContainer) {
provide(getStackInSlot(0), getMaxProvide(), false)
onInventoryChanged()
}
if (getStackInSlot(1) != null && getStackInSlot(1)?.item is ItemEnergyContainer) {
val stack: ItemStack? = getStackInSlot(1)
receive(stack, maxReceive, false)
onInventoryChanged()
}
if (!worldObj.isClientSide) {
if (worldObj.getBlockId(xCoord, yCoord, zCoord) == IndustryBlocks.machineCompressor.id &&
currentCompression == 0 &&
contents[2] == null
) {
BlockCompressor.updateBlockState(true, worldObj, xCoord, yCoord, zCoord)
machineUpdated = true
}
}
if (hasEnergy && canCompress()) {
++currentCompression
--energy
active = true
if (currentCompression == maxCompression) {
currentCompression = 0
compressItem()
active = false
machineUpdated = true
}
} else {
currentCompression = 0
active = false
}
if (machineUpdated)
onInventoryChanged()
if (active)
worldObj.markBlockDirty(xCoord, yCoord, zCoord)
}
override fun readFromNBT(compoundTag: CompoundTag?) {
super.readFromNBT(compoundTag)
val nbtTagList = compoundTag!!.getList("Items")
contents = arrayOfNulls(sizeInventory)
for (i in 0 until nbtTagList.tagCount()) {
val compoundTag2: CompoundTag = nbtTagList.tagAt(i) as CompoundTag
val byte: Int = compoundTag2.getByte("Slot").toInt()
if (byte >= 0 && byte < contents.size)
contents[byte] = ItemStack.readItemStackFromNbt(compoundTag2)
}
currentCompression = compoundTag.getShort("Compression").toInt()
energy = compoundTag.getShort("Energy").toInt()
}
override fun writeToNBT(compoundTag: CompoundTag?) {
super.writeToNBT(compoundTag)
compoundTag?.putShort("Compression", currentCompression.toShort())
compoundTag?.putShort("Energy", energy.toShort())
val listTag = ListTag()
for (i in contents.indices) {
if (contents[i] != null) {
val compoundTag2 = CompoundTag()
compoundTag2.putByte("Slot", i.toByte())
contents[i]!!.writeToNBT(compoundTag2)
listTag.addTag(compoundTag2)
}
}
compoundTag!!.put("Items", listTag)
}
private fun canCompress(): Boolean {
if (contents[2] == null)
return false
if (contents[2]!!.item == null)
return false
val itemStack: ItemStack? = RecipesCompressor.getResult(contents[2]!!.item.id)
return when {
contents[3] == null -> true
!contents[3]!!.isItemEqual(itemStack) -> false
contents[3]!!.stackSize < inventoryStackLimit && contents[3]!!.stackSize < contents[3]!!.maxStackSize -> true
else -> contents[3]!!.stackSize < itemStack!!.maxStackSize
}
}
private fun compressItem() {
if (canCompress()) {
val itemStack: ItemStack = RecipesCompressor.getResult(contents[2]!!.item.id) ?: return
if (contents[3] == null)
contents[3] = itemStack.copy()
else
if (contents[3]!!.itemID == itemStack.itemID)
++contents[3]!!.stackSize
--contents[2]!!.stackSize
if (contents[2]!!.stackSize <= 0)
contents[2] = null
}
}
fun getProgressScaled(i: Int): Int {
return if (maxCompression == 0) 0 else (currentCompression * i) / maxCompression
}
}
| 1
|
Kotlin
|
2
| 1
|
66419a1444ec93518f067eb43fcd723f9ecc2268
| 6,635
|
Industry2
|
Creative Commons Zero v1.0 Universal
|
oauth/src/main/java/jp/co/soramitsu/oauth/base/navigation/NavigationExt.kt
|
sora-xor
| 610,919,196
| false
| null |
package jp.co.soramitsu.oauth.base.navigation
import android.os.Bundle
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.runtime.Composable
import androidx.navigation.NamedNavArgument
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDeepLink
import androidx.navigation.NavGraphBuilder
import com.google.accompanist.navigation.animation.composable
private const val TRANSITION_DURATION = 300
@ExperimentalAnimationApi
fun NavGraphBuilder.animatedComposable(
route: String,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
content: @Composable AnimatedVisibilityScope.(NavBackStackEntry) -> Unit
) {
this.composable(
route = route,
arguments = arguments,
deepLinks = deepLinks,
enterTransition = {
slideInHorizontally(
initialOffsetX = { it },
animationSpec = tween(TRANSITION_DURATION)
)
},
popEnterTransition = {
slideInHorizontally(
initialOffsetX = { -it },
animationSpec = tween(TRANSITION_DURATION)
)
},
exitTransition = {
slideOutHorizontally(
targetOffsetX = { -it },
animationSpec = tween(TRANSITION_DURATION)
)
},
popExitTransition = {
slideOutHorizontally(
targetOffsetX = { it },
animationSpec = tween(TRANSITION_DURATION)
)
},
content = content
)
}
fun NavBackStackEntry.requireArguments(): Bundle {
return arguments ?: throw IllegalStateException("Arguments is null")
}
fun Bundle.requireString(key: String): String {
return getString(key) ?: throw IllegalStateException("Argument is null")
}
| 18
|
Kotlin
|
1
| 2
|
410fe1823630ef60c8c9584014f91caf03fd6656
| 2,077
|
sora-card-android
|
Apache License 2.0
|
travis-interface/src/main/java/com/kevalpatel2106/greenbuild/travisInterface/response/BranchesResponse.kt
|
kevalpatel2106
| 129,620,378
| false
| null |
package com.kevalpatel2106.greenbuild.travisInterface.response
import com.google.gson.annotations.SerializedName
import com.kevalpatel2106.greenbuild.travisInterface.entities.TravisBranch
internal data class BranchesResponse(
@field:SerializedName("branches")
val branches: ArrayList<TravisBranch>,
@field:SerializedName("@pagination")
val pagination: Pagination
){
internal data class Pagination(
@field:SerializedName("is_last")
val isLast: Boolean,
@field:SerializedName("offset")
val offset: Int,
@field:SerializedName("limit")
val limit: Int,
@field:SerializedName("count")
val count: Int? = null,
@field:SerializedName("is_first")
val isFirst: Boolean
)
}
| 6
|
Kotlin
|
14
| 75
|
da9f2e64cd09848528f313d0e3188b7c40f4b3f7
| 707
|
green-build
|
Apache License 2.0
|
src/test/kotlin/no/nav/permitteringsportal/database/DatabaseTest.kt
|
navikt
| 435,468,925
| false
|
{"Kotlin": 54535, "Dockerfile": 91}
|
package no.nav.permitteringsportal.database
import no.nav.permitteringsportal.setup.issuerConfig
import no.nav.permitteringsportal.startLokalApp
import no.nav.security.mock.oauth2.MockOAuth2Server
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
class DatabaseTest {
companion object {
private val mockOAuth2Server = MockOAuth2Server()
private val dataSource = LokalDatabaseConfig().dataSource
init {
mockOAuth2Server.shutdown()
mockOAuth2Server.start()
}
}
@Test
fun `Skal kunne skrive og lese fra database`() {
startLokalApp(dataSource, issuerConfig = issuerConfig(mockOAuth2Server)).use {
LokalDatabaseConfig().deleteAll()
val repository = Repository(dataSource)
repository.leggTilNyBekreftelse("11111111111", "111111111");
val hentAlt = repository.hentAlleBekreftelserForOrganisasjon("111111111");
assertThat(hentAlt.size).isEqualTo(1)
}
}
@Test
fun `Skal lagre en ny hendelse sammen med bekreftelse for en organisasjon`() {
startLokalApp(dataSource, issuerConfig = issuerConfig(mockOAuth2Server)).use {
LokalDatabaseConfig().deleteAll()
val repository = Repository(dataSource)
repository.leggTilNyBekreftelse("11111111111", "111111111");
val alleBekreftelserForOrganisasjon = repository.hentAlleBekreftelserForOrganisasjon("111111111");
assertThat(alleBekreftelserForOrganisasjon.size).isEqualTo(1)
assertThat(alleBekreftelserForOrganisasjon[0].orgnr).isEqualTo("111111111")
}
}
@Test
fun `Skal kunne lagre flere hendelser på en bekreftelse`() {
startLokalApp(dataSource, issuerConfig = issuerConfig(mockOAuth2Server)).use {
LokalDatabaseConfig().deleteAll()
val repository = Repository(dataSource)
val bekreftelseId = repository.leggTilNyBekreftelse("11111111111", "111111111");
val hendelseId =
repository.leggTilNyHendelsePåBekreftelse(bekreftelseId, "NY",100, Date(), Date())
assertNotNull(hendelseId)
val hendelseId2 =
repository.leggTilNyHendelsePåBekreftelse(bekreftelseId, "ENDRING",100, Date(), Date())
assertNotNull(hendelseId2)
assertNotEquals(hendelseId, hendelseId2)
val hentAlleHendelser =
repository.hentAlleHendelserForBekreftelseOgOrganisasjon("111111111", bekreftelseId)
assertNotNull(hentAlleHendelser)
assertEquals(2, hentAlleHendelser.size)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
aa1dc34de424934e00835ff17e8b5015d6c23617
| 2,787
|
permitteringsportal-api
|
MIT License
|
hideout-core/src/main/kotlin/dev/usbharu/hideout/application/config/OwlConfig.kt
|
usbharu
| 627,026,893
| false
|
{"Kotlin": 1472831, "Mustache": 111614, "Gherkin": 21440, "JavaScript": 1112, "HTML": 936}
|
/*
* Copyright (C) 2024 usbharu
*
* 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 dev.usbharu.hideout.application.config
import com.fasterxml.jackson.databind.ObjectMapper
import dev.usbharu.owl.broker.ModuleContext
import dev.usbharu.owl.common.property.*
import dev.usbharu.owl.common.retry.RetryPolicyFactory
import dev.usbharu.owl.producer.api.OWL
import dev.usbharu.owl.producer.api.OwlProducer
import dev.usbharu.owl.producer.defaultimpl.DEFAULT
import dev.usbharu.owl.producer.embedded.EMBEDDED
import dev.usbharu.owl.producer.embedded.EMBEDDED_GRPC
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.*
@Configuration
class OwlConfig(private val producerConfig: ProducerConfig) {
@Bean
fun producer(
@Autowired(required = false) retryPolicyFactory: RetryPolicyFactory? = null,
@Qualifier("activitypub") objectMapper: ObjectMapper,
): OwlProducer {
return when (producerConfig.mode) {
ProducerMode.EMBEDDED -> {
OWL(EMBEDDED) {
if (retryPolicyFactory != null) {
this.retryPolicyFactory = retryPolicyFactory
}
if (producerConfig.port != null) {
this.port = producerConfig.port.toString()
}
val moduleContext = ServiceLoader.load(ModuleContext::class.java).firstOrNull()
if (moduleContext != null) {
this.moduleContext = moduleContext
}
this.propertySerializerFactory = CustomPropertySerializerFactory(
setOf(
IntegerPropertySerializer(),
StringPropertyValueSerializer(),
DoublePropertySerializer(),
BooleanPropertySerializer(),
LongPropertySerializer(),
FloatPropertySerializer(),
ObjectPropertySerializer(objectMapper),
)
)
}
}
ProducerMode.GRPC -> {
OWL(EMBEDDED_GRPC) {
}
}
ProducerMode.EMBEDDED_GRPC -> {
OWL(DEFAULT) {
}
}
}
}
}
@ConfigurationProperties("hideout.owl.producer")
data class ProducerConfig(val mode: ProducerMode = ProducerMode.EMBEDDED, val port: Int? = null)
enum class ProducerMode {
GRPC,
EMBEDDED,
EMBEDDED_GRPC
}
| 41
|
Kotlin
|
0
| 11
|
1c18c6d0dcbd3079ad64f8d211e877c7c41520ed
| 3,372
|
Hideout
|
Apache License 2.0
|
graph/graph-application/src/test/kotlin/eu/tib/orkg/prototype/contenttypes/services/ContributionServiceUnitTests.kt
|
TIBHannover
| 197,416,205
| false
|
{"Kotlin": 2994730, "Cypher": 216833, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240}
|
package org.orkg.contenttypes.domain
import io.kotest.assertions.asClue
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import java.util.*
import org.junit.jupiter.api.Test
import org.orkg.common.PageRequests
import org.orkg.graph.domain.Classes
import org.orkg.graph.domain.Visibility
import org.orkg.graph.output.ResourceRepository
import org.orkg.graph.output.StatementRepository
import org.orkg.graph.testing.fixtures.createResource
import org.springframework.data.domain.Page
class ContributionServiceUnitTests {
private val resourceRepository: ResourceRepository = mockk()
private val statementRepository: StatementRepository = mockk()
private val service = ContributionService(resourceRepository, statementRepository)
@Test
fun `Given a contribution exists, when fetching it by id, then it is returned`() {
val expected = createResource(
classes = setOf(Classes.contribution)
)
every { resourceRepository.findById(expected.id) } returns Optional.of(expected)
every { statementRepository.findAllBySubject(expected.id, PageRequests.ALL) } returns Page.empty(PageRequests.ALL)
val actual = service.findById(expected.id)
actual.isPresent shouldBe true
actual.get() shouldNotBe null
actual.get().asClue { contribution ->
contribution.id shouldBe expected.id
contribution.label shouldBe expected.label
contribution.properties shouldNotBe null
contribution.properties shouldBe emptyMap()
contribution.createdAt shouldBe expected.createdAt
contribution.createdBy shouldBe expected.createdBy
contribution.visibility shouldBe Visibility.DEFAULT
contribution.unlistedBy shouldBe expected.unlistedBy
}
verify(exactly = 1) { resourceRepository.findById(expected.id) }
verify(exactly = 1) { statementRepository.findAllBySubject(expected.id, any()) }
}
@Test
fun `Given a resource, when fetching it as a contribution although its not a contribution, then it returns an empty result`() {
val expected = createResource()
every { resourceRepository.findById(expected.id) } returns Optional.of(expected)
service.findById(expected.id).isPresent shouldBe false
verify(exactly = 1) { resourceRepository.findById(expected.id) }
verify(exactly = 0) { statementRepository.findAllBySubject(expected.id, any()) }
}
}
| 0
|
Kotlin
|
2
| 5
|
8739ce33adc28e780a0c98771cd0c91b63dc922a
| 2,571
|
orkg-backend
|
MIT License
|
common/src/main/java/com/prosabdev/common/roomdatabase/repositories/equalizer/EqualizerPresetBandLevelItemRepository.kt
|
4kpros
| 555,755,264
| false
|
{"Kotlin": 948923, "Java": 1923}
|
package com.prosabdev.common.roomdatabase.repositories.equalizer
import android.content.Context
import com.prosabdev.common.models.equalizer.EqualizerPresetBandLevelItem
import com.prosabdev.common.roomdatabase.AppDatabase
import com.prosabdev.common.roomdatabase.dao.equalizer.EqualizerPresetBandLevelItemDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class EqualizerPresetBandLevelItemRepository(ctx : Context) {
private var mDao: EqualizerPresetBandLevelItemDao? = AppDatabase.getDatabase(ctx).equalizerPresetBandLevelItemDao()
suspend fun insert(item: EqualizerPresetBandLevelItem?): Long?{
return withContext(Dispatchers.IO){
mDao?.insert(item)
}
}
suspend fun insertMultiple(itemList: List<EqualizerPresetBandLevelItem>?): List<Long>?{
return withContext(Dispatchers.IO){
mDao?.insertMultiple(itemList)
}
}
suspend fun update(item: EqualizerPresetBandLevelItem?): Int?{
return withContext(Dispatchers.IO){
mDao?.update(item)
}
}
suspend fun delete(item: EqualizerPresetBandLevelItem?): Int?{
return withContext(Dispatchers.IO){
mDao?.delete(item)
}
}
suspend fun deleteMultiple(itemList: List<EqualizerPresetBandLevelItem>?): Int?{
return withContext(Dispatchers.IO){
mDao?.deleteMultiple(itemList)
}
}
suspend fun deleteAtId(id: Long): Int?{
return withContext(Dispatchers.IO){
mDao?.deleteAtId(id)
}
}
suspend fun deleteBandAtPresetName(bandId: Int, presetName: String?): Int?{
return withContext(Dispatchers.IO){
mDao?.deleteBandAtPresetName(bandId, presetName)
}
}
suspend fun deleteAllBandsAtPresetName(presetName: String?): Int?{
return withContext(Dispatchers.IO){
mDao?.deleteAllBandsAtPresetName(presetName)
}
}
suspend fun deleteAll(): Int?{
return withContext(Dispatchers.IO){
mDao?.deleteAll()
}
}
suspend fun getAtId(id: Long): EqualizerPresetBandLevelItem?{
return withContext(Dispatchers.IO){
mDao?.getAtId(id)
}
}
suspend fun getBandAtPresetName(presetName: String?, bandId: Short): EqualizerPresetBandLevelItem?{
return withContext(Dispatchers.IO){
mDao?.getBandAtPresetName(presetName, bandId)
}
}
suspend fun getAllAtPresetName(presetName: String?): List<EqualizerPresetBandLevelItem>?{
return withContext(Dispatchers.IO){
mDao?.getAllAtPresetName(presetName)
}
}
}
| 0
|
Kotlin
|
0
| 2
|
c9363fa150d1cd34b0fac119c825bfe75e2f96e1
| 2,674
|
FluidMusic
|
Apache License 2.0
|
idea/tests/org/jetbrains/kotlin/idea/lightClasses/LightElementsEqualsTest.kt
|
JakeWharton
| 99,388,807
| false
| null |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.lightClasses
import com.intellij.psi.*
import com.intellij.testFramework.LightProjectDescriptor
import junit.framework.TestCase
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.KtElement
import java.lang.System.identityHashCode as idh
class LightElementsEqualsTest : KotlinLightCodeInsightFixtureTestCase() {
private val SAMPLE_SOURCE = """
class A(i: Int) {
val b: String
@Synchronized
fun foo(param: String){}
}
""".trimIndent()
fun testEqualityOfTwiceConvertedLightElements() {
val psiFile = myFixture.configureByText("a.kt", SAMPLE_SOURCE)
psiFile.accept(object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element is KtElement) {
val firstConversion = element.toLightElements()
val secondConversion = element.toLightElements()
TestCase.assertEquals(
"LightElements from ${element.text} should be equal if they retrieved twice",
firstConversion, secondConversion
)
for ((e1, e2) in firstConversion zip secondConversion) {
TestCase.assertEquals(
"LightElements '$e1'(${e1.javaClass}) and '$e2'(${e2.javaClass}) from `${element.text}` should have equal hashcode as long as they are equal",
e1.hashCode(), e2.hashCode()
)
}
}
element.acceptChildren(this)
}
})
}
fun testToLightMethodsConvertedEquality() {
myFixture.configureByText("a.kt", SAMPLE_SOURCE)
val theAPsiClass = myFixture.javaFacade.findClass("A")
val directlyFlattenMethods = theAPsiClass.methods.asSequence().flatMap { psiElementsFlatten(it) }
val contentOfToLightMethods = (theAPsiClass as KtLightClass).kotlinOrigin!!.declarations.asSequence()
.flatMap { it.toLightMethods().asSequence() }
.flatMap { psiElementsFlatten(it) }
for ((e1, e2) in directlyFlattenMethods zip contentOfToLightMethods) {
TestCase.assertEquals(e1, e2)
TestCase.assertEquals(e1.hashCode(), e2.hashCode())
}
}
private fun psiElementsFlatten(psiElement: PsiElement): Sequence<PsiElement> {
return when (psiElement) {
is PsiClass -> sequenceOf(psiElement, psiElement.modifierList).filterNotNull() +
psiElement.methods.asSequence().flatMap { psiElementsFlatten(it) } +
psiElement.fields.asSequence().flatMap { psiElementsFlatten(it) }
is PsiMethod -> sequenceOf(psiElement, psiElement.parameterList) + psiElementsFlatten(psiElement.parameterList)
is PsiParameterList -> sequenceOf(psiElement) +
psiElement.parameters.asSequence().flatMap { psiElementsFlatten(it) }
is PsiModifierList -> sequenceOf(psiElement) +
psiElement.annotations.asSequence().flatMap { psiElementsFlatten(it) }
is PsiAnnotation -> sequenceOf(psiElement, psiElement.parameterList) + psiElementsFlatten(psiElement.parameterList)
else -> sequenceOf(psiElement)
}
}
override fun getProjectDescriptor(): LightProjectDescriptor {
return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
}
| 0
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 4,552
|
kotlin
|
Apache License 2.0
|
backend/src/main/kotlin/org/beckn/one/sandbox/bap/client/discovery/controllers/SearchController.kt
|
beckn
| 508,229,088
| false
| null |
package org.beckn.one.sandbox.bap.client.discovery.controllers
import org.beckn.one.sandbox.bap.client.discovery.services.ProtocolSearchService
import org.beckn.one.sandbox.bap.client.shared.dtos.SearchRequestDto
import org.beckn.one.sandbox.bap.client.shared.services.LoggingService
import org.beckn.one.sandbox.bap.factories.ContextFactory
import org.beckn.one.sandbox.bap.factories.LoggingFactory
import org.beckn.protocol.schemas.ProtocolAckResponse
import org.beckn.protocol.schemas.ProtocolContext
import org.beckn.protocol.schemas.ResponseMessage
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
@RestController
class SearchController @Autowired constructor(
val searchService: ProtocolSearchService,
val contextFactory: ContextFactory,
val loggingService: LoggingService,
val loggingFactory: LoggingFactory
) {
val log: Logger = LoggerFactory.getLogger(this::class.java)
@PostMapping("/client/v1/search")
@ResponseBody
fun searchV1(@RequestBody request: SearchRequestDto): ResponseEntity<ProtocolAckResponse> {
val protocolContext =
contextFactory.create(transactionId = request.context.transactionId, action = ProtocolContext.Action.SEARCH)
val loggerRequest = loggingFactory.create(messageId = protocolContext.messageId,
transactionId = protocolContext.transactionId, contextTimestamp = protocolContext.timestamp.toString(),
action = protocolContext.action
)
loggingService.postLog(loggerRequest)
return searchService.search(protocolContext, request.message.criteria)
.fold(
{
log.error("Error during search. Error: {}", it)
val loggerRequest = loggingFactory.create(messageId = protocolContext.messageId, transactionId = protocolContext.transactionId, contextTimestamp = protocolContext.timestamp.toString(),
action = protocolContext.action, bppId = protocolContext.bppId, errorMessage = it.error().message, errorCode = it.error().code
)
loggingService.postLog(loggerRequest)
ResponseEntity
.status(it.status().value())
.body(ProtocolAckResponse(null, it.message(), it.error()))
},
{
log.info("Successfully initiated Search")
ResponseEntity.ok(it)
}
)
}
}
| 10
|
Kotlin
|
1
| 0
|
2b26c557bb9b3e32bfbbfcc941e9526532947d90
| 2,630
|
mobility-BAP
|
MIT License
|
backend/mandalore-express-infra/src/main/kotlin/com/beyondxscratch/mandaloreexpress/infrastructure/rest/resources/search/Price.kt
|
davidaparicio
| 761,161,576
| false
|
{"Kotlin": 198124, "JavaScript": 37294, "HTML": 1661, "CSS": 365}
|
package com.beyondxscratch.mandaloreexpress.infrastructure.rest.resources.search
import com.beyondxscratch.mandaloreexpress.domain.money.Currency
import com.beyondxscratch.mandaloreexpress.infrastructure.rest.resources.Resource
import java.math.BigDecimal
import com.beyondxscratch.mandaloreexpress.domain.search.spacetrain.fare.Price as DomainPrice
@Resource
data class Price(val amount : BigDecimal, val currency: Currency)
fun DomainPrice.toResource() = Price(this.amount.value, this.currency)
| 8
|
Kotlin
|
0
| 0
|
05dc41e2a5a5ea47ef5d688177631ffa9923fe11
| 500
|
model-mitosis
|
Apache License 2.0
|
app/src/main/kotlin/me/oikvpqya/apps/music/media3/AppMediaControllerImpl.kt
|
oikvpqya
| 835,137,893
| false
|
{"Kotlin": 288415, "HTML": 303}
|
package me.oikvpqya.apps.music.media3
import android.content.ComponentName
import android.content.Context
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.guava.asDeferred
import kotlinx.coroutines.launch
import me.oikvpqya.apps.music.data.AppDatabaseRepository
import me.oikvpqya.apps.music.data.AppMediaController
import me.oikvpqya.apps.music.data.AppMediaHandler
import me.oikvpqya.apps.music.data.AppMediaInfo
import me.oikvpqya.apps.music.data.PreferenceRepository
import me.oikvpqya.apps.music.media3.util.asInt
import me.oikvpqya.apps.music.media3.util.asMediaItem
import me.oikvpqya.apps.music.media3.util.asPlaybackRepeatMode
import me.oikvpqya.apps.music.media3.util.asPlaybackState
import me.oikvpqya.apps.music.media3.util.asTag
import me.oikvpqya.apps.music.model.Library
import me.oikvpqya.apps.music.model.PlaybackRepeatMode
import me.oikvpqya.apps.music.model.PlaybackState
import me.tatarka.inject.annotations.Inject
@Inject
class AppMediaControllerImpl(
private val context: Context,
private val databaseRepository: AppDatabaseRepository,
private val preferenceRepository: PreferenceRepository
) : AppMediaController {
private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
private val sessionToken by lazy {
SessionToken(context, ComponentName(context, AppMediaLibraryService::class.java))
}
private val mediaControllerDefer by lazy {
MediaController.Builder(
context,
sessionToken
).buildAsync().asDeferred()
}
private val _playbackSharedFlow = MutableSharedFlow<PlaybackState>(replay = 1)
private val playbackSharedFlow = _playbackSharedFlow.asSharedFlow()
private val _playWhenReadySharedFlow = MutableSharedFlow<Boolean>(replay = 1)
private val playWhenReadySharedFlow = _playWhenReadySharedFlow.asSharedFlow()
private val _mediaItemTransitionSharedFlow = MutableSharedFlow<Unit>(replay = 1)
private val mediaItemTransitionSharedFlow = _mediaItemTransitionSharedFlow.asSharedFlow()
private val _requestAppMediaInfoSharedFlow: MutableSharedFlow<Unit> = MutableSharedFlow(replay = 1)
private val requestAppMediaInfoSharedFlow = _requestAppMediaInfoSharedFlow.asSharedFlow()
private val listener by lazy {
object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
scope.launch {
_playbackSharedFlow.emit(playbackState.asPlaybackState())
}
}
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
scope.launch {
_playWhenReadySharedFlow.emit(playWhenReady)
}
}
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
scope.launch {
_mediaItemTransitionSharedFlow.emit(Unit)
}
}
}
}
private val mediaControllerFlow: Flow<MediaController> = flow {
emit(
mediaControllerDefer.await()
.also {
val playbackState = it.playbackState.asPlaybackState()
val playWhenReady = it.playWhenReady
val repeatMode = it.repeatMode.asPlaybackRepeatMode()
scope.launch {
_playbackSharedFlow.emit(playbackState)
_playWhenReadySharedFlow.emit(playWhenReady)
_mediaItemTransitionSharedFlow.emit(Unit)
_requestAppMediaInfoSharedFlow.emit(Unit)
}
}
.apply {
addListener(listener)
}
)
}
override val mediaInfoFlow: Flow<AppMediaInfo> = combine(
mediaControllerFlow,
combine(
playbackSharedFlow,
playWhenReadySharedFlow,
mediaItemTransitionSharedFlow,
requestAppMediaInfoSharedFlow
) { playback, _, _, _ ->
playback
},
databaseRepository.queueFlow,
preferenceRepository.queueIndexFlow,
combine(
preferenceRepository.repeatModeFlow,
preferenceRepository.shuffleModeFlow
) { repeatMode, shuffleMode ->
repeatMode to shuffleMode
}
) { mediaController, playback, queue, index, modePair ->
if (playback == PlaybackState.READY) {
with(mediaController) {
val tag = currentMediaItem?.asTag()
AppMediaInfo(
isPlaying = isPlaying,
song = if (tag != null) Library.Song.Default(tag = tag) else null,
position = currentPosition,
progress = currentPosition.toFloat() / duration,
state = playback,
queue = queue,
queueIndex = currentMediaItemIndex,
repeatMode = modePair.first,
shuffleMode = modePair.second,
volume = volume,
)
.also {
if (it.isPlaying) {
scope.launch {
delay(1000L)
_requestAppMediaInfoSharedFlow.emit(Unit)
}
}
}
}
} else {
AppMediaInfo(
isPlaying = false,
song = null,
position = 0L,
progress = 0f,
state = playback,
queue = queue,
queueIndex = index,
repeatMode = modePair.first,
shuffleMode = modePair.second,
volume = 1f,
)
}
}
override val mediaHandlerFlow: Flow<AppMediaHandler> = mediaControllerFlow.map { mediaController ->
object : AppMediaHandler {
override fun playOrPause() {
scope.launch {
mediaController.repeatMode
with(mediaController) {
if (!isConnected) return@launch
if (isPlaying) pause() else play()
}
}
}
override fun playSongs(items: List<Library.Song>, index: Int, position: Long) {
if (items.isEmpty()) return
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
setMediaItems(items.map { it.tag.asMediaItem() }, index, position)
prepare()
play()
// setCurrentQueue(items)
}
}
}
override fun playAt(index: Int, position: Long) {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
if (currentMediaItem == null) {
preferenceRepository.updateQueueIndex(index)
} else {
seekTo(index, position)
}
}
}
}
override fun playAt(position: Long) {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
if (isCurrentMediaItemSeekable) {
seekTo(position)
}
}
}
}
override fun like(item: Library.Song?) {
scope.launch {
item?.tag?.mediaId?.let { databaseRepository.setFavorite(listOf(it)) }
}
}
override fun unlike(item: Library.Song?) {
scope.launch {
item?.tag?.mediaId?.let { databaseRepository.deleteFavorite(listOf(it)) }
}
}
override fun isFavoriteSharedFlow(item: Library.Song?): SharedFlow<Boolean> {
val flow = item?.tag?.mediaId?.let { databaseRepository.isFavoriteFlow(it) }
return (flow ?: flow {})
.shareIn(
scope = scope,
started = SharingStarted.WhileSubscribed(),
replay = 1
)
}
override fun disableRepeatMode() {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
repeatMode = PlaybackRepeatMode.OFF.asInt()
}
}
}
override fun enableRepeatOneMode() {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
repeatMode = PlaybackRepeatMode.ONE.asInt()
}
}
}
override fun enableRepeatAllMode() {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
repeatMode = PlaybackRepeatMode.ALL.asInt()
}
}
}
override fun enableShuffleMode() {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
shuffleModeEnabled = true
}
}
}
override fun disableShuffleMode() {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
shuffleModeEnabled = false
}
}
}
override fun seekToPrevious() {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
seekToPrevious()
}
}
}
override fun seekToNext() {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
seekToNextMediaItem()
}
}
}
override fun setVolume(value: Float) {
scope.launch {
with(mediaController) {
if (!isConnected) return@launch
volume = value.coerceIn(0f..1f)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
eb46d4bd66e9e8f079b886dc15163d9753636ebf
| 11,560
|
nextro
|
Apache License 2.0
|
waypoints-api/src/main/kotlin/de/md5lukas/waypoints/api/BeaconColor.kt
|
Sytm
| 211,378,928
| false
| null |
package de.md5lukas.waypoints.api
import org.bukkit.Material
/**
* This class represents all possible beacon beam colors that can be created with one colored glass block
*/
enum class BeaconColor(val material: Material) {
/**
* Beacon is covered with [Material.GLASS]
*/
CLEAR(Material.GLASS),
/**
* Beacon is covered with [Material.LIGHT_GRAY_STAINED_GLASS]
*/
LIGHT_GRAY(Material.LIGHT_GRAY_STAINED_GLASS),
/**
* Beacon is covered with [Material.GRAY_STAINED_GLASS]
*/
GRAY(Material.GRAY_STAINED_GLASS),
/**
* Beacon is covered with [Material.PINK_STAINED_GLASS]
*/
PINK(Material.PINK_STAINED_GLASS),
/**
* Beacon is covered with [Material.LIME_STAINED_GLASS]
*/
LIME(Material.LIME_STAINED_GLASS),
/**
* Beacon is covered with [Material.YELLOW_STAINED_GLASS]
*/
YELLOW(Material.YELLOW_STAINED_GLASS),
/**
* Beacon is covered with [Material.LIGHT_BLUE_STAINED_GLASS]
*/
LIGHT_BLUE(Material.LIGHT_BLUE_STAINED_GLASS),
/**
* Beacon is covered with [Material.MAGENTA_STAINED_GLASS]
*/
MAGENTA(Material.MAGENTA_STAINED_GLASS),
/**
* Beacon is covered with [Material.ORANGE_STAINED_GLASS]
*/
ORANGE(Material.ORANGE_STAINED_GLASS),
/**
* Beacon is covered with [Material.WHITE_STAINED_GLASS]
*/
WHITE(Material.WHITE_STAINED_GLASS),
/**
* Beacon is covered with [Material.BLACK_STAINED_GLASS]
*/
BLACK(Material.BLACK_STAINED_GLASS),
/**
* Beacon is covered with [Material.RED_STAINED_GLASS]
*/
RED(Material.RED_STAINED_GLASS),
/**
* Beacon is covered with [Material.GREEN_STAINED_GLASS]
*/
GREEN(Material.GREEN_STAINED_GLASS),
/**
* Beacon is covered with [Material.BROWN_STAINED_GLASS]
*/
BROWN(Material.BROWN_STAINED_GLASS),
/**
* Beacon is covered with [Material.BLUE_STAINED_GLASS]
*/
BLUE(Material.BLUE_STAINED_GLASS),
/**
* Beacon is covered with [Material.CYAN_STAINED_GLASS]
*/
CYAN(Material.CYAN_STAINED_GLASS),
/**
* Beacon is covered with [Material.PURPLE_STAINED_GLASS]
*/
PURPLE(Material.PURPLE_STAINED_GLASS),
;
val blockData by lazy {
material.createBlockData()
}
}
| 3
|
Kotlin
|
3
| 12
|
9a69b00457a7308507dea14a54199abb181a6b90
| 2,322
|
waypoints
|
MIT License
|
src/main/java/me/han/muffin/client/command/commands/ConnectCommand.kt
|
SmallFishDD
| 425,272,585
| false
|
{"Kotlin": 1725682, "Java": 943392, "GLSL": 15937}
|
package me.han.muffin.client.command.commands
import me.han.muffin.client.command.Argument
import me.han.muffin.client.command.Command
import me.han.muffin.client.core.Globals
import net.minecraft.client.gui.GuiMainMenu
import net.minecraft.client.gui.GuiMultiplayer
import net.minecraft.client.multiplayer.GuiConnecting
import net.minecraft.client.multiplayer.ServerData
object ConnectCommand: Command(arrayOf("connect", "c"), Argument("ip")) {
override fun dispatch(): String {
val serverIPArgument = getArgument("ip")?.value ?: return "Invalid values."
val serverData = ServerData("", serverIPArgument, false)
Globals.mc.world.sendQuittingDisconnectingPacket()
Globals.mc.loadWorld(null)
Globals.mc.displayGuiScreen(GuiConnecting(GuiMultiplayer(GuiMainMenu()), Globals.mc, serverData))
return "Connecting to ${serverData.serverIP}..."
}
}
| 1
|
Kotlin
|
2
| 2
|
13235eada9edd9ccca039dea4d3a59cc7a930830
| 902
|
muffin-0.10.4-src-leaked
|
MIT License
|
ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/importordering/ImportOrderingRuleIdeaTest.kt
|
pinterest
| 64,293,719
| false
|
{"Kotlin": 3159822, "Shell": 4162, "Batchfile": 518, "Python": 103}
|
package com.pinterest.ktlint.ruleset.standard.importordering
import com.pinterest.ktlint.core.api.FeatureInAlphaState
import com.pinterest.ktlint.ruleset.standard.ImportOrderingRule
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThat
import com.pinterest.ktlint.test.LintViolation
import org.junit.jupiter.api.Test
@OptIn(FeatureInAlphaState::class)
class ImportOrderingRuleIdeaTest {
private val importOrderingRuleAssertThat = ImportOrderingRule().assertThat()
@Test
fun `Given some imports which are sorted incorrectly then do return lint errors`() {
val code =
"""
import android.app.Activity
import android.content.Context as Ctx
import androidx.fragment.app.Fragment as F
import android.view.View
import android.view.ViewGroup
import java.util.List
import javax.net.ssl.SSLHandshakeException
import kotlin.io.Closeable
import kotlin.concurrent.Thread
import kotlinx.coroutines.CoroutineDispatcher
import ru.example.a
""".trimIndent()
val formattedCode =
"""
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import kotlinx.coroutines.CoroutineDispatcher
import ru.example.a
import java.util.List
import javax.net.ssl.SSLHandshakeException
import kotlin.concurrent.Thread
import kotlin.io.Closeable
import android.content.Context as Ctx
import androidx.fragment.app.Fragment as F
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)
.hasLintViolation(
1,
1,
"Imports must be ordered in lexicographic order without any empty lines in-between with \"java\", \"javax\", \"kotlin\" and aliases in the end"
)
.isFormattedAs(formattedCode)
}
@Test
fun `Given imports which are sorted correctly then do not return lint errors`() {
val code =
"""
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import kotlinx.coroutines.CoroutineDispatcher
import ru.example.a
import java.util.List
import javax.net.ssl.SSLHandshakeException
import kotlin.concurrent.Thread
import kotlin.io.Closeable
import android.content.Context as Ctx
import androidx.fragment.app.Fragment as F
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)
.hasNoLintViolations()
}
@Test
fun `Given some duplicate class imports unless they have distinct aliases`() {
val code =
"""
import android.view.View
import android.view.ViewGroup
import android.view.View
import android.content.Context as Ctx1
import android.content.Context as Ctx2
import android.content.Context as Ctx1
""".trimIndent()
val formattedCode =
"""
import android.view.View
import android.view.ViewGroup
import android.content.Context as Ctx1
import android.content.Context as Ctx2
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)
.hasLintViolations(
LintViolation(3, 1, "Duplicate 'import android.view.View' found"),
LintViolation(6, 1, "Duplicate 'import android.content.Context as Ctx1' found")
).isFormattedAs(formattedCode)
}
@Test
fun `Given some imports in correct order and containing blank lines then do return a lint error`() {
val code =
"""
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import java.util.List
""".trimIndent()
val formattedCode =
"""
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import java.util.List
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)
.hasLintViolation(
1,
1,
"Imports must be ordered in lexicographic order without any empty lines in-between with \"java\", \"javax\", \"kotlin\" and aliases in the end"
)
.isFormattedAs(formattedCode)
}
@Test
fun `Given some imports having an EOL comment but in incorrect order then retain the comment and do return a lint error`() {
val code =
"""
import android.app.Activity
import android.content.Context as Ctx
import androidx.fragment.app.Fragment as F // comment 3
import android.view.ViewGroup
import android.view.View // comment 1
import java.util.List // comment 2
import javax.net.ssl.SSLHandshakeException
import kotlin.io.Closeable
import kotlin.concurrent.Thread
import kotlinx.coroutines.CoroutineDispatcher
import ru.example.a
""".trimIndent()
val formattedCode =
"""
import android.app.Activity
import android.view.View // comment 1
import android.view.ViewGroup
import kotlinx.coroutines.CoroutineDispatcher
import ru.example.a
import java.util.List // comment 2
import javax.net.ssl.SSLHandshakeException
import kotlin.concurrent.Thread
import kotlin.io.Closeable
import android.content.Context as Ctx
import androidx.fragment.app.Fragment as F // comment 3
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)
.hasLintViolation(
1,
1,
"Imports must be ordered in lexicographic order without any empty lines in-between with \"java\", \"javax\", \"kotlin\" and aliases in the end"
)
.isFormattedAs(formattedCode)
}
@Test
fun `Given some imports containing 'as' in the path then do not remove them`() {
val code =
"""
import assertk.all
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.doesNotContain
import assertk.assertions.isEqualTo
import assertk.assertions.isFailure
import assertk.assertions.isInstanceOf
import assertk.assertions.isNotNull
import assertk.assertions.isNull
import assertk.assertions.message
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.google.inject.multibindings.MapBinder
import com.google.inject.name.Names
import com.trib3.json.modules.ObjectMapperModule
import dev.misfitlabs.kotlinguice4.KotlinModule
import dev.misfitlabs.kotlinguice4.typeLiteral
import org.testng.annotations.Guice
import org.testng.annotations.Test
import org.threeten.extra.YearQuarter
import java.time.LocalDate
import javax.inject.Inject
import kotlin.reflect.KClass
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)
.hasNoLintViolations()
}
@Test
fun `Given some imports with aliases`() {
val code =
"""
import android.view.ViewGroup.LayoutParams.MATCH_PARENT as MATCH
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT as WRAP
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)
.hasNoLintViolations()
}
@Test
fun `Issue 1243 - Format should not remove imports when having a distinct alias`() {
val code =
"""
import foo.Bar as Bar1
import foo.Bar as Bar2
import foo.Bar as Bar2
val bar1 = Bar1()
val bar2 = Bar2()
""".trimIndent()
val formattedCode =
"""
import foo.Bar as Bar1
import foo.Bar as Bar2
val bar1 = Bar1()
val bar2 = Bar2()
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(IDEA_DEFAULT_IMPORT_ORDERING)
.hasLintViolation(3, 1, "Duplicate 'import foo.Bar as Bar2' found")
.isFormattedAs(formattedCode)
}
private companion object {
val IDEA_DEFAULT_IMPORT_ORDERING = ImportOrderingRule.ideaImportsLayoutProperty to "*,java.**,javax.**,kotlin.**,^"
}
}
| 64
|
Kotlin
|
509
| 6,205
|
80c4d5d822d47bb7077a874ebb9105097f2eb1c2
| 9,585
|
ktlint
|
MIT License
|
shared/core/utils/src/main/kotlin/ru/hh/plugins/extensions/psi/PsiClassExt.kt
|
XiaMuYao
| 322,474,012
| true
|
{"Kotlin": 421608, "Shell": 3230}
|
package ru.hh.plugins.extensions.psi
import com.intellij.psi.PsiClass
import com.intellij.psi.util.InheritanceUtil
fun PsiClass.isInheritedFrom(fullyQualifiedClassName: String): Boolean {
return InheritanceUtil.isInheritor(this, fullyQualifiedClassName)
}
| 0
| null |
0
| 1
|
a2328efbcb05c01e644f9eb2cd59848d7ba9f6e6
| 262
|
android-multimodule-plugin
|
MIT License
|
app/src/main/java/go/deyu/stupidgame2/presentation/theme/Color.kt
|
DeyuGoGo
| 618,735,859
| false
| null |
package go.deyu.stupidgame2.presentation.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Teal200 = Color(0xFF03DAC5)
val Teal700 = Color(0xFF018786)
val Amber200 = Color(0xFFFFE082)
val Amber700 = Color(0xFFFFA000)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
| 0
|
Kotlin
|
0
| 0
|
a9856f73ffe873f3afadf78d90e4d442b4319534
| 422
|
StupidGame2
|
Apache License 2.0
|
app/src/main/java/ru/tech/imageresizershrinker/data/image/filters/BilaterialBlurFilter.kt
|
T8RIN
| 478,710,402
| false
| null |
package ru.tech.imageresizershrinker.data.image.filters
import android.content.Context
import android.graphics.Bitmap
import jp.co.cyberagent.android.gpuimage.filter.GPUImageBilateralBlurFilter
import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter
import ru.tech.imageresizershrinker.domain.image.filters.Filter
class BilaterialBlurFilter(
private val context: Context,
override val value: Float = -8f,
) : GPUFilterTransformation(context), Filter.BilaterialBlur<Bitmap> {
override val cacheKey: String
get() = (value to context).hashCode().toString()
override fun createFilter(): GPUImageFilter = GPUImageBilateralBlurFilter(-value)
}
| 20
| null |
77
| 979
|
7d164a02c463afede47c785f8b182c954abfcde9
| 671
|
ImageToolbox
|
Apache License 2.0
|
libraries/csm.cloud.common.web/src/main/kotlin/com/bosch/pt/csm/cloud/common/facade/rest/LinkUtils.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.facade.rest
import java.util.regex.Pattern
import org.springframework.hateoas.Link
import org.springframework.util.Assert
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import org.springframework.web.servlet.support.ServletUriComponentsBuilder
import org.springframework.web.util.UriComponents
import org.springframework.web.util.UriComponentsBuilder
object LinkUtils {
private val pattern = Pattern.compile(".*/v([1-9][0-9]*)/.*")
/**
* Creates a [UriComponentsBuilder] with given path segments for the current servlet mapping
* including the given API version.
*
* @param apiVersion the desired API version
* @param segments path segments
* @return uri components builder
*/
@JvmStatic
fun linkTemplateWithPathSegments(
apiVersion: Int,
vararg segments: String?
): UriComponentsBuilder =
ServletUriComponentsBuilder.fromCurrentServletMapping()
.pathSegment("v$apiVersion")
.pathSegment(*segments)
/**
* Creates a [UriComponentsBuilder] with given path segments for the current servlet mapping
* including the API version from the current request.
*
* @param segments path segments
* @return uri components builder
*/
@JvmStatic
fun linkTemplateWithPathSegments(vararg segments: String?): UriComponentsBuilder =
linkTemplateWithPathSegments(getCurrentApiVersion(), *segments)
/**
* Creates a [UriComponentsBuilder] with given path segments for the current servlet mapping.
*
* @param segments path segments
* @return uri components builder
*/
@JvmStatic
fun linkTemplateWithPathSegmentsUnversioned(vararg segments: String?): UriComponentsBuilder =
ServletUriComponentsBuilder.fromCurrentServletMapping().pathSegment(*segments)
/**
* Creates a [Link] from [UriComponents] representing the links URL.
*
* @param components URI components
* @param rel link relation
* @return new [Link]
*/
@JvmStatic
fun linkFromUriComponents(components: UriComponents, rel: String): Link =
Link.of(components.toUriString(), rel)
@JvmStatic fun getCurrentApiVersionPrefix(): String = "/v" + getCurrentApiVersion()
@JvmStatic
fun getCurrentApiVersion(): Int {
val attrs = RequestContextHolder.getRequestAttributes()
Assert.state(attrs is ServletRequestAttributes, "No current ServletRequestAttributes")
val request = (attrs as ServletRequestAttributes).request
val version = extractApiVersion(request.requestURI)
return if (version > 0) {
version
} else {
error("No version information found in url path")
}
}
@JvmStatic
fun extractApiVersion(requestUri: String?): Int {
val matcher = pattern.matcher(requestUri)
return if (matcher.find()) {
matcher.group(1).toInt()
} else -1
}
}
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 3,154
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
app/src/main/java/com/github/kazukinr/android/sample/ui/exo_player_sample/ExoPlayerSampleFragment.kt
|
kazukinr
| 185,600,625
| false
|
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 4, "XML": 27, "Kotlin": 70}
|
package com.github.kazukinr.android.sample.ui.exo_player_sample
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import com.github.kazukinr.android.sample.R
import com.github.kazukinr.android.sample.databinding.ExoPlayerSampleFragmentBinding
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.video.MediaCodecVideoRenderer
import dagger.android.support.DaggerFragment
class ExoPlayerSampleFragment : DaggerFragment() {
private var binding: ExoPlayerSampleFragmentBinding? = null
private var player: ExoPlayer? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding?.let {
return it.root
}
return DataBindingUtil.inflate<ExoPlayerSampleFragmentBinding>(
inflater,
R.layout.exo_player_sample_fragment,
container,
false
).also {
binding = it
}.root
}
override fun onResume() {
super.onResume()
player = ExoPlayerFactory.newSimpleInstance(requireContext())
binding?.player?.player = player
val mediaSource = ProgressiveMediaSource.Factory(
DefaultDataSourceFactory(requireContext(), "user-agent"),
DefaultExtractorsFactory()
).createMediaSource(Uri.parse("file:///android_asset/movie_sample.mp4"))
player?.prepare(mediaSource)
player?.playWhenReady = true
}
override fun onPause() {
super.onPause()
binding?.player?.player = null
player?.release()
player = null
}
}
| 1
| null |
1
| 1
|
f0254984745a260e53ace6505fc5ceb6edfc8192
| 2,164
|
android-project-sample
|
Apache License 2.0
|
app/src/main/java/xyz/felixb/starwars/di/SwapiModule.kt
|
FlxB2
| 707,994,622
| false
|
{"Kotlin": 52364, "Java": 176}
|
package xyz.felixb.starwars.di
import android.util.Log
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.swapi.client.apis.DefaultApi
import dev.swapi.client.infrastructure.ApiClient
import javax.inject.Singleton
/**
* Module to provide the Swapi API via Hilt.
*/
@InstallIn(SingletonComponent::class)
@Module
class SwapiModule {
@Singleton
@Provides
fun provideSwapiApi(): DefaultApi {
/**
* In a real application authentication, caching etc would be
* handled in a separate file which creates the client.
*/
return ApiClient()
.setLogger { m -> Log.i("API", m) }
.createService(DefaultApi::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
417bb473f63bd76407105b99e53b1632f6d1bcfd
| 778
|
AndroidStarWarsSample
|
Apache License 2.0
|
core/src/main/java/com/albro/storyapp/core/domain/models/Story.kt
|
rifkyhaekal
| 640,716,208
| false
| null |
package com.albro.storyapp.core.domain.models
data class Story(
val id: String,
val name: String,
val description: String,
val photoUrl: String,
)
| 0
|
Kotlin
|
0
| 1
|
606a83047bc734d616615d70bf5b7bf9026a4be5
| 164
|
StoryApp
|
MIT License
|
src/main/kotlin/xyz/attacktive/plugins/Routing.kt
|
Attacktive
| 867,967,479
| false
|
{"Kotlin": 2850}
|
package xyz.attacktive.plugins
import io.ktor.http.ContentType
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import io.ktor.server.webjars.Webjars
fun Application.configureRouting() {
install(Webjars) {
path = "/webjars" // defaults to /webjars
}
routing {
get("/") {
call.respondText("Hello World!")
}
get("/webjars") {
call.respondText("<script src='/webjars/jquery/jquery.js'></script>", ContentType.Text.Html)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
774a0e7ac86eb07cc62c5342a53eb41334354e92
| 600
|
ktor-sample
|
MIT License
|
plugins/kotlin/completion/testData/basic/java/syntheticExtensions/ShowGetSetOnSecondCompletion.kt
|
ingokegel
| 72,937,917
| false
| null |
fun foo(thread: Thread) {
thread.<caret>
}
// IGNORE_K2
// INVOCATION_COUNT: 2
// EXIST: { lookupString: "priority", itemText: "priority", tailText: " (from getPriority()/setPriority())", typeText: "Int", icon: "org/jetbrains/kotlin/idea/icons/field_variable.svg"}
// EXIST: getPriority
// EXIST: setPriority
| 284
| null |
5162
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 314
|
intellij-community
|
Apache License 2.0
|
compiler/testData/diagnostics/tests/syntheticExtensions/samAdapters/NoNamedArgsAllowed.fir.kt
|
android
| 263,405,600
| false
| null |
// !WITH_NEW_INFERENCE
// FILE: KotlinFile.kt
fun foo(javaClass: JavaClass) {
javaClass.doSomething(p = 1) {
bar()
}
}
fun bar(){}
// FILE: JavaClass.java
public class JavaClass {
public void doSomething(int p, Runnable runnable) { runnable.run(); }
}
| 0
| null |
37
| 316
|
74126637a097f5e6b099a7b7a4263468ecfda144
| 273
|
kotlin
|
Apache License 2.0
|
telegram-bot/src/jvmTest/kotlin/eu/vendeli/api/botactions/SetMyActionsTest.kt
|
vendelieu
| 496,567,172
| false
| null |
package eu.vendeli.api.botactions
import BotTestContext
import eu.vendeli.tgbot.api.botactions.deleteMyCommands
import eu.vendeli.tgbot.api.botactions.getMyCommands
import eu.vendeli.tgbot.api.botactions.getMyDefaultAdministratorRights
import eu.vendeli.tgbot.api.botactions.getMyDescription
import eu.vendeli.tgbot.api.botactions.getMyName
import eu.vendeli.tgbot.api.botactions.getMyShortDescription
import eu.vendeli.tgbot.api.botactions.setMyCommands
import eu.vendeli.tgbot.api.botactions.setMyDefaultAdministratorRights
import eu.vendeli.tgbot.api.botactions.setMyDescription
import eu.vendeli.tgbot.api.botactions.setMyName
import eu.vendeli.tgbot.api.botactions.setMyShortDescription
import eu.vendeli.tgbot.types.bot.BotCommand
import eu.vendeli.tgbot.types.chat.ChatAdministratorRights
import eu.vendeli.tgbot.types.internal.onFailure
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.collections.shouldContain
import io.kotest.matchers.collections.shouldNotBeEmpty
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
class SetMyActionsTest : BotTestContext() {
@Test
suspend fun `set my default administrator rights method testing`() {
setMyDefaultAdministratorRights(
ChatAdministratorRights(
isAnonymous = true,
canManageChat = false,
canDeleteMessages = false,
canRestrictMembers = false,
canPromoteMembers = false,
canChangeInfo = false,
canInviteUsers = false,
canPostMessages = false,
canEditMessages = false,
canPinMessages = false,
canManageTopics = false,
canManageVideoChats = false,
canPostStories = false,
canEditStories = false,
canDeleteStories = false,
),
).send(bot)
val result = getMyDefaultAdministratorRights().sendReq().shouldSuccess()
with(result) {
isAnonymous.shouldBeTrue()
}
setMyDefaultAdministratorRights(
ChatAdministratorRights(
isAnonymous = false,
canManageChat = false,
canDeleteMessages = false,
canRestrictMembers = false,
canPromoteMembers = false,
canChangeInfo = false,
canInviteUsers = false,
canPostMessages = false,
canEditMessages = false,
canPinMessages = false,
canManageTopics = false,
canPostStories = false,
canEditStories = false,
canDeleteStories = false,
canManageVideoChats = false,
),
).send(bot)
}
@Test
suspend fun `set description method testing`() {
setMyDescription("test").send(bot)
val result = getMyDescription().sendReq().shouldSuccess()
result.shouldNotBeNull()
result.description shouldBe "test"
setMyDescription().send(bot)
}
@Test
suspend fun `set short description method testing`() {
setMyShortDescription("test").send(bot)
val result = getMyShortDescription().sendReq().shouldSuccess()
result.shouldNotBeNull()
result.shortDescription shouldBe "test"
setMyShortDescription().send(bot)
}
@Test
suspend fun `set my commands method testing`() {
setMyCommands {
botCommand("test", "testD")
"test2" description "testC"
}.send(bot)
val result = getMyCommands().sendReq().shouldSuccess()
result.shouldNotBeNull()
result.shouldNotBeEmpty()
result shouldContain BotCommand("test", "testD")
deleteMyCommands().send(bot)
}
@Test
suspend fun `delete my commands method testing`() {
// setMyCommands("en", BotCommandScope.AllPrivateChats) {
// "test" description "testD"
// }.send(bot)
// getMyCommands("en", BotCommandScope.AllPrivateChats).sendReq()
// .await().getOrNull().shouldNotBeNull().shouldNotBeEmpty()
val result = deleteMyCommands().sendReq().shouldSuccess()
result.shouldNotBeNull()
result.shouldBeTrue()
}
@Test
suspend fun `set my name method testing`() {
val request = setMyName("testbot2").sendReq()
request.onFailure {
if (it.errorCode == 429) return // delay due to limit
}
val result = request.shouldSuccess()
result.shouldNotBeNull()
result.shouldBeTrue()
getMyName()
.sendReq()
.shouldSuccess()
.name shouldBe "testbot2"
setMyName("testbot").send(bot)
}
}
| 6
| null |
14
| 176
|
41d50ea8fd014cb31b61eb5c2f4a4bebf4736b45
| 4,826
|
telegram-bot
|
Apache License 2.0
|
app/src/main/java/com/seven_sheesh/greventure/data/repository/BubblePhotoRepositoryImpl.kt
|
ahargunyllib
| 846,841,295
| false
|
{"Kotlin": 453189}
|
package com.seven_sheesh.greventure.data.repository
import android.app.Application
import android.content.ContentResolver
import android.net.Uri
import android.util.Log
import com.seven_sheesh.greventure.domain.model.BubblePhoto
import com.seven_sheesh.greventure.domain.repository.BubblePhotoRepository
import io.github.jan.supabase.postgrest.Postgrest
import io.github.jan.supabase.storage.Storage
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.InputStream
import javax.inject.Inject
class BubblePhotoRepositoryImpl @Inject constructor(
private val supabaseClientProvider: Postgrest,
private val supabaseStorage: Storage,
private val application: Application
) : BubblePhotoRepository {
private val TAG = "BubblePhotoRepositoryImpl"
override fun getAllBubblePhotos(): Flow<Pair<String, List<BubblePhoto>>> {
return flow {
Log.d(TAG, "getAllBubblePhotos: Loading...")
emit(Pair("Loading...", emptyList()))
try {
val bubblePhotosResponse = withContext(Dispatchers.IO) {
supabaseClientProvider.from("bubble_photos").select().decodeList<BubblePhoto>()
}
val bubblePhotos = bubblePhotosResponse ?: emptyList()
Log.d(TAG, "getAllBubblePhotos: Successfully fetched bubble photos")
emit(Pair("Successfully fetched bubble photos", bubblePhotos))
} catch (e: Exception) {
Log.e(TAG, "getAllBubblePhotos: An error occurred: ${e.message}", e)
emit(Pair("An error occurred: ${e.message}", emptyList()))
}
}
}
override fun getBubblePhotoById(photoId: Int): Flow<Pair<String, BubblePhoto?>> {
return flow {
Log.d(TAG, "getBubblePhotoById: Loading...")
emit(Pair("Loading...", null))
try {
val bubblePhotoResponse = withContext(Dispatchers.IO) {
supabaseClientProvider.from("bubble_photos")
.select {
filter {
eq("id", photoId)
}
}
.decodeSingleOrNull<BubblePhoto>()
}
Log.d(TAG, "getBubblePhotoById: Bubble photo found")
emit(Pair("Bubble photo found", bubblePhotoResponse))
} catch (e: Exception) {
Log.e(TAG, "getBubblePhotoById: An error occurred: ${e.message}", e)
emit(Pair("An error occurred: ${e.message}", null))
}
}
}
override fun getBubblePhotosByBubbleId(bubbleId: String): Flow<Pair<String, List<BubblePhoto>>> {
return flow {
Log.d(TAG, "getBubblePhotosByBubbleId: Loading...")
emit(Pair("Loading...", emptyList()))
try {
val bubblePhotosResponse = withContext(Dispatchers.IO) {
supabaseClientProvider.from("bubble_photos")
.select {
filter {
eq("bubble_id", bubbleId)
}
}
.decodeList<BubblePhoto>()
}
val bubblePhotos = bubblePhotosResponse ?: emptyList()
Log.d(TAG, "getBubblePhotosByBubbleId: Successfully fetched bubble photos")
emit(Pair("Successfully fetched bubble photos", bubblePhotos))
} catch (e: Exception) {
Log.e(TAG, "getBubblePhotosByBubbleId: An error occurred: ${e.message}", e)
emit(Pair("An error occurred: ${e.message}", emptyList()))
}
}
}
override fun upsertBubblePhoto(bubblePhoto: BubblePhoto): Flow<String> {
return flow {
emit("Starting photo upload...")
Log.d(TAG, "upsertBubblePhoto: Uploading photo...")
val contentResolver: ContentResolver = application.contentResolver
val uri = Uri.parse(bubblePhoto.url)
val inputStream: InputStream? = contentResolver.openInputStream(uri)
if (inputStream == null) {
Log.e(TAG, "upsertBubblePhoto: Unable to open InputStream from Uri")
emit("Unable to open InputStream from Uri")
return@flow
}
try {
val imagePath = "bubble_photos/${uri.lastPathSegment ?: "unknown_image"}"
val uploadResponse = supabaseStorage.from("bubble").upload(
path = imagePath,
data = inputStream.readBytes(),
upsert = true
)
Log.d(TAG, "upsertBubblePhoto: Upload response: $uploadResponse")
val publicUrl = supabaseStorage.from("bubble").publicUrl(imagePath)
Log.d(TAG, "upsertBubblePhoto: Public URL: $publicUrl")
val updatedBubblePhoto = bubblePhoto.copy(url = publicUrl)
val updateResponse = withContext(Dispatchers.IO) {
supabaseClientProvider.from("bubble_photos").upsert(updatedBubblePhoto)
}
Log.d(TAG, "upsertBubblePhoto: Update response: $updateResponse")
Log.d(TAG, "upsertBubblePhoto: Bubble photo successfully inserted/updated")
emit("Bubble photo successfully inserted/updated")
} catch (e: Exception) {
Log.e(TAG, "upsertBubblePhoto: An error occurred: ${e.message}", e)
emit("An error occurred: ${e.message}")
} finally {
inputStream.close()
}
}
}
override fun deleteBubblePhoto(photoId: Int): Flow<String> {
return flow {
Log.d(TAG, "deleteBubblePhoto: Processing...")
emit("Processing...")
try {
val response = withContext(Dispatchers.IO) {
supabaseClientProvider.from("bubble_photos")
.delete {
filter {
eq("id", photoId)
}
}
}
Log.d(TAG, "deleteBubblePhoto: Bubble photo successfully deleted")
emit("Bubble photo successfully deleted")
} catch (e: Exception) {
Log.e(TAG, "deleteBubblePhoto: An error occurred: ${e.message}", e)
emit("An error occurred: ${e.message}")
}
}
}
}
| 0
|
Kotlin
|
1
| 0
|
8735831666609ec8f4e017c5120dbe6fbe241916
| 6,697
|
Greventure
|
MIT License
|
app/src/main/java/com/fredporciuncula/daggerjourney/business/BusinessUtil.kt
|
tfcporciuncula
| 178,914,410
| false
| null |
package com.fredporciuncula.daggerjourney.business
import android.content.Context
import android.content.SharedPreferences
import com.fredporciuncula.daggerjourney.R
import dagger.Reusable
import timber.log.Timber
import javax.inject.Inject
@Reusable
class BusinessUtil @Inject constructor(
private val context: Context,
private val sharedPreferences: SharedPreferences
) {
fun log(message: String) {
Timber.d(context.getString(R.string.log_template, message))
storeLastLogMessage(message)
}
private fun storeLastLogMessage(message: String) =
sharedPreferences
.edit()
.putString(context.getString(R.string.log_preference_key), message)
.apply()
}
| 0
|
Kotlin
|
4
| 99
|
555b0258f9fd0f4b674a8fc91c3a92d3d61ec032
| 692
|
dagger-journey
|
Apache License 2.0
|
app/src/main/java/com/mikhailgrigorev/simple_password/common/utils/Constants.kt
|
grigorevmp
| 268,231,866
| false
|
{"Kotlin": 276476, "AIDL": 8443}
|
package com.mikhailgrigorev.simple_password.common.utils
const val authorTelegramLink = "https://t.me/grigorevmp"
const val authorGitHubLink = "https://github.com/grigorevmp"
const val Dg_WPX_GitHubLink = "https://github.com/WaifuPX-DG"
const val authorBaseMail = "<EMAIL>"
| 2
|
Kotlin
|
2
| 33
|
20ab0beb627cf8f8fe11af1eb1337f45614651ea
| 274
|
Simple_Passwords_QuickPass
|
MIT License
|
library/src/main/kotlin/de/eternalwings/focus/storage/data/WithOperation.kt
|
kumpelblase2
| 259,880,502
| false
| null |
package de.eternalwings.focus.storage.data
interface WithOperation {
val operation: Operation
}
| 1
|
Kotlin
|
0
| 5
|
80ed810a66a954739219ac73af3d1e626f55c58c
| 101
|
focus
|
Apache License 2.0
|
core/src/main/java/com/hxw/core/adapter/SimpleRecyclerAdapter.kt
|
huxiaowei008
| 135,882,287
| false
|
{"Kotlin": 170604, "Java": 119250}
|
package com.hxw.core.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
/**
* RecyclerView的Adapter简单封装
*
* @author hxw
* @date 2019/1/28
*/
class SimpleRecyclerAdapter<T>(@param:LayoutRes private val layoutId: Int) : RecyclerView.Adapter<SimpleViewHolder>() {
private var mData: List<T>? = null
private var initView: ((view: View, data: T, position: Int) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder {
val v = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
return SimpleViewHolder(v)
}
override fun onBindViewHolder(holder: SimpleViewHolder, position: Int) {
initView?.invoke(holder.itemView, mData!![position], position)
}
override fun getItemCount(): Int {
return if (mData == null) 0 else mData!!.size
}
fun setInitView(initView: (view: View, data: T, position: Int) -> Unit): SimpleRecyclerAdapter<T> {
this.initView = initView
return this
}
fun setData(data: List<T>?): SimpleRecyclerAdapter<T> {
this.mData = data
return this
}
fun getData(): List<T>? {
return mData
}
}
| 0
|
Kotlin
|
0
| 2
|
a5785cfbfd74e6c7399514a0bb2730083ddf3e4a
| 1,332
|
WanAndroid
|
Apache License 2.0
|
SKIE/skie-gradle/plugin-api/src/main/kotlin/co/touchlab/skie/plugin/util/BooleanProperty.takeIf.kt
|
touchlab
| 685,579,240
| false
|
{"Kotlin": 1644009, "Swift": 6029, "Shell": 1040}
|
package co.touchlab.skie.plugin.util
import org.gradle.api.provider.Property
internal infix fun <T> T.takeIf(property: Property<Boolean>): T? =
this.takeIf { property.orNull ?: false }
| 9
|
Kotlin
|
8
| 735
|
b96044d4dec91e4b85c5b310226c6f56e3bfa2b5
| 191
|
SKIE
|
Apache License 2.0
|
browser-kotlin/src/jsMain/kotlin/web/rtc/RTCIceGathererState.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6272741}
|
// Automatically generated - do not modify!
package web.rtc
import seskar.js.JsValue
sealed external interface RTCIceGathererState {
companion object {
@JsValue("complete")
val complete: RTCIceGathererState
@JsValue("gathering")
val gathering: RTCIceGathererState
@JsValue("new")
val new: RTCIceGathererState
}
}
| 0
|
Kotlin
|
8
| 36
|
95b065622a9445caf058ad2581f4c91f9e2b0d91
| 374
|
types-kotlin
|
Apache License 2.0
|
src/test/kotlin/io/vlang/lang/parser/ParserTestBase.kt
|
vlang
| 754,996,747
| false
|
{"Kotlin": 1648092, "V": 250415, "Java": 68641, "Lex": 20424, "HTML": 6275}
|
package org.vlang.lang.parser
import com.intellij.lang.ParserDefinition
import com.intellij.testFramework.ParsingTestCase
import java.io.IOException
abstract class ParserTestBase(dataPath: String, fileExt: String, vararg definitions: ParserDefinition) : ParsingTestCase(dataPath, fileExt, *definitions) {
override fun getTestDataPath() = "src/test/resources"
override fun skipSpaces() = true
override fun doTest(checkErrors: Boolean) {
doTestImpl(checkResult = true, ensureNoErrorElements = true)
if (checkErrors) {
assertFalse(
"PsiFile contains error elements",
toParseTreeText(myFile, skipSpaces(), includeRanges()).contains("PsiErrorElement")
)
}
}
private fun doTestImpl(checkResult: Boolean, ensureNoErrorElements: Boolean) {
val name = testName.trim()
try {
parseFile(name, loadFile("$name.$myFileExt"))
if (checkResult) {
checkResult(name, myFile)
if (ensureNoErrorElements) {
ensureNoErrorElements()
}
} else {
toParseTreeText(myFile, skipSpaces(), includeRanges())
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
| 4
|
Kotlin
|
5
| 33
|
5b05a7b1f71ef8dcd7f26425a756259081fe5122
| 1,321
|
intellij-v
|
MIT License
|
gradle-plugin-integration-test-utils/src/main/kotlin/org/unbrokendome/gradle/pluginutils/test/integration/junit/SetupProjectDirAnnotationBased.kt
|
unbroken-dome
| 332,452,514
| false
| null |
package org.unbrokendome.gradle.pluginutils.test.integration.junit
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.unbrokendome.gradle.pluginutils.test.DirectoryBuilder
import org.unbrokendome.gradle.pluginutils.test.directory
import org.unbrokendome.gradle.pluginutils.test.integration.util.plus
import java.io.File
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.nio.file.Path
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class SetupProjectDir
internal class SetupProjectDirAnnotationBasedExtension : BeforeAllCallback {
private companion object {
const val ErrorMessage = "A method annotated with @SetupProjectDir must have a single " +
"parameter of type File, Path or DirectoryBuilder"
}
@ExperimentalStdlibApi
override fun beforeAll(context: ExtensionContext) {
val initializer = context.requiredTestClass.methods.asSequence()
.filter { method ->
method.isAnnotationPresent(SetupProjectDir::class.java)
}
.map { method ->
check(method.parameterTypes.size == 1) { ErrorMessage }
val initializer = when (method.parameterTypes.single()) {
File::class.java -> FileMethodProjectDirInitializer(method)
Path::class.java -> PathMethodProjectDirInitializer(method)
DirectoryBuilder::class.java -> DirectoryBuilderMethodProjectDirInitializer(method)
else -> error(ErrorMessage)
}
@Suppress("USELESS_CAST") // false positive, removing cast gives compile error
initializer as ProjectDirInitializer?
}
.reduceOrNull { acc, initializer -> acc + initializer }
if (initializer != null) {
context.setupProjectDir(initializer)
}
}
}
private abstract class AbstractMethodProjectDirInitializer<T : Any>(
private val method: Method
) : ProjectDirInitializer {
init {
assert(method.parameterTypes.size == 1)
}
protected abstract fun invoke(projectDir: File, invokeMethod: (T) -> Unit)
final override fun accept(projectDir: File, context: ExtensionContext) {
val target = if (Modifier.isStatic(method.modifiers)) null else context.requiredTestInstance
invoke(projectDir) { arg ->
method.invoke(target, arg)
}
}
}
private class FileMethodProjectDirInitializer(method: Method) : AbstractMethodProjectDirInitializer<File>(method) {
init {
assert(method.parameterTypes.single() == File::class.java)
}
override fun invoke(projectDir: File, invokeMethod: (File) -> Unit) {
invokeMethod(projectDir)
}
}
private class PathMethodProjectDirInitializer(method: Method) : AbstractMethodProjectDirInitializer<Path>(method) {
init {
assert(method.parameterTypes.single() == Path::class.java)
}
override fun invoke(projectDir: File, invokeMethod: (Path) -> Unit) {
invokeMethod(projectDir.toPath())
}
}
private class DirectoryBuilderMethodProjectDirInitializer(
method: Method
) : AbstractMethodProjectDirInitializer<DirectoryBuilder>(method) {
init {
assert(method.parameterTypes.single() == DirectoryBuilder::class.java)
}
override fun invoke(projectDir: File, invokeMethod: (DirectoryBuilder) -> Unit) {
directory(projectDir, invokeMethod)
}
}
| 0
|
Kotlin
|
0
| 0
|
56f3868043230d0f7fafc011e3850c85e11f25c3
| 3,582
|
gradle-plugin-utils
|
MIT License
|
erc20/api/src/main/kotlin/com/rarible/protocol/erc20/api/configuration/Erc20IndexerApiConfiguration.kt
|
NFTDroppr
| 418,665,809
| true
|
{"Kotlin": 2329156, "Scala": 37343, "Shell": 6001, "HTML": 547}
|
package com.rarible.protocol.erc20.api.configuration
import com.rarible.core.loggingfilter.EnableLoggingContextFilter
import com.rarible.core.mongo.configuration.EnableRaribleMongo
import com.rarible.ethereum.contract.EnableContractService
import com.rarible.ethereum.converters.EnableScaletherMongoConversions
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import scalether.core.MonoEthereum
import scalether.domain.Address
import scalether.transaction.ReadOnlyMonoTransactionSender
@Configuration
@EnableRaribleMongo
@EnableContractService
@EnableLoggingContextFilter
@EnableScaletherMongoConversions
@EnableConfigurationProperties(Erc20IndexerApiProperties::class)
class Erc20IndexerApiConfiguration {
@Bean
fun sender(ethereum: MonoEthereum) = ReadOnlyMonoTransactionSender(ethereum, Address.ZERO())
}
| 0
|
Kotlin
|
0
| 1
|
b1efdaceab8be95429befe80ce1092fab3004d18
| 961
|
ethereum-indexer
|
MIT License
|
video-common-ui/src/test/java/com/kaleyra/video_common_ui/contactdetailsprovider/CachedLocalContactDetailsProviderTest.kt
|
KaleyraVideo
| 686,975,102
| false
|
{"Kotlin": 3508512, "Shell": 7470, "Python": 6756, "Java": 1213}
|
/*
* Copyright 2023 Kaleyra @ https://www.kaleyra.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kaleyra.video_common_ui.contactdetailsprovider
import com.kaleyra.video_common_ui.contactdetails.cachedprovider.CachedLocalContactDetailsProvider
import com.kaleyra.video_common_ui.contactdetails.model.ContactDetails
import com.kaleyra.video_common_ui.contactdetailsprovider.ContactDetailsTestHelper.assertEqualsContactDetails
import com.kaleyra.video_common_ui.contactdetailsprovider.LocalContactDetailsProviderTestHelper.usersDescriptionProviderMock
import com.kaleyra.video_common_ui.model.UserDetailsProvider
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.spyk
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Test
internal class CachedLocalContactDetailsProviderTest {
private val testDispatcher = StandardTestDispatcher()
@Suppress("UNCHECKED_CAST")
@Test
fun `test retrieve cached user contact details`() = runTest(testDispatcher) {
// cannot use spyk(usersDescriptionProviderMock()) because of this issue https://github.com/mockk/mockk/issues/1033
val usersDescriptionProvider: UserDetailsProvider = spyk {
coEvery { this@spyk.invoke(any()) } coAnswers { call ->
usersDescriptionProviderMock().invoke(call.invocation.args.first() as List<String>)
}
}
val provider = CachedLocalContactDetailsProvider(userDetailsProvider = usersDescriptionProvider, ioDispatcher = testDispatcher)
val result = provider.fetchContactsDetails("userId1")
val expected = listOf(ContactDetails("userId1", MutableStateFlow("username1"), MutableStateFlow(LocalContactDetailsProviderTestHelper.uriUser1)))
assertEqualsContactDetails(expected, result)
val newResult = provider.fetchContactsDetails("userId1", "userId2")
val newExpected = listOf(
ContactDetails("userId1", MutableStateFlow("username1"), MutableStateFlow(LocalContactDetailsProviderTestHelper.uriUser1)),
ContactDetails("userId2", MutableStateFlow("username2"), MutableStateFlow(LocalContactDetailsProviderTestHelper.uriUser2)),
)
assertEqualsContactDetails(newExpected, newResult)
coVerify(exactly = 1) { usersDescriptionProvider(listOf("userId1")) }
coVerify(exactly = 1) { usersDescriptionProvider(listOf("userId2")) }
}
}
| 0
|
Kotlin
|
0
| 1
|
18f298f0e37b089d1ef530eea70bd5e5b9016f9b
| 3,024
|
VideoAndroidSDK
|
Apache License 2.0
|
app/src/main/java/com/b_lam/resplash/util/ViewExt.kt
|
b-lam
| 69,628,893
| false
| null |
package com.b_lam.resplash.util
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.inputmethod.InputMethodManager
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar
fun View.showSnackBar(
message: String,
duration: Int = Snackbar.LENGTH_SHORT,
anchor: View? = null
) {
Snackbar.make(this, message, duration)
.setAnchorView(anchor)
.show()
}
fun View.showSnackBar(
@StringRes textId: Int,
duration: Int = Snackbar.LENGTH_SHORT,
anchor: View? = null
) {
Snackbar.make(this, textId, duration)
.setAnchorView(anchor)
.show()
}
fun View.showSnackBar(
@StringRes textId: Int,
duration: Int = Snackbar.LENGTH_SHORT,
@IdRes anchor: Int
) {
Snackbar.make(this, textId, duration)
.setAnchorView(anchor)
.show()
}
fun View.margin(left: Int? = null, top: Int? = null, right: Int? = null, bottom: Int? = null) {
layoutParams<ViewGroup.MarginLayoutParams> {
left?.let { leftMargin = it }
top?.let { topMargin = it }
right?.let { rightMargin = it }
bottom?.let { bottomMargin = it }
}
}
inline fun <reified T : ViewGroup.LayoutParams> View.layoutParams(block: T.() -> Unit) {
if (layoutParams is T) block(layoutParams as T)
}
fun View.showKeyboard() {
if (requestFocus()) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
fun View.doOnApplyWindowInsets(f: (View, WindowInsets, InitialPadding) -> Unit) {
// Create a snapshot of the view's padding state
val initialPadding = recordInitialPaddingForView(this)
// Set an actual OnApplyWindowInsetsListener which proxies to the given
// lambda, also passing in the original padding state
setOnApplyWindowInsetsListener { v, insets ->
f(v, insets, initialPadding)
// Always return the insets, so that children can also use them
insets
}
// request some insets
requestApplyInsetsWhenAttached()
}
data class InitialPadding(val left: Int, val top: Int,
val right: Int, val bottom: Int)
private fun recordInitialPaddingForView(view: View) = InitialPadding(
view.paddingLeft, view.paddingTop, view.paddingRight, view.paddingBottom)
fun View.requestApplyInsetsWhenAttached() {
if (isAttachedToWindow) {
// We're already attached, just request as normal
requestApplyInsets()
} else {
// We're not attached to the hierarchy, add a listener to request when we are
addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View) {
v.removeOnAttachStateChangeListener(this)
v.requestApplyInsets()
}
override fun onViewDetachedFromWindow(v: View) = Unit
})
}
}
| 33
|
Kotlin
|
105
| 569
|
4b13d31134d1c31bd331e92ffe8d410984529212
| 3,242
|
Resplash
|
The Unlicense
|
app/src/main/java/com/flowfoundation/wallet/widgets/MnemonicWhiteSerialItem.kt
|
Outblock
| 692,942,645
| false
|
{"Kotlin": 2425609, "Java": 104150}
|
package com.flowfoundation.wallet.widgets
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.TextView
import com.flowfoundation.wallet.R
import com.flowfoundation.wallet.page.walletcreate.fragments.mnemonic.MnemonicModel
class MnemonicItem : FrameLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet? = null) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr)
private val indexView by lazy { findViewById<TextView>(R.id.index_view) }
private val textView by lazy { findViewById<TextView>(R.id.text_view) }
init {
LayoutInflater.from(context).inflate(R.layout.widget_mnemonic_item, this)
}
fun setText(text: MnemonicModel) {
indexView.text = "${text.index}"
textView.text = text.text
}
}
| 62
|
Kotlin
|
5
| 0
|
2426c3e1fa04986395d95dfd5fa6ae18fcf11043
| 1,002
|
FRW-Android
|
Apache License 2.0
|
opensdk/src/main/java/com/alicloud/databox/opensdk/scope/AliyunpanFileScope.kt
|
alibaba
| 730,014,798
| false
| null |
package com.alicloud.databox.opensdk.scope
import com.alicloud.databox.opensdk.AliyunpanScope
import org.json.JSONArray
interface AliyunpanFileScope {
/**
* 获取文件列表
* @property driveId drive id
* @property limit 返回文件数量,默认 50,最大 100
* @property marker 分页标记
* @property orderBy created_at, updated_at, name, size, name_enhanced
* @property orderDirection DESC ASC
* @property parentFileId 根目录为root
* @property category 分类,目前有枚举:video | doc | audio | zip | others | image, 可任意组合,按照逗号分割,例如 video,doc,audio, image,doc
* @property type all | file | folder, 默认所有类型, type为folder时,category不做检查
* @property videoThumbnailTime 生成的视频缩略图截帧时间,单位ms,默认120000ms
* @property videoThumbnailWidth 生成的视频缩略图宽度,默认480px
* @property imageThumbnailWidth 生成的图片缩略图宽度,默认480px
* @property fields 当填 * 时,返回文件所有字段
*/
class GetFileList(
private val driveId: String,
private val limit: Int? = null,
private val marker: String? = null,
private val orderBy: String? = null,
private val orderDirection: String? = null,
private val parentFileId: String,
private val category: String? = null,
private val type: String? = null,
private val videoThumbnailTime: Long? = null,
private val videoThumbnailWidth: Long? = null,
private val imageThumbnailWidth: Long? = null,
private val fields: String? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/list"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"limit" to limit,
"marker" to marker,
"order_by" to orderBy,
"order_direction" to orderDirection,
"parent_file_id" to parentFileId,
"category" to category,
"type" to type,
"video_thumbnail_time" to videoThumbnailTime,
"video_thumbnail_width" to videoThumbnailWidth,
"image_thumbnail_width" to imageThumbnailWidth,
"fields" to fields
)
}
}
/**
* 文件搜索
* @property driveId drive id
* @property limit 返回文件数量,默认 100,最大100
* @property marker 分页标记
* @property query 查询语句,样例:固定目录搜索,只搜索一级 parent_file_id = '123' 精确查询 name = '123' 模糊匹配 name match '123' 搜索指定后缀文件 file_extension = 'apk' 范围查询 created_at < '2019-01-14T00:00:00' 复合查询: type = 'folder' or name = '123' parent_file_id = 'root' and name = '123' and category = 'video'
* @property orderBy created_at ASC | DESC updated_at ASC | DESC name ASC | DESC size ASC | DESC
* @property videoThumbnailTime 生成的视频缩略图截帧时间,单位ms,默认120000ms
* @property videoThumbnailWidth 生成的视频缩略图宽度,默认480px
* @property imageThumbnailWidth 生成的图片缩略图宽度,默认480px
* @property returnTotalCount 是否返回总数
*/
class SearchFile(
private val driveId: String,
private val limit: Int? = null,
private val marker: String? = null,
private val query: String? = null,
private val orderBy: String? = null,
private val videoThumbnailTime: Long? = null,
private val videoThumbnailWidth: Long? = null,
private val imageThumbnailWidth: Long? = null,
private val returnTotalCount: Boolean? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/search"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"limit" to limit,
"marker" to marker,
"query" to query,
"order_by" to orderBy,
"video_thumbnail_time" to videoThumbnailTime,
"video_thumbnail_width" to videoThumbnailWidth,
"image_thumbnail_width" to imageThumbnailWidth,
"return_total_count" to returnTotalCount
)
}
}
/**
* 获取收藏文件列表
* @property driveId drive id
* @property limit 默认100,最大 100
* @property marker 分页标记
* @property orderBy created_at, updated_at, name, size
* @property videoThumbnailTime 生成的视频缩略图截帧时间,单位ms,默认120000ms
* @property videoThumbnailWidth 生成的视频缩略图宽度,默认480px
* @property imageThumbnailWidth 生成的图片缩略图宽度,默认480px
* @property orderDirection DESC ASC
* @property type file 或 folder , 默认所有类型
*/
class GetStarredList(
private val driveId: String,
private val limit: Int? = null,
private val marker: String? = null,
private val orderBy: String? = null,
private val videoThumbnailTime: Long? = null,
private val videoThumbnailWidth: Long? = null,
private val imageThumbnailWidth: Long? = null,
private val orderDirection: String? = null,
private val type: String? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/starredList"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"limit" to limit,
"marker" to marker,
"order_by" to orderBy,
"video_thumbnail_time" to videoThumbnailTime,
"video_thumbnail_width" to videoThumbnailWidth,
"image_thumbnail_width" to imageThumbnailWidth,
"order_direction" to orderDirection,
"type" to type
)
}
}
/**
* 获取文件详情
* @property driveId drive id
* @property fileId file_id
* @property videoThumbnailTime 生成的视频缩略图截帧时间,单位ms,默认120000ms
* @property videoThumbnailWidth 生成的视频缩略图宽度,默认480px
* @property imageThumbnailWidth 生成的图片缩略图宽度,默认480px
*/
class GetFile(
private val driveId: String,
private val fileId: String,
private val videoThumbnailTime: Long? = null,
private val videoThumbnailWidth: Long? = null,
private val imageThumbnailWidth: Long? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/get"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"file_id" to fileId,
"video_thumbnail_time" to videoThumbnailTime,
"video_thumbnail_width" to videoThumbnailWidth,
"image_thumbnail_width" to imageThumbnailWidth
)
}
}
/**
* 根据文件路径查找文件
* @property driveId drive id
* @property filePath file_path
*/
class GetFileByPath(private val driveId: String, private val filePath: String) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/get_by_path"
}
override fun getRequest(): Map<String, Any?> {
return mapOf("drive_id" to driveId, "file_path" to filePath)
}
}
/**
* 批量获取文件详情
* @property fileList
* @property videoThumbnailTime 生成的视频缩略图截帧时间,单位ms,默认120000ms
* @property videoThumbnailWidth 生成的视频缩略图宽度,默认480px
* @property imageThumbnailWidth 生成的图片缩略图宽度,默认480px
*/
class BatchGet(
private val fileList: JSONArray,
private val videoThumbnailTime: Long? = null,
private val videoThumbnailWidth: Long? = null,
private val imageThumbnailWidth: Long? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/batch/get"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"file_list" to fileList,
"video_thumbnail_time" to videoThumbnailTime,
"video_thumbnail_width" to videoThumbnailWidth,
"image_thumbnail_width" to imageThumbnailWidth,
)
}
}
/**
* 获取文件下载详情
* @property driveId drive id
* @property fileId file_id
* @property expireSec 下载地址过期时间,单位为秒,默认为 900 秒, 最长4h(14400秒)
*/
class GetFileGetDownloadUrl(
private val driveId: String,
private val fileId: String,
private val expireSec: Int? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/getDownloadUrl"
}
override fun getRequest(): Map<String, Any?> {
return mapOf("drive_id" to driveId, "file_id" to fileId, "expire_sec" to expireSec)
}
}
/**
* 创建文件
* @property driveId drive id
* @property parentFileId 根目录为root
* @property name 文件名称,按照 utf8 编码最长 1024 字节,不能以 / 结尾
* @property type file | folder
* @property checkNameMode auto_rename 自动重命名,存在并发问题, refuse 同名不创建, ignore 同名文件可创建
* @property partInfoList 最大分片数量 10000
* @property streamsInfo 仅上传livp格式的时候需要,常见场景不需要
* @property preHash 针对大文件sha1计算非常耗时的情况, 可以先在读取文件的前1k的sha1, 如果前1k的sha1没有匹配的, 那么说明文件无法做秒传, 如果1ksha1有匹配再计算文件sha1进行秒传,这样有效边避免无效的sha1计算。
* @property size 秒传必须, 文件大小,单位为 byte
* @property contentHash 秒传必须, 文件内容 hash 值,需要根据 content_hash_name 指定的算法计算,当前都是sha1算法
* @property contentHashName 秒传必须, 默认都是 sha1
* @property proofCode 秒传必须
* @property proofVersion 固定 v1
* @property localCreatedAt 本地创建时间,格式yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
* @property localModifiedAt 本地修改时间,格式yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
*/
class CreateFile(
private val driveId: String,
private val parentFileId: String,
private val name: String,
private val type: String,
private val checkNameMode: String,
private val partInfoList: JSONArray? = null,
private val streamsInfo: JSONArray? = null,
private val preHash: String? = null,
private val size: Long? = null,
private val contentHash: String? = null,
private val contentHashName: String? = null,
private val proofCode: String? = null,
private val proofVersion: String? = null,
private val localCreatedAt: String? = null,
private val localModifiedAt: String? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/create"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"parent_file_id" to parentFileId,
"name" to name,
"type" to type,
"check_name_mode" to checkNameMode,
"part_info_list" to partInfoList,
"streams_info" to streamsInfo,
"pre_hash" to preHash,
"size" to size,
"content_hash" to contentHash,
"content_hash_name" to contentHashName,
"proof_code" to proofCode,
"proof_version" to proofVersion,
"local_created_at" to localCreatedAt,
"local_modified_at" to localModifiedAt
)
}
}
/**
* 刷新获取上传地址
* @property driveId drive id
* @property fileId file_id
* @property uploadId 文件创建获取的upload_id
* @property partInfoList 分片信息列表
*/
class GetUploadURL(
private val driveId: String,
private val fileId: String,
private val uploadId: String,
private val partInfoList: JSONArray? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/getUploadUrl"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"file_id" to fileId,
"upload_id" to uploadId,
"part_info_list" to partInfoList
)
}
}
/**
* 列举已上传分片
* @property driveId drive id
* @property fileId file_id
* @property uploadId 文件创建获取的upload_id
* @property partNumberMarker
*/
class ListUploadedParts(
private val driveId: String,
private val fileId: String,
private val uploadId: String,
private val partNumberMarker: String? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/listUploadedParts"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"file_id" to fileId,
"upload_id" to uploadId,
"part_number_marker" to partNumberMarker
)
}
}
/**
* 标记文件上传完毕
* @property driveId drive id
* @property fileId file_id
* @property uploadId 文件创建获取的upload_id
*/
class CompleteUpload(private val driveId: String, private val fileId: String, private val uploadId: String) :
AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/complete"
}
override fun getRequest(): Map<String, Any?> {
return mapOf("drive_id" to driveId, "file_id" to fileId, "upload_id" to uploadId)
}
}
/**
* 文件更新
* @property driveId drive id
* @property fileId file_id
* @property name 新的文件名
* @property checkNameMode auto_rename 自动重命名, refuse 同名不创建, ignore 同名文件可创建。 默认
* @property starred 收藏 true,移除收藏 false
*/
class UpdateFile(
private val driveId: String,
private val fileId: String,
private val name: String? = null,
private val checkNameMode: String? = null,
private val starred: Boolean? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/update"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"file_id" to fileId,
"name" to name,
"check_name_mode" to checkNameMode,
"starred" to starred
)
}
}
/**
* 移动文件或文件夹
* @property driveId 当前drive id
* @property fileId file_id
* @property toDriveId 目标drive,默认是当前drive_id 目前只能在当前drive操作
* @property toParentFileId 父文件ID、根目录为 root
* @property checkNameMode 同名文件处理模式,可选值如下:ignore:允许同名文件;auto_rename:当发现同名文件是,云端自动重命名。refuse:当云端存在同名文件时,拒绝创建新文件。默认为 refuse
* @property newName 当云端存在同名文件时,使用的新名字
*/
class MoveFile(
private val driveId: String,
private val fileId: String,
private val toDriveId: String? = null,
private val toParentFileId: String,
private val checkNameMode: String? = null,
private val newName: String? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/move"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"file_id" to fileId,
"to_drive_id" to toDriveId,
"to_parent_file_id" to toParentFileId,
"check_name_mode" to checkNameMode,
"new_name" to newName
)
}
}
/**
* 复制文件或文件夹
* @property driveId drive id
* @property fileId file_id
* @property toDriveId 目标drive,默认是当前drive_id
* @property toParentFileId 父文件ID、根目录为 root
* @property autoRename 当目标文件夹下存在同名文件时,是否自动重命名,默认为 false,默认允许同名文件
*/
class CopyFile(
private val driveId: String,
private val fileId: String,
private val toDriveId: String? = null,
private val toParentFileId: String,
private val autoRename: Boolean? = null
) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/copy"
}
override fun getRequest(): Map<String, Any?> {
return mapOf(
"drive_id" to driveId,
"file_id" to fileId,
"to_drive_id" to toDriveId,
"to_parent_file_id" to toParentFileId,
"auto_rename" to autoRename
)
}
}
/**
* 放入回收站
* @property driveId drive id
* @property fileId file_id
*/
class TrashFileToRecyclebin(private val driveId: String, private val fileId: String) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/recyclebin/trash"
}
override fun getRequest(): Map<String, Any?> {
return mapOf("drive_id" to driveId, "file_id" to fileId)
}
}
/**
* 删除文件
* @property driveId drive id
* @property fileId file_id
*/
class DeleteFile(private val driveId: String, private val fileId: String) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/delete"
}
override fun getRequest(): Map<String, Any?> {
return mapOf("drive_id" to driveId, "file_id" to fileId)
}
}
/**
* 获取异步任务状态
* @property asyncTaskId 异步任务ID
*/
class GetAsyncTask(private val asyncTaskId: String) : AliyunpanScope {
override fun getHttpMethod(): String {
return "POST"
}
override fun getApi(): String {
return "adrive/v1.0/openFile/async_task/get"
}
override fun getRequest(): Map<String, Any?> {
return mapOf("async_task_id" to asyncTaskId)
}
}
}
| 0
| null |
2
| 9
|
3057d51f04803e043a63f29b7418a0d01da17cdf
| 19,035
|
aliyunpan-android-sdk
|
MIT License
|
brv/src/main/java/com/drake/brv/utils/PageRefreshUtils.kt
|
liangjingkanji
| 206,460,689
| false
| null |
/*
* Copyright (C) 2018 Drake, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.drake.brv.utils
import android.view.View
import android.view.ViewGroup
import com.drake.brv.PageRefreshLayout
/**
* PageRefreshLayout 包裹当前 view
*
* @receiver View
* @param loadMoreEnabled Boolean 启用上拉加载
* @param stateEnabled Boolean 启用缺省页
*/
fun View.page(
loadMoreEnabled: Boolean = true,
stateEnabled: Boolean = true
): PageRefreshLayout {
val pageRefreshLayout = PageRefreshLayout(context)
val parent = parent as ViewGroup
pageRefreshLayout.id = id
val index = parent.indexOfChild(this)
val layoutParams = layoutParams
parent.removeView(this)
pageRefreshLayout.setRefreshContent(this@page)
parent.addView(pageRefreshLayout, index, layoutParams)
pageRefreshLayout.apply {
setEnableLoadMore(loadMoreEnabled)
this.stateEnabled = stateEnabled
initialize()
}
return pageRefreshLayout
}
| 4
|
Kotlin
|
87
| 747
|
1519b799fd0c84b765c94ae64e74d83cd33e3d39
| 1,485
|
BRV
|
Apache License 2.0
|
core/local/src/main/java/com/anshtya/movieinfo/core/local/database/entity/FavoriteContentEntity.kt
|
anshtya
| 704,151,092
| false
|
{"Kotlin": 377757}
|
package com.anshtya.movieinfo.core.local.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.anshtya.movieinfo.core.model.library.LibraryItem
@Entity(
tableName = "favorite_content",
indices = [Index(value = ["media_id", "media_type"], unique = true)]
)
data class FavoriteContentEntity(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "media_id") val mediaId: Int,
@ColumnInfo(name = "media_type") val mediaType: String,
@ColumnInfo(name = "image_path") val imagePath: String,
val name: String
) {
fun asLibraryItem() = LibraryItem(
id = mediaId,
mediaType = mediaType,
imagePath = imagePath,
name = name
)
}
fun LibraryItem.asFavoriteContentEntity() = FavoriteContentEntity(
mediaId = id,
mediaType = mediaType,
imagePath = imagePath,
name = name
)
| 0
|
Kotlin
|
0
| 2
|
4af49c0b3b5af426393c8ceee830b877f1e66c92
| 952
|
MovieInfo
|
MIT License
|
app/src/main/kotlin/org/mediasoup/droid/demo/utils/ClipboardCopy.kt
|
crow-misia
| 264,322,033
| true
|
{"Kotlin": 119961}
|
package org.mediasoup.droid.demo.utils
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.widget.Toast
import androidx.core.content.getSystemService
object ClipboardCopy {
fun clipboardCopy(context: Context, content: String?, tipsResId: Int) {
val clipboard = context.getSystemService<ClipboardManager>() ?: return
val clip = ClipData.newPlainText("label", content)
clipboard.setPrimaryClip(clip)
Toast.makeText(context, tipsResId, Toast.LENGTH_SHORT).show()
}
}
| 0
|
Kotlin
|
3
| 7
|
27869aa9fec304e41424dec644348dff0c3591bb
| 572
|
mediasoup-demo-android
|
MIT License
|
modules/preferences/src/androidMain/kotlin/splitties/preferences/Changes.kt
|
LouisCAD
| 65,558,914
| false
|
{"Kotlin": 682428, "Java": 1368, "Shell": 358}
|
/*
* Copyright 2019 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.preferences
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.conflate
import splitties.experimental.NonSymmetricalApi
@OptIn(ExperimentalCoroutinesApi::class)
internal actual fun SharedPreferences.changesFlow(
key: String,
emitAfterRegister: Boolean
): Flow<Unit> = channelFlow {
@OptIn(NonSymmetricalApi::class)
val listener = OnSharedPreferenceChangeListener { _, changedKey ->
if (key == changedKey) trySend(Unit)
}
registerOnSharedPreferenceChangeListener(listener)
if (emitAfterRegister) trySend(Unit)
awaitClose {
unregisterOnSharedPreferenceChangeListener(listener)
}
}.conflate()
| 53
|
Kotlin
|
160
| 2,476
|
1ed56ba2779f31dbf909509c955fce7b9768e208
| 916
|
Splitties
|
Apache License 2.0
|
src/main/kotlin/com/example/ecommerce/shared/domain/event/EventPublisher.kt
|
IvanGuardado
| 197,396,455
| false
| null |
package com.example.ecommerce.shared.domain.event
interface EventPublisher {
operator fun invoke(event: DomainEvent)
operator fun invoke(events: ArrayList<DomainEvent>) {
events.forEach {
invoke(it)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
39a87bb2778cddd119df581b8adc052c46b87ef1
| 248
|
kotlin-api-clean-architecture
|
MIT License
|
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/device/RamFill.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.remix.remix.device
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.DeviceGroup
public val DeviceGroup.RamFill: ImageVector
get() {
if (_ramFill != null) {
return _ramFill!!
}
_ramFill = Builder(name = "RamFill", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(2.0f, 5.0f)
curveTo(1.448f, 5.0f, 1.0f, 5.448f, 1.0f, 6.0f)
verticalLineTo(18.0f)
curveTo(1.0f, 18.552f, 1.448f, 19.0f, 2.0f, 19.0f)
horizontalLineTo(5.0f)
verticalLineTo(17.0f)
horizontalLineTo(7.0f)
verticalLineTo(19.0f)
horizontalLineTo(9.0f)
verticalLineTo(17.0f)
horizontalLineTo(11.0f)
verticalLineTo(19.0f)
horizontalLineTo(13.0f)
verticalLineTo(17.0f)
horizontalLineTo(15.0f)
verticalLineTo(19.0f)
horizontalLineTo(17.0f)
verticalLineTo(17.0f)
horizontalLineTo(19.0f)
verticalLineTo(19.0f)
horizontalLineTo(22.0f)
curveTo(22.552f, 19.0f, 23.0f, 18.552f, 23.0f, 18.0f)
verticalLineTo(6.0f)
curveTo(23.0f, 5.448f, 22.552f, 5.0f, 22.0f, 5.0f)
horizontalLineTo(2.0f)
close()
moveTo(5.0f, 9.0f)
horizontalLineTo(11.0f)
verticalLineTo(12.0f)
horizontalLineTo(5.0f)
verticalLineTo(9.0f)
close()
moveTo(13.0f, 9.0f)
horizontalLineTo(19.0f)
verticalLineTo(12.0f)
horizontalLineTo(13.0f)
verticalLineTo(9.0f)
close()
}
}
.build()
return _ramFill!!
}
private var _ramFill: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 2,782
|
compose-icon-collections
|
MIT License
|
buildSrc/src/main/kotlin/koleton/Extensions.kt
|
ericktijerou
| 267,768,682
| false
| null |
@file:Suppress("unused")
package skeletor
import org.gradle.api.Project
val Project.minSdk: Int
get() = intProperty("minSdk")
val Project.targetSdk: Int
get() = intProperty("targetSdk")
val Project.compileSdk: Int
get() = intProperty("compileSdk")
val Project.groupId: String
get() = stringProperty("groupId")
val Project.publishVersion: String
get() = stringProperty("publishVersion")
val Project.vcsUrl: String
get() = stringProperty("vcsUrl")
val Project.issueTrackerUrl: String
get() = stringProperty("issueTrackerUrl")
private fun Project.intProperty(name: String): Int {
return (property(name) as String).toInt()
}
private fun Project.stringProperty(name: String): String {
return property(name) as String
}
| 6
| null |
12
| 87
|
58b7a54674ee3bf0c2351f21101181ca203a3d06
| 760
|
koleton
|
Apache License 2.0
|
modules/feature/map/impl/src/main/kotlin/kekmech/ru/feature_map_impl/launcher/DeeplinkDelegate.kt
|
tonykolomeytsev
| 203,239,594
| false
| null |
package kekmech.ru.feature_map.launcher
import kekmech.ru.feature_map.screens.main.elm.FilterTab
internal class DeeplinkDelegate {
private var placeUid: String? = null
private var tab: FilterTab? = null
fun putPlaceUid(placeUid: String) {
this.placeUid = placeUid
}
fun getPlaceUid() = placeUid
fun putTab(tabName: String) {
this.tab = FilterTab.valueOf(tabName)
}
fun getTab() = tab
fun clear() {
placeUid = null
tab = null
}
fun isNotEmpty() = placeUid != null || tab != null
}
| 9
| null |
4
| 41
|
15c3c17e33d0ffffc0e269ad0cd6fe47b0bc971a
| 564
|
mpeiapp
|
MIT License
|
app/src/main/java/com/afterow/sanyaoyi/SelectActivity.kt
|
afterow
| 856,459,302
| false
|
{"Kotlin": 32589}
|
package com.afterow.sanyaoyi
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class SelectActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_select)
val yao1: TextView = findViewById(R.id.yao1)
val yao2: TextView = findViewById(R.id.yao2)
val yao3: TextView = findViewById(R.id.yao3)
// 设置点击事件监听器
val listener = View.OnClickListener { view ->
val yaoTextView = view as TextView
// 切换爻的显示
yaoTextView.text = if (yaoTextView.text == "⚋") "⚊" else "⚋"
}
// 为每个爻设置点击事件
yao1.setOnClickListener(listener)
yao2.setOnClickListener(listener)
yao3.setOnClickListener(listener)
val myButton: Button = findViewById(R.id.anl1)
myButton.setOnClickListener {
val mutableList = mutableListOf<Int>()
val views = listOf(yao1, yao2, yao3)
views.forEach {
if (it.text == "⚊") {
mutableList.add(1)
} else {
mutableList.add(0)
}
}
val listString = mutableList.joinToString(",") { it.toString() }
val intent = Intent(this, DivinationActivity::class.java)
intent.putExtra("listData", listString)
startActivity(intent)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
adfc849fae5a5717c26fca9abee0e6e53f092209
| 1,608
|
sanyaoyi-kotlin
|
MIT License
|
drestaurant-apps/drestaurant-microservices-rest-2/drestaurant-microservices-rest-2-common/src/main/kotlin/com/drestaurant/customer/query/api/queries.kt
|
idugalic
| 135,263,722
| false
| null |
package com.drestaurant.customer.query.api
import com.drestaurant.customer.domain.api.model.CustomerId
data class FindCustomerQuery(val customerId: CustomerId)
| 0
|
Kotlin
|
83
| 284
|
920248e62c5b7d9b8d3c365b2f911355aa19c7db
| 162
|
digital-restaurant
|
Apache License 2.0
|
bundles/github.com/korlibs/korge-bundles/7439e5c7de7442f2cd33a1944846d44aea31af0a/korge-admob/src/jvmMain/kotlin/com/soywiz/korge/admob/Admob.kt
|
jfbilodeau
| 402,501,246
| false
| null |
package com.soywiz.korge.admob
import com.soywiz.korge.view.Views
import com.soywiz.korim.bitmap.Bitmaps
import com.soywiz.korim.color.Colors
import com.soywiz.korim.color.RGBA
import com.soywiz.korma.geom.Matrix
actual suspend fun AdmobCreate(views: Views, testing: Boolean): Admob = AdmobCreateDefault(views, testing)
| 0
|
Kotlin
|
1
| 2
|
306f034be2d9832743c3fb0acfbfd46b53c7f01f
| 322
|
BeyondBeachball
|
Apache License 2.0
|
Mobile App/app/src/main/java/com/example/scar/interfaces/LinkWeapon.kt
|
gursimar03
| 704,020,851
| false
|
{"Kotlin": 147166, "Python": 75744, "CSS": 12172, "JavaScript": 8955, "HTML": 5933, "Java": 198}
|
package com.example.scar.interfaces
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
//import com.example.scar.AppViewModelProvider
import com.example.scar.R
import com.example.scar.screens.GunUiState
import com.example.scar.screens.GunViewModel
//import com.example.scar.gun.GunEntryViewModel
import com.example.scar.screens.PlayerUiState
import com.example.scar.screens.PlayerViewModel
import com.example.scar.ui.theme.Gun
import com.example.scar.ui.theme.GunData
import com.example.scar.ui.theme.GunList
import com.example.scar.ui.theme.Screen
import com.example.scar.ui.theme.cardBg2
import com.example.scar.ui.theme.cardBgDark
import com.example.scar.ui.theme.creme
import com.example.scar.ui.theme.textBg
//sources
///https://stackoverflow.com/questions/72794300/is-there-a-way-to-filter-the-exposed-dropdown-menu-options-depending-on-the-valu/72795638#72795638
@Composable
fun LinkWeapon(navController: NavController) {
val gunViewModel: GunViewModel = viewModel()
Surface(modifier = Modifier.fillMaxSize()) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
// .fillMaxSize()
.padding(horizontal = 16.dp)
) {
Card(
modifier = Modifier
// .fillMaxSize()
.padding(16.dp)
.height(600.dp),
colors = CardDefaults.cardColors(containerColor = Color.White)
) {
// weaponList()
GunUI(guns = gunViewModel.gunUiState)
}
Column {
val playerViewModel: PlayerViewModel = viewModel()
Button(
modifier = Modifier
.width(350.dp)
.height(80.dp)
.shadow(
elevation = 8.dp,
shape = RoundedCornerShape(70),
clip = true
),
onClick = {
navController.navigate(Screen.StartMatch.route)
},
shape = RoundedCornerShape(10.dp),
colors = ButtonDefaults.buttonColors(
textBg
),
// border = BorderStroke(5.dp, Color.Black)
) {
Text(
text = "Continue", fontFamily = FontFamily(
Font(R.font.montserrat_bold, weight = FontWeight.Normal)
), fontSize = 20.sp
)
}
}
}
}
Spacer(modifier = Modifier.height(40.dp))
BottomNavigationBar(navController = navController)
}
data class weaponData(val name:String)
@Composable
fun weaponList(list: List<Gun>)
{
LazyColumn {
itemsIndexed(list) { index, entry ->
weapon(name = entry.weaponName, image = entry.image)
}
}
}
@Composable
fun weapon(name:String, image:String){
var clicked by remember { mutableStateOf(false) }
val coroutineScope = rememberCoroutineScope()
// val GunViewModel:GunEntryViewModel = viewModel(factory = AppViewModelProvider.Factory)
Card(
modifier = Modifier
.padding(16.dp)
.height(400.dp)
.shadow(
elevation = 8.dp,
),
colors = CardDefaults.cardColors(containerColor = Color.White),
) {
Text(
text = name,
style = TextStyle(color= Color.Black, fontSize = 30.sp),
fontFamily= FontFamily(
Font(R.font.montserrat_bold,weight= FontWeight.Normal)
),
modifier = Modifier.padding(10.dp)
)
Box(modifier=Modifier
.size(250.dp).align(Alignment.CenterHorizontally)
,
contentAlignment = Alignment.Center,
) {
AsyncImage(
model = image,
contentDescription = null,
)
}
Column(
modifier = Modifier
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ElevatedCard(
colors = CardDefaults.cardColors(containerColor = cardBgDark),
modifier = Modifier
.height(55.dp)
.fillMaxWidth()
.shadow(
shape = RoundedCornerShape(70),
spotColor = Color.White,
elevation = 30.dp,
),
) {
Row {
Button(onClick = {
// val TestGun = Gun(name = "Gun A", gunID = 1)
// coroutineScope.launch {
// GunViewModel.saveItem(TestGun);
// }
clicked = !clicked
},
modifier = Modifier.fillMaxSize()
.background(if (clicked) Color.Green else Color.Gray),
colors = if (clicked) ButtonDefaults.buttonColors(Color.Green) else ButtonDefaults.buttonColors(
cardBg2)
) {
Text(text = if (clicked) "Gun Linked" else "Link Gun", color = Color.White,
fontFamily = FontFamily(
Font(R.font.montserrat_bold, weight = FontWeight.Normal)),
fontSize = 16.sp)
}
}
}
}
}
}
@Composable
fun GunUI(guns: GunUiState) {
when (guns) {
is GunUiState.Loading -> LoadingGuns()
is GunUiState.Success ->
SuccessLoadingGuns(guns.data)
//
is GunUiState.Error -> LoadingGuns()
else -> {
LoadingGuns()}
}
}
@Composable
fun LoadingGuns()
{
// val matchDataExample = remember {
// listOf(
// weaponData("weapon1"),
// weaponData("weapon1"),
// weaponData("weapon1"),
//
// )
// }
//
// LazyColumn {
// itemsIndexed(matchDataExample) { index, entry ->
// (entry.kills,entry.spotted,entry.travelled)
// }
// }
}
@Composable
fun SuccessLoadingGuns(gunInfoList: GunData)
{
Log.d("userInfoList",gunInfoList.guns.toString())
for (gun in gunInfoList.guns) {
// Replace this with your custom layout for displaying each gun
weaponList(list = gun.weapons)
}
}
| 3
|
Kotlin
|
0
| 0
|
2537e60a25aea46db22146178f6bd1989f3ed2ae
| 8,751
|
SCAR
|
MIT License
|
app/src/main/java/com/aditya/to_do/ui/screens/task/TaskScreen.kt
|
aditya-bhawsar
| 413,261,754
| false
|
{"Kotlin": 73381}
|
package com.aditya.to_do.ui.screens.task
import android.content.Context
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalContext
import com.aditya.to_do.data.models.Priority
import com.aditya.to_do.data.models.ToDoTask
import com.aditya.to_do.ui.viewmodels.SharedViewModel
import com.aditya.to_do.util.Action
@Composable
fun TaskScreen(
sharedViewModel: SharedViewModel,
navigateToListScreen: (Action) -> Unit,
selectedTask: ToDoTask?
) {
val title: String by sharedViewModel.title
val desc: String by sharedViewModel.desc
val priority: Priority by sharedViewModel.priority
val ctx = LocalContext.current
BackHandler {
navigateToListScreen(Action.NO_ACTION)
}
Scaffold(
topBar = {
TaskAppBar(
navigateToListScreen = { action ->
if (action == Action.NO_ACTION) {
navigateToListScreen(action)
} else {
if (sharedViewModel.validateFields()) {
navigateToListScreen(action)
} else {
displayToast(ctx = ctx)
}
}
},
selectedTask = selectedTask
)
},
content = {
TaskContent(
title = title,
onTitleChanged = {
sharedViewModel.updateTitle(it)
},
description = desc,
onDescriptionChanged = {
sharedViewModel.desc.value = it
},
priority = priority,
onPrioritySelected = {
sharedViewModel.priority.value = it
}
)
}
)
}
fun displayToast(ctx: Context) {
Toast.makeText(ctx, "Fields can't be Empty", Toast.LENGTH_LONG).show()
}
| 0
|
Kotlin
|
0
| 1
|
e2e4d58c9e6d3463ccafa93e427f27b30b008b12
| 2,109
|
to-do-compose
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.