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/java/org/grammatek/simacorrect/spellcheckerservice/RettritunSpellCheckerService.kt
grammatek
473,551,296
false
null
package org.grammatek.simacorrect.spellcheckerservice import android.content.ContentResolver import android.database.ContentObserver import android.database.Cursor import android.provider.UserDictionary.Words import android.service.textservice.SpellCheckerService import android.util.Log import android.view.textservice.* import org.grammatek.models.CorrectRequest import org.grammatek.simacorrect.network.ConnectionManager /** * Implements Rettritun spell checking as a SpellCheckerService */ class RettritunSpellCheckerService : SpellCheckerService() { override fun createSession(): Session { return AndroidSpellCheckerSession(contentResolver) } private class AndroidSpellCheckerSession(contentResolver: ContentResolver): Session() { private lateinit var _locale: String private var _contentResolver: ContentResolver = contentResolver private var _userDict: ArrayList<String> = ArrayList() private val _yfirlesturRulesToIgnore = listOf("Z002") override fun onCreate() { _locale = locale loadUserDictionary() // Register a listener for changes in the user dictionary. _contentResolver.registerContentObserver( Words.CONTENT_URI, false, object : ContentObserver(null) { override fun onChange(selfChange: Boolean) { if (LOG) Log.d(TAG, "Observed changes in user dictionary") loadUserDictionary() } } ) } /** * Synchronously loads the user's dictionary into the spell checker session. */ @Synchronized private fun loadUserDictionary() { // from user dictionary, query for words with locale = "_locale" val cursor: Cursor = _contentResolver.query(Words.CONTENT_URI, arrayOf(Words.WORD), "${Words.LOCALE} = ?", arrayOf(_locale), null) ?: return val index = cursor.getColumnIndex(Words.WORD) val words = ArrayList<String>() while (cursor.moveToNext()) { words.add(cursor.getString(index)) } cursor.close() _userDict = words } override fun onGetSuggestionsMultiple( textInfos: Array<TextInfo?>, suggestionsLimit: Int, sequentialWords: Boolean ): Array<SuggestionsInfo> { TODO("Not to be implemented") } override fun onGetSentenceSuggestionsMultiple( textInfos: Array<out TextInfo>?, suggestionsLimit: Int, ): Array<SentenceSuggestionsInfo?> { if(LOG) Log.d(TAG, "onGetSentenceSuggestionsMultiple: ${textInfos?.size}") if(textInfos == null || textInfos.isEmpty()) { return emptyArray() } val retval = arrayOfNulls<SentenceSuggestionsInfo>(textInfos.size) for (i in textInfos.indices) { val suggestionList: Array<SuggestionsInfo> val suggestionsIndices: Array<YfirlesturAnnotation.AnnotationIndices> try { val text = textInfos[i].text!! if (text.isBlank()) { continue } val request = CorrectRequest(text, ignoreWordlist = _userDict, ignoreRules = _yfirlesturRulesToIgnore) val response = ConnectionManager.correctSentence(request) val ylAnnotation = YfirlesturAnnotation(response, textInfos[i].text) suggestionList = ylAnnotation.getSuggestionsForAnnotatedWords(suggestionsLimit).toTypedArray() suggestionsIndices = ylAnnotation.suggestionsIndices.toTypedArray() } catch (e: Exception) { Log.e(TAG, "onGetSentenceSuggestionsMultiple: ${e.message} ${e.stackTrace.joinToString("\n")}") return emptyArray() } retval[i] = reconstructSuggestions( suggestionList, suggestionsIndices, textInfos[i] ) } return retval } fun reconstructSuggestions( results: Array<SuggestionsInfo>, resultsIndices: Array<YfirlesturAnnotation.AnnotationIndices>, originalTextInfo: TextInfo ): SentenceSuggestionsInfo? { if (results.isEmpty() || originalTextInfo.text.isEmpty()) { return null } val offsets = IntArray(results.size) val lengths = IntArray(results.size) val reconstructedSuggestions = arrayOfNulls<SuggestionsInfo>(results.size) for (i in results.indices) { offsets[i] = resultsIndices[i].startChar lengths[i] = resultsIndices[i].length val result: SuggestionsInfo = results[i] // If the SuggestionInfo result has no suggestions we originally wanted to annotate that // word regardless, but doing so we would increase the occurrence of a bug with looping suggestions. // https://github.com/grammatek/simacorrect/issues/22 for more details. if (result.suggestionsCount == 0) { reconstructedSuggestions[i] = SuggestionsInfo(0, null) } else { reconstructedSuggestions[i] = result result.setCookieAndSequence(originalTextInfo.cookie, originalTextInfo.sequence) } } return SentenceSuggestionsInfo(reconstructedSuggestions, offsets, lengths) } override fun onGetSuggestions(textInfo: TextInfo?, suggestionsLimit: Int): SuggestionsInfo { TODO("Not to be implemented") } companion object { private const val LOG = false private val TAG = RettritunSpellCheckerService::class.java.simpleName } } }
4
Kotlin
0
2
4400c0b02a3afe1d3dd38c0c73a10b23ab10d452
6,091
simacorrect
Apache License 1.1
app/src/main/java/com/g/pocketmal/domain/entity/converter/RankingEntityConverter.kt
glodanif
847,288,195
false
{"Kotlin": 517413, "Java": 112995}
package com.g.pocketmal.domain.entity.converter import com.g.pocketmal.data.api.response.RankingResponse import com.g.pocketmal.data.util.TitleType import com.g.pocketmal.domain.entity.RankingEntity class RankingEntityConverter { fun transform(response: RankingResponse, titleType: TitleType, useEnglishTitle: Boolean): List<RankingEntity> { return response.list.map { item -> val node = item.node val english = node.alternativeTitles?.english val titleLabel = if (useEnglishTitle && english != null && english.isNotEmpty()) english else node.title val episodes = if (titleType == TitleType.ANIME) node.numEpisodes else node.numChapters RankingEntity( node.id, titleLabel, node.mainPicture?.large, node.mediaType, episodes, node.score, node.menders, node.startDate, node.synopsis, item.ranking.rank, item.ranking.previousRank ) } } }
0
Kotlin
1
8
1a7fe52c2dc59dd3bf4eaeb3d9bb64d469e10845
1,189
Pocket_MAL
MIT License
okhttp/src/main/java/cn/yizems/util/ktx/okhttp/OKHttpEx.kt
yizems
429,726,361
false
{"Kotlin": 175954, "Java": 7863}
package cn.yizems.util.ktx.okhttp import cn.yizems.util.ktx.comm.file.generateUuidName import okhttp3.MediaType.Companion.toMediaType import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody import java.io.File import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.X509TrustManager //region media type /** Json请求header, 包含charset */ const val MEDIA_TYPE_JSON_STR_WITH_CHARSET = "application/json;charset=utf-8" /** Json请求Header*/ const val MEDIA_TYPE_JSON_STR = "application/json" /** Json请求 MediaType */ val MEDIA_TYPE_JSON by lazy { MEDIA_TYPE_JSON_STR_WITH_CHARSET.toMediaType() } /** form 请求 mediaType */ val MEDIA_TYPE_FORM_DATA by lazy { "multipart/form-data".toMediaType() } //endregion //region Body创建 /** String 转为 json 请求体 */ fun String?.toJsonRequestBody() = (this ?: "{}").toRequestBody(MEDIA_TYPE_JSON) /** 文件请求体 */ fun File.toRequestBody() = this.asRequestBody(MEDIA_TYPE_FORM_DATA) /** 文件转为 MultipartBody.Part */ fun File.toMultiPart(key: String = "file", fileName: String? = null): MultipartBody.Part { val rFileName = fileName ?: this.generateUuidName() return MultipartBody.Part.createFormData(key, rFileName, this.toRequestBody()) } //endregion //region OkhttpClient 配置 /** * 信任所有域名 * @receiver OkHttpClient.Builder * @return OkHttpClient.Builder */ fun OkHttpClient.Builder.trustAllCerts(): OkHttpClient.Builder { val trustManager = object : X509TrustManager { override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) { } override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) { } override fun getAcceptedIssuers(): Array<X509Certificate> { return arrayOf() } } val trustManagers = arrayOf(trustManager) val sslContext = SSLContext.getInstance("TSL"); sslContext.init(null, trustManagers, SecureRandom()); val sslSocketFactory = sslContext.socketFactory this.sslSocketFactory(sslSocketFactory, trustManager) this.hostnameVerifier { _, _ -> true }; return this } //endregion
0
Kotlin
1
31
89d851aeeacb11f6b5dd31a3b3ddc81f3b5e1219
2,265
KUtil
MIT License
app/src/main/java/com/sayantanbanerjee/transactionmanagementapp/NetworkConnectivity.kt
SayantanBanerjee16
366,980,477
false
null
package com.sayantanbanerjee.transactionmanagementapp import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.util.Log // Utility class to check if Network connectivity present or not class NetworkConnectivity { companion object { fun isNetworkAvailable(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) if (capabilities != null) { when { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> { Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR") return true } capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> { Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI") return true } capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> { Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET") return true } } } return false } } }
0
Kotlin
4
23
bcd1119b8c0fa64c77208f7a583617c9911793a5
1,451
Transact
MIT License
app/src/main/java/com/xtensolutions/weatherapp/di/LocationModule.kt
riontech-xten
345,582,958
false
null
package com.xtensolutions.weatherapp.di import android.content.Context import android.location.Geocoder import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.xtensolutions.weatherapp.WeatherApp import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityComponent import dagger.hilt.android.components.ApplicationComponent import dagger.hilt.android.qualifiers.ActivityContext import dagger.hilt.android.qualifiers.ApplicationContext import java.util.* import javax.inject.Singleton /** * Created by <NAME> on 18/02/21. * <EMAIL> */ @InstallIn(ApplicationComponent::class) @Module class LocationModule { @Provides fun getApplicationContext(app: WeatherApp): Context { return app.applicationContext } @Provides fun getFusedLocationClient(@ApplicationContext context: Context): FusedLocationProviderClient { return LocationServices.getFusedLocationProviderClient(context) } @Provides fun getGeocoder(@ApplicationContext context: Context): Geocoder { return Geocoder(context, Locale.getDefault()) } }
0
Kotlin
0
0
baea739eb9789d3d803a4bb29084965f15cdae83
1,205
Weather
Apache License 2.0
app/src/main/java/com/onoffrice/marvel_comics/utils/CustomLinearLayoutManager.kt
LucasOnofre
246,949,422
false
null
package com.onoffrice.marvel_comics.utils import android.content.Context class CustomLinearLayoutManager(context: Context) : androidx.recyclerview.widget.LinearLayoutManager(context) { override fun supportsPredictiveItemAnimations(): Boolean { return false } }
0
Kotlin
0
2
48a352905df791baddd7d2c0313409b948502e98
280
Marvel-Comics
MIT License
materialize/scrollspy.module_definitely-typed.kt
Jolanrensen
224,876,635
false
null
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION") import M.ScrollSpyOptionsPartial import kotlin.js.* import kotlin.js.Json import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* /* extending interface from autocomplete.d.ts */ inline fun JQuery.scrollSpy(options: ScrollSpyOptionsPartial?): JQuery = this.asDynamic().scrollSpy(options) inline fun JQuery.scrollSpy(): JQuery = this.asDynamic().scrollSpy() /* extending interface from autocomplete.d.ts */ inline fun JQuery.scrollSpy(method: Any): JQuery = this.asDynamic().scrollSpy(method)
0
Kotlin
0
0
6865eacb00ddee4417ace11de847be008e9e28bc
900
materializecss-kotlin-types
MIT License
src/main/kotlin/net/fabricmc/example/server/lives/PlayerLives.kt
DasPhiller
853,029,836
false
{"Kotlin": 9671, "Java": 8520}
package net.fabricmc.example.server.lives import net.minecraft.server.network.ServerPlayerEntity import net.minecraft.sound.SoundCategory import net.minecraft.sound.SoundEvent import net.minecraft.sound.SoundEvents import net.minecraft.util.Language.load import net.silkmc.silk.core.text.literalText import net.silkmc.silk.core.text.sendText import java.io.File import java.util.Properties import java.util.UUID private val configFile = File("config.properties") fun saveConfig(key: UUID, value: Double) { val properties = Properties().apply { if (configFile.exists()) { configFile.inputStream().use { load(it) } } setProperty(key.toString(), value.toString()) } configFile.outputStream().use { properties.store(it, "Lives") } } fun getConfigValue(key: UUID): Double? { val properties = Properties() return if (configFile.exists()) { configFile.inputStream().use { properties.load(it) } properties.getProperty(key.toString())?.toDouble() } else { null } } fun sendMessage(player: ServerPlayerEntity, lives: Double) { player.sendText(literalText("-$lives ♥") { color = 0xAA0000 bold = false }) player.playSoundToPlayer(SoundEvent.of(SoundEvents.BLOCK_NOTE_BLOCK_DIDGERIDOO.value().id), SoundCategory.MASTER, 100f, 1f) }
0
Kotlin
0
1
99d2f0269852e6641b88d5c202059d22e7f1c4f9
1,375
Klassenpvp
Creative Commons Zero v1.0 Universal
lib-moshi/src/main/java/net/codefeet/lemmyandroidclient/hotfix/RegistrationModeHotfix.kt
Flex4Reddit
648,927,752
false
null
package net.codefeet.lemmyandroidclient.hotfix import com.squareup.moshi.FromJson import com.squareup.moshi.ToJson import net.codefeet.lemmyandroidclient.gen.types.RegistrationMode /** * Lemmy does not capitalize RegistrationMode values. * * eg: GET /site site_view.local_site.registration_mode */ class RegistrationModeHotfix { companion object { private val enums = RegistrationMode.values().associateBy { it.name.lowercase() } } @ToJson fun toJson(it: RegistrationMode) = it.name.lowercase() @FromJson fun fromJson(it: String) = enums[it.lowercase()] }
0
Kotlin
0
0
8028bbf4fc50d7c945d20c7034d6da2de4b7c0ac
584
lemmy-android-client
MIT License
src/test/aoc2021/Day1Test.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package test.aoc2021 import aoc2021.Day1 import org.junit.Assert.assertEquals import org.junit.Test import resourceAsList class Day1Test { private val exampleInput = """ 199 200 208 210 200 207 240 269 260 263 """.trimIndent().split("\n") @Test fun testPartOneExample1() { val day1 = Day1(exampleInput) assertEquals(7, day1.solvePart1()) } @Test fun partOneRealInput() { val day1 = Day1(resourceAsList("2021/day1.txt")) assertEquals(1688, day1.solvePart1()) } @Test fun testPartTwoExample1() { val day1 = Day1(exampleInput) assertEquals(5, day1.solvePart2()) } @Test fun partTwoRealInput() { val day1 = Day1(resourceAsList("2021/day1.txt")) assertEquals(1728, day1.solvePart2()) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
888
aoc
MIT License
src/test/kotlin/days/Day25Test.kt
nuudles
316,314,995
false
null
package days import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class Day25Test { private val dayTwentyFive = Day25() @Test fun testPartOne() { assertThat(dayTwentyFive.partOne(), `is`(14897079L)) } @Test fun testPartTwo() { assertThat(dayTwentyFive.partTwo(), `is`(Unit)) } }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
379
advent-of-code-2020
Creative Commons Zero v1.0 Universal
app/src/main/java/com/app/nikhil/coroutinesessentials/utils/Constants.kt
nikhilbansal97
192,935,710
false
null
package com.app.nikhil.coroutinesessentials.utils object Constants { const val BUNDLE_KEY_USER = "BUNDLE_KEY_USER" }
0
Kotlin
0
0
f97da0455cc1368d3a5985dd450e5e502d028fcc
121
Github-Client
MIT License
lawnchair/src/app/lawnchair/search/algorithms/data/calculator/internal/Scanner.kt
LawnchairLauncher
83,799,439
false
{"Java": 9665767, "Kotlin": 2674103, "AIDL": 30229, "Python": 17364, "Makefile": 3820, "Shell": 770}
package app.lawnchair.search.algorithms.data.calculator.internal import app.lawnchair.search.algorithms.data.calculator.ExpressionException import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.AMP_AMP import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.ASSIGN import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.BAR_BAR import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.COMMA import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.EOF import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.EQUAL_EQUAL import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.EXPONENT import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.GREATER import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.GREATER_EQUAL import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.IDENTIFIER import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.LEFT_PAREN import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.LESS import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.LESS_EQUAL import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.MINUS import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.MODULO import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.NOT_EQUAL import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.NUMBER import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.PLUS import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.RIGHT_PAREN import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.SLASH import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.SQUARE_ROOT import app.lawnchair.search.algorithms.data.calculator.internal.TokenType.STAR import java.math.MathContext private fun invalidToken(c: Char) { throw ExpressionException("Invalid token '$c'") } internal class Scanner( private val source: String, private val mathContext: MathContext, ) { private val tokens: MutableList<Token> = mutableListOf() private var start = 0 private var current = 0 fun scanTokens(): List<Token> { while (!isAtEnd()) { scanToken() } tokens.add(Token(EOF, "", null)) return tokens } private fun isAtEnd(): Boolean { return current >= source.length } private fun scanToken() { start = current when (val c = advance()) { ' ', '\r', '\t', -> { // Ignore whitespace. } '+' -> addToken(PLUS) '-' -> addToken(MINUS) '*' -> addToken(STAR) '/' -> addToken(SLASH) '%' -> addToken(MODULO) '^' -> addToken(EXPONENT) '√' -> addToken(SQUARE_ROOT) '=' -> if (match('=')) addToken(EQUAL_EQUAL) else addToken(ASSIGN) '!' -> if (match('=')) addToken(NOT_EQUAL) else invalidToken(c) '>' -> if (match('=')) addToken(GREATER_EQUAL) else addToken(GREATER) '<' -> if (match('=')) addToken(LESS_EQUAL) else addToken(LESS) '|' -> if (match('|')) addToken(BAR_BAR) else invalidToken(c) '&' -> if (match('&')) addToken(AMP_AMP) else invalidToken(c) ',' -> addToken(COMMA) '(' -> addToken(LEFT_PAREN) ')' -> addToken(RIGHT_PAREN) else -> { when { c.isDigit() -> number() c.isAlpha() -> identifier() else -> invalidToken(c) } } } } private fun isDigit( char: Char, previousChar: Char = '\u0000', nextChar: Char = '\u0000', ): Boolean { return char.isDigit() || when (char) { '.' -> true 'e', 'E' -> previousChar.isDigit() && (nextChar.isDigit() || nextChar == '+' || nextChar == '-') '+', '-' -> (previousChar == 'e' || previousChar == 'E') && nextChar.isDigit() else -> false } } private fun number() { while (peek().isDigit()) advance() if (isDigit(peek(), peekPrevious(), peekNext())) { advance() while (isDigit(peek(), peekPrevious(), peekNext())) advance() } val value = source .substring(start, current) .toBigDecimal(mathContext) addToken(NUMBER, value) } private fun identifier() { while (peek().isAlphaNumeric()) advance() addToken(IDENTIFIER) } private fun advance() = source[current++] private fun peek(): Char { return if (isAtEnd()) { '\u0000' } else { source[current] } } private fun peekPrevious(): Char = if (current > 0) source[current - 1] else '\u0000' private fun peekNext(): Char { return if (current + 1 >= source.length) { '\u0000' } else { source[current + 1] } } private fun match(expected: Char): Boolean { if (isAtEnd()) return false if (source[current] != expected) return false current++ return true } private fun addToken(type: TokenType) = addToken(type, null) private fun addToken(type: TokenType, literal: Any?) { val text = source.substring(start, current) tokens.add(Token(type, text, literal)) } private fun Char.isAlphaNumeric() = isAlpha() || isDigit() private fun Char.isAlpha() = this in 'a'..'z' || this in 'A'..'Z' || this == '_' private fun Char.isDigit() = this == '.' || this in '0'..'9' }
388
Java
1200
9,200
d91399d2e4c6acbeef9c0704043f269115bb688b
5,874
lawnchair
Apache License 2.0
app/src/main/java/com/ramiyon/soulmath/presentation/ui/material/onboard/screens/second/MaterialLearningPurposeBottomSheetFragment.kt
KylixEza
482,724,913
false
{"Kotlin": 253697}
package com.ramiyon.soulmath.presentation.ui.material.onboard.screens.second import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.ramiyon.soulmath.databinding.FragmentMaterialLearningPurposeBottomSheetBinding import com.ramiyon.soulmath.domain.model.material.MaterialLearningPurpose import com.ramiyon.soulmath.presentation.adapter.LearningPurposeAdapter import com.ramiyon.soulmath.presentation.ui.material.onboard.MaterialOnBoardViewModel import com.ramiyon.soulmath.util.Constanta.ARG_MATERIAL_ID import com.ramiyon.soulmath.util.Resource import com.ramiyon.soulmath.util.ResourceStateCallback import kotlinx.coroutines.flow.collect import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.sharedViewModel class MaterialLearningPurposeBottomSheetFragment : BottomSheetDialogFragment() { private val viewModel by sharedViewModel<MaterialOnBoardViewModel>() private val adapter by inject<LearningPurposeAdapter>() private var _binding: FragmentMaterialLearningPurposeBottomSheetBinding? = null private val binding get() = _binding private var materialId: String? = null companion object { fun getInstance(materialId: String) = MaterialLearningPurposeBottomSheetFragment().apply { arguments = Bundle().apply { putString(ARG_MATERIAL_ID, materialId) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { materialId = it.getString(ARG_MATERIAL_ID) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentMaterialLearningPurposeBottomSheetBinding.inflate(layoutInflater, container, false) return binding?.root } @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.apply { rvLearningPurpose.apply { adapter = [email protected] layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) } } viewModel.getDummyMaterialLearningPurpose(materialId!!).let { binding?.apply { tvLearningPurposeChapter.text = "Tujuan Pembelajaran Bab ${it.chapter}" adapter.submitData(it.purposes) } } /*lifecycleScope.launchWhenStarted { viewModel.learningPurposeState.collect { when(it) { is Resource.Loading -> materialLearningPurpose.onResourceLoading() is Resource.Success -> materialLearningPurpose.onResourceSuccess(it.data!!) is Resource.Error -> materialLearningPurpose.onResourceError(it.message!!) else -> materialLearningPurpose.onNeverFetched() } } }*/ } override fun onDestroyView() { _binding = null super.onDestroyView() } private val materialLearningPurpose = object : ResourceStateCallback<MaterialLearningPurpose>() { override fun onResourceLoading() { } override fun onResourceSuccess(data: MaterialLearningPurpose) { lifecycleScope.launchWhenStarted { viewModel.learningPurpose.collect { binding?.apply { tvLearningPurposeChapter.text = "Tujuan Pembelajaran Bab ${it.chapter}" adapter.submitData(it.purposes) } } } } } }
0
Kotlin
0
0
7f7106b6bee4f09da9b1395a441d9f5b2b9a6da7
4,064
SoulMath
Apache License 2.0
common/presentation/src/main/java/com/viplearner/common/presentation/component/ProgressDialog.kt
VIPlearner
678,766,501
false
{"Kotlin": 272893}
package com.viplearner.common.presentation.component import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment.Companion.Center import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @Composable fun ProgressDialog( modifier: Modifier = Modifier ) { val progressValue = 1f val infiniteTransition = rememberInfiniteTransition() val progressAnimationValue by infiniteTransition.animateFloat( initialValue = 0.0f, targetValue = progressValue, animationSpec = infiniteRepeatable(animation = tween(900)) ) Box( modifier = modifier .fillMaxSize() .background(color = Color.Transparent), contentAlignment = Center ) { CircularProgressIndicator( progress = progressAnimationValue, modifier = Modifier .wrapContentSize(), color = Color.Red.copy(alpha = 0.8f) ) } }
0
Kotlin
0
0
becf4c8e908c26d578aa8387a8b9aee88d60ef27
1,494
VIPNotes
MIT License
core/src/main/java/mastodon4j/api/method/FollowsMethod.kt
takke
89,424,966
true
{"Gradle": 6, "YAML": 2, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Java": 4, "Kotlin": 119, "JSON": 26, "TOML": 1, "INI": 1}
package mastodon4j.api.method import mastodon4j.MastodonClient import mastodon4j.MastodonRequest import mastodon4j.Parameter import mastodon4j.api.entity.Account import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.toRequestBody /** * See more https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#follows */ class FollowsMethod(private val client: MastodonClient) { /** * POST /api/v1/follows * @param uri: username@domain of the person you want to follow */ fun postRemoteFollow(uri: String): MastodonRequest<Account> { val parameters = Parameter() .append("uri", uri) .build() return MastodonRequest<Account>( { client.post( "/api/v1/follows", parameters .toRequestBody("application/x-www-form-urlencoded; charset=utf-8".toMediaTypeOrNull()) ) }, { client.getSerializer().fromJson(it, Account::class.java) } ) } }
2
Kotlin
0
1
861bc0a1f957d3893fb48e377b6904e32b89e6a8
1,115
mastodon4j
MIT License
app/src/main/java/com/tech/weatherforecast/features/weatherforecast/domain/GetWeatherForecastUseCase.kt
felipe-silvestre-morais
191,602,754
false
null
package com.tech.weatherforecast.features.weatherforecast.domain import androidx.lifecycle.LiveData import androidx.lifecycle.Transformations import com.tech.weatherforecast.model.WeatherForecast import com.tech.weatherforecast.repository.WeatherRepository /** * Use case that gets a [LiveData<WeatherForecast>] * and makes some specific logic actions on it. * * In this Use Case, I'm just doing nothing... ¯\_(ツ)_/¯ */ class GetWeatherForecastUseCase(private val repository: WeatherRepository) { operator fun invoke(): LiveData<WeatherForecast> { return Transformations.map(repository.getWeatherForecast()) { it } } }
0
Kotlin
0
0
8955d6d4a0dc02499a6b27feaa0f20ad0900664e
662
WeatherForecast-app
MIT License
app/src/main/kotlin/com/markodevcic/newsreader/sync/SyncUseCase.kt
deva666
108,725,368
false
null
package com.markodevcic.newsreader.sync import com.markodevcic.newsreader.data.Article import com.markodevcic.newsreader.data.Source interface SyncUseCase { suspend fun downloadSourcesAsync(categories: Collection<String>) suspend fun downloadArticlesAsync(source: Source): Int suspend fun search(query: String): List<Article> }
1
Kotlin
3
22
f10a6a60160f84e823157a61c7b6bfd5b73d2f11
333
NewsReader
MIT License
src/main/kotlin/com/solarexsoft/kotlinexercise/K2.5.kt
flyfire
113,817,538
false
{"Kotlin": 136532, "Java": 25581, "HTML": 257}
package com.solarexsoft.kotlinexercise /** * Created by houruhou on 2018/11/6. * Desc: */ val arrayOfInt : IntArray = intArrayOf(1, 2, 3) val arrayOfChar : CharArray = charArrayOf('a', 'b', 'c') val arrayOfString :Array<String> = Array(3){i -> "No.$i" } val arrayOfString2 :Array<String> = arrayOf("solarex", "flyfire") fun main(args: Array<String>) { println(arrayOfString.size) println(arrayOfString2.size) println(arrayOfChar.joinToString("-")) println(arrayOfInt.slice(0 until 1)) println(arrayOfInt.slice(0..1)) println(arrayOfString[1]) println(arrayOfString::class.java.simpleName) println(arrayOfInt::class.java.simpleName) val b = arrayOfChar::class val c = arrayOfChar.javaClass val d = arrayOfChar.javaClass.kotlin println(b) println(c) println(d) }
0
Kotlin
0
0
d5f0238c6f54539d1fea56bca206c808b0351260
821
JavaWithKotlin
Apache License 2.0
yandex-mapkit-kmp/src/commonMain/kotlin/ru/sulgik/mapkit/map/ClusterTapListener.kt
SuLG-ik
813,953,018
false
{"Kotlin": 321441}
package ru.sulgik.mapkit.map import ru.sulgik.mapkit.geometry.Cluster public expect abstract class ClusterTapListener() { public abstract fun onClusterTap(cluster: Cluster): Boolean } public inline fun ClusterTapListener(crossinline onClusterTap: (cluster: Cluster) -> Boolean): ClusterTapListener { return object : ClusterTapListener() { override fun onClusterTap(cluster: Cluster): Boolean { return onClusterTap.invoke(cluster) } } }
0
Kotlin
1
17
2d292b701adb2c538f8cd3ddf614250f9d6a444d
480
yandex-mapkit-kmp
Apache License 2.0
app/src/main/java/com/cyrilpillai/userful/db/entity/Name.kt
cyrilpillai
131,496,352
false
null
package com.cyrilpillai.userful.db.entity import com.google.gson.annotations.SerializedName data class Name( @SerializedName("title") val salutation: String, @SerializedName("first") val firstName: String, @SerializedName("last") val lastName: String )
0
Kotlin
0
0
f85f52ae1acaf46fac680fcfd6df45f1661497c5
278
Userful
Apache License 2.0
app/src/main/java/ru/kovsh/tasku/ui/mainMenu/view/FAB.kt
KovshefulCoder
670,538,720
false
null
package ru.kovsh.tasku.ui.mainMenu.view import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.FloatingActionButton import androidx.compose.material.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.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import ru.kovsh.tasku.R import ru.kovsh.tasku.ui.theme.AccentBlue import ru.kovsh.tasku.ui.theme.DarkBlueBackground900 import ru.kovsh.tasku.ui.theme.PlaceholderText import ru.kovsh.tasku.ui.theme.typography import kotlin.math.roundToInt @Composable fun FAB( onFabClick: () -> Unit = {}, onFabChange: (Float, Float) -> Unit, onFabStart: () -> Unit, onFabEnd: () -> Unit, modifier: Modifier = Modifier, focusRequester: FocusRequester = FocusRequester(), ) { val fabX = remember { mutableStateOf(0f) } val fabY = remember { mutableStateOf(0f) } val xPosition = remember { mutableStateOf(0f) } val yPosition = remember { mutableStateOf(0f) } FloatingActionButton( onClick = onFabClick, modifier = modifier .padding(vertical = 8.dp) .size(72.dp) .offset { IntOffset(fabX.value.roundToInt(), fabY.value.roundToInt()) } .pointerInput(Unit) { detectDragGestures( onDragStart = { onFabStart() }, onDragEnd = { fabX.value = 0f fabY.value = 0f xPosition.value = 0f yPosition.value = 0f onFabEnd() focusRequester.requestFocus() }, ) { change, dragAmount -> change.consume() if (fabX.value + dragAmount.x < 0) fabX.value += dragAmount.x if (fabY.value + dragAmount.y < 0) fabY.value += dragAmount.y } } .onGloballyPositioned { coordinates -> xPosition.value = coordinates.positionInRoot().x yPosition.value = coordinates.positionInRoot().y //Log.i("FABonGloballyPositioned", "x: $xPosition, y: $yPosition") //Log.i("FABonGloballyPositioned", "fabX: ${fabX.value}, fabY: ${fabY.value}") if (fabX.value == 0f && fabY.value == 0f) onFabChange(0f, 0f) else onFabChange(xPosition.value, yPosition.value) }, backgroundColor = AccentBlue, ) { Image( painter = painterResource(id = R.drawable.ic_fab), contentDescription = "FAB", ) } } @Composable fun TextFieldPlaceholderUnderFab( onAddNewArea: (String) -> Unit, height: Dp = 15.dp, focusRequester: FocusRequester ) { var placeholderDisplayed by remember { mutableStateOf(true) } val text = remember { mutableStateOf("") } val placeholder = when (text.value) { "" -> stringResource(id = R.string.placeholder_text_textfield_under_fab) + stringResource(id = R.string.ellipsis) else -> "" } Box( modifier = Modifier .fillMaxWidth() .height(height) .background(DarkBlueBackground900), contentAlignment = Alignment.CenterStart ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start, modifier = Modifier.padding(horizontal = 8.dp) ) { AreaImage( modifier = Modifier .weight(1f, false) .fillMaxWidth(), areaName = text.value ) BasicTextField( value = text.value, onValueChange = { placeholderDisplayed = it.isEmpty() text.value = it }, modifier = Modifier .fillMaxWidth() .background(DarkBlueBackground900) .weight(9f) .focusRequester(focusRequester), keyboardOptions = KeyboardOptions( imeAction = ImeAction.Done ), keyboardActions = KeyboardActions( onDone = { onAddNewArea(text.value) } ), singleLine = true, cursorBrush = SolidColor(AccentBlue), textStyle = typography.subtitle2, decorationBox = { innerTextField -> Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Box( modifier = Modifier .weight(1f) .fillMaxWidth() ) { if (placeholderDisplayed) { Text( text = placeholder, style = typography.body1.copy( color = PlaceholderText, fontStyle = FontStyle.Italic ) ) } innerTextField() } } } ) } } }
0
Kotlin
0
0
5b4a23217599e03b8c69bcde10295803cca728d5
7,254
Tasku
Apache License 2.0
libs/designsystem/src/main/kotlin/com/dmdiaz/currency/libs/designsystem/components/OverlappingRow.kt
dmdiaz4
338,934,852
false
{"Kotlin": 258525}
/* * MIT License * * Copyright (c) 2024 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdiaz.currency.libs.designsystem.components import androidx.annotation.FloatRange import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.MeasurePolicy /** * overlappingFactor decides how much of each child composable will be * visible before next one overlaps it 1.0 means completely visible * 0.7 means 70% 0.5 means 50% visible and so on */ @Composable fun OverlappingRow( modifier: Modifier = Modifier, @FloatRange(from = 0.1,to = 1.0) widthOverlapFactor:Float = 0.5f, @FloatRange(from = 0.1,to = 1.0) heightOverlapFactor:Float = 0.5f, content: @Composable () -> Unit, ){ val measurePolicy = overlappingRowMeasurePolicy( widthOverlapFactor = widthOverlapFactor, heightOverlapFactor = heightOverlapFactor ) Layout(measurePolicy = measurePolicy, content = content, modifier = modifier ) } private fun overlappingRowMeasurePolicy(widthOverlapFactor: Float, heightOverlapFactor: Float) = MeasurePolicy { measurables, constraints -> val placeables = measurables.map { measurable -> measurable.measure(constraints)} val height = (placeables.subList(1,placeables.size).sumOf { it.height }* heightOverlapFactor + placeables[0].height).toInt() val width = (placeables.subList(1,placeables.size).sumOf { it.width }* widthOverlapFactor + placeables[0].width).toInt() layout(width,height) { var xPos = 0 var yPos = 0 for (placeable in placeables) { placeable.placeRelative(xPos, yPos, 0f) xPos += (placeable.width * widthOverlapFactor).toInt() yPos += (placeable.height * heightOverlapFactor).toInt() } } }
0
Kotlin
0
1
4b62e68e15130737e98587c38b9dcc05e0a48b46
2,897
Currency
MIT License
app/src/main/java/com/inju/dayworryandroid/worry/worryDetail/WorryDetailViewModel.kt
inju2403
286,212,922
false
null
package com.inju.dayworryandroid.worry.worryDetail import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.inju.dayworryandroid.model.pojo.Contents import com.inju.dayworryandroid.model.pojo.Worry import com.inju.dayworryandroid.model.repository.IDayWorryRepository import com.inju.dayworryandroid.utils.BaseViewModel import kotlinx.coroutines.launch import okhttp3.MultipartBody import kotlin.coroutines.CoroutineContext class WorryDetailViewModel( private val repo: IDayWorryRepository, uiContext: CoroutineContext ): BaseViewModel<WorryDetailEvent>(uiContext) { private val worryState = MutableLiveData<Worry>() val worry: LiveData<Worry> get() = worryState fun initWorry() { worryState.value = Worry() } fun getWorryById(postId: Long) = launch { worryState.value = repo.getWorryById(postId) } fun addOrUpdateWorry(userId: String, tageName: String) = launch { var contents = Contents( worry.value!!.content, worry.value!!.postId, worry.value!!.postImage, tageName, worry.value!!.title, userId) repo.addOrUpdateWorry(contents) } fun postImage(file: MultipartBody.Part) = launch { Log.d("로그그", "$file") worry.value!!.postImage = repo.postImage(file) } fun deleteWorry(id: Long) = launch { repo.deleteWorry(id) } fun setWorryTitle(newTitle: String) { worryState.value!!.title = newTitle } fun setWorryContent(newContent: String) { worryState.value!!.content = newContent } override fun handleEvent(event: WorryDetailEvent) { TODO("Not yet implemented") } }
0
Kotlin
1
6
7069d517b6ba9ca9a645583835f7b4192e3c8c24
1,821
DayWorry
Apache License 2.0
app/src/main/java/com/vv/nasapod/ui/npod/NasaPODViewModelFactory.kt
vishalvn
275,745,892
false
null
package com.vv.nasapod.ui.npod import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import javax.inject.Inject @Suppress("UNCHECKED_CAST") class NasaPODViewModelFactory @Inject constructor( private val nasaAPODRepository: NasaPODRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return NasaPODViewModel( nasaAPODRepository ) as T } }
1
null
1
1
3d9034b8f811151ca20411eb790b58a2b14d870e
459
Nasa-pic-of-the-day
Apache License 2.0
core/common/src/dev/programadorthi/routing/core/RouteMethod.kt
programadorthi
626,174,472
false
null
package dev.programadorthi.routing.core public interface RouteMethod { public val value: String public companion object Empty : RouteMethod { override val value: String = "EMPTY" } }
0
Kotlin
2
40
e25ae8274a1b76c6471e3e26fe2ab98f591fc49b
206
kotlin-routing
Apache License 2.0
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/dccreissuance/core/processor/DccReissuanceProcessor.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.dccreissuance.core.processor import de.rki.coronawarnapp.ccl.dccwalletinfo.model.CertificateReissuance import de.rki.coronawarnapp.dccreissuance.core.error.DccReissuanceException import de.rki.coronawarnapp.dccreissuance.core.server.DccReissuanceServer import de.rki.coronawarnapp.dccreissuance.core.server.data.DccReissuanceResponse import de.rki.coronawarnapp.tag import timber.log.Timber import javax.inject.Inject class DccReissuanceProcessor @Inject constructor( private val dccReissuanceServer: DccReissuanceServer ) { @Throws(DccReissuanceException::class) suspend fun requestDccReissuance(dccReissuanceDescriptor: CertificateReissuance): DccReissuanceResponse { Timber.tag(TAG).d("Requesting Dcc Reissuance") return dccReissuanceDescriptor.callApi().also { Timber.tag(TAG).d("Returning response") } } private suspend fun CertificateReissuance.callApi(): DccReissuanceResponse { Timber.tag(TAG).d("Call DCC Reissuance API") return dccReissuanceServer.requestDccReissuance( action = ACTION_RENEW, certificates = certificates ) } private val CertificateReissuance.certificates: List<String> get() { val certs = mutableListOf(certificateToReissue) certs.addAll(accompanyingCertificates) return certs.map { it.certificateRef.barcodeData } } companion object { private val TAG = tag<DccReissuanceProcessor>() private const val ACTION_RENEW = "renew" } }
2
Kotlin
516
2,493
aa450b97e701f6481019681cc6f5a03b7dcc6e86
1,559
cwa-app-android
Apache License 2.0
foodbanks/src/main/java/com/yuriisurzhykov/foodbanks/data/city/cache/CityWithPointsCache.kt
yuriisurzhykov
524,002,724
false
{"Kotlin": 274520, "Java": 1023}
package com.yuriisurzhykov.foodbanks.data.city.cache import androidx.room.Embedded import androidx.room.Relation import com.yuriisurzhykov.foodbanks.data.point.cache.PointCache data class CityWithPointsCache( @Embedded val city: CityCache, @Relation( parentColumn = "nameCode", entityColumn = "cityCodeId" ) var points: List<PointCache> = emptyList() )
1
Kotlin
0
2
f9b12ffa6dafe283dc8738e7f0eeb0328f7f547b
386
PointDetector
MIT License
defitrack-protocols/aave/src/main/java/io/defitrack/protocol/aave/v2/contract/LendingPoolContract.kt
decentri-fi
426,174,152
false
null
package io.defitrack.protocol.aave.v2.contract import io.defitrack.abi.TypeUtils.Companion.toAddress import io.defitrack.abi.TypeUtils.Companion.toUint16 import io.defitrack.abi.TypeUtils.Companion.toUint256 import io.defitrack.evm.contract.BlockchainGateway import io.defitrack.evm.contract.EvmContract import org.web3j.abi.datatypes.Function import java.math.BigInteger class LendingPoolContract(blockchainGateway: BlockchainGateway, abi: String, address: String) : EvmContract( blockchainGateway, abi, address ) { fun depositFunction(asset: String, amount: BigInteger): Function { return createFunctionWithAbi( "deposit", listOf( asset.toAddress(), amount.toUint256(), "0000000000000000000000000000000000000000".toAddress(), BigInteger.ZERO.toUint16() ), emptyList() ) } }
17
Kotlin
6
9
f7c65aa58bec3268101d90fc538c3f8bd0c29093
930
defi-hub
MIT License
app/src/main/kotlin/dev/aaa1115910/bv/util/Prefs.kt
aaa1115910
571,702,700
false
null
package dev.aaa1115910.bv.util import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.floatPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import de.schnettler.datastore.manager.PreferenceRequest import dev.aaa1115910.bv.BVApp import dev.aaa1115910.bv.entity.Resolution import dev.aaa1115910.bv.entity.VideoCodec import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import mu.KotlinLogging import java.util.Date import kotlin.math.roundToInt object Prefs { private val dsm = BVApp.dataStoreManager val logger = KotlinLogging.logger { } var isLogin: Boolean get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefIsLoginRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefIsLoginKey, value) } var uid: Long get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefUidRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefUidKey, value) } var sid: String get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefSidRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefSidKey, value) } var sessData: String get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefSessDataRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefSessDataKey, value) } var biliJct: String get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefBiliJctRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefBiliJctKey, value) } var uidCkMd5: String get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefUidCkMd5Request).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefUidCkMd5Key, value) } var tokenExpiredData: Date get() = Date(runBlocking { dsm.getPreferenceFlow(PrefKeys.prefTokenExpiredDateRequest).first() }) set(value) = runBlocking { dsm.editPreference(PrefKeys.prefTokenExpiredDateKey, value.time) } var defaultQuality: Int get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefDefaultQualityRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefDefaultQualityKey, value) } var defaultDanmakuSize: Int get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefDefaultDanmakuSizeRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefDefaultDanmakuSizeKey, value) } var defaultDanmakuTransparency: Int get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefDefaultDanmakuTransparencyRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefDefaultDanmakuTransparencyKey, value) } var defaultDanmakuEnabled: Boolean get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefDefaultDanmakuEnabledRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefDefaultDanmakuEnabledKey, value) } var defaultDanmakuArea: Float get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefDefaultDanmakuAreaRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefDefaultDanmakuAreaKey, value) } var defaultVideoCodec: VideoCodec get() = VideoCodec.fromCode( runBlocking { dsm.getPreferenceFlow(PrefKeys.prefDefaultVideoCodecRequest).first() } ) set(value) = runBlocking { dsm.editPreference(PrefKeys.prefDefaultVideoCodecKey, value.ordinal) } var enableFirebaseCollection: Boolean get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefEnabledFirebaseCollectionRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefEnabledFirebaseCollectionKey, value) } var incognitoMode: Boolean get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefIncognitoModeRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefIncognitoModeKey, value) } var defaultSubtitleFontSize: TextUnit get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefDefaultSubtitleFontSizeRequest).first().sp } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefDefaultSubtitleFontSizeKey, value.value.roundToInt()) } var defaultSubtitleBottomPadding: Dp get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefDefaultSubtitleBottomPaddingRequest).first().dp } set(value) = runBlocking { dsm.editPreference( PrefKeys.prefDefaultSubtitleBottomPaddingKey, value.value.roundToInt() ) } var showFps: Boolean get() = runBlocking { dsm.getPreferenceFlow(PrefKeys.prefShowFpsRequest).first() } set(value) = runBlocking { dsm.editPreference(PrefKeys.prefShowFpsKey, value) } } private object PrefKeys { val prefIsLoginKey = booleanPreferencesKey("il") val prefUidKey = longPreferencesKey("uid") val prefSidKey = stringPreferencesKey("sid") val prefSessDataKey = stringPreferencesKey("sd") val prefBiliJctKey = stringPreferencesKey("bj") val prefUidCkMd5Key = stringPreferencesKey("ucm") val prefTokenExpiredDateKey = longPreferencesKey("ted") val prefDefaultQualityKey = intPreferencesKey("dq") val prefDefaultDanmakuSizeKey = intPreferencesKey("dds") val prefDefaultDanmakuTransparencyKey = intPreferencesKey("ddt") val prefDefaultDanmakuEnabledKey = booleanPreferencesKey("dde") val prefDefaultDanmakuAreaKey = floatPreferencesKey("dda") val prefDefaultVideoCodecKey = intPreferencesKey("dvc") val prefEnabledFirebaseCollectionKey = booleanPreferencesKey("efc") val prefIncognitoModeKey = booleanPreferencesKey("im") val prefDefaultSubtitleFontSizeKey = intPreferencesKey("dsfs") val prefDefaultSubtitleBottomPaddingKey = intPreferencesKey("dsbp") val prefShowFpsKey = booleanPreferencesKey("sf") val prefIsLoginRequest = PreferenceRequest(prefIsLoginKey, false) val prefUidRequest = PreferenceRequest(prefUidKey, 0) val prefSidRequest = PreferenceRequest(prefSidKey, "") val prefSessDataRequest = PreferenceRequest(prefSessDataKey, "") val prefBiliJctRequest = PreferenceRequest(prefBiliJctKey, "") val prefUidCkMd5Request = PreferenceRequest(prefUidCkMd5Key, "") val prefTokenExpiredDateRequest = PreferenceRequest(prefTokenExpiredDateKey, 0) val prefDefaultQualityRequest = PreferenceRequest(prefDefaultQualityKey, Resolution.R1080P.code) val prefDefaultDanmakuSizeRequest = PreferenceRequest(prefDefaultDanmakuSizeKey, 6) val prefDefaultDanmakuTransparencyRequest = PreferenceRequest(prefDefaultDanmakuTransparencyKey, 0) val prefDefaultDanmakuEnabledRequest = PreferenceRequest(prefDefaultDanmakuEnabledKey, true) val prefDefaultDanmakuAreaRequest = PreferenceRequest(prefDefaultDanmakuAreaKey, 1f) val prefDefaultVideoCodecRequest = PreferenceRequest(prefDefaultVideoCodecKey, VideoCodec.AVC.ordinal) val prefEnabledFirebaseCollectionRequest = PreferenceRequest(prefEnabledFirebaseCollectionKey, true) val prefIncognitoModeRequest = PreferenceRequest(prefIncognitoModeKey, false) val prefDefaultSubtitleFontSizeRequest = PreferenceRequest(prefDefaultSubtitleFontSizeKey, 24) val prefDefaultSubtitleBottomPaddingRequest = PreferenceRequest(prefDefaultSubtitleBottomPaddingKey, 12) val prefShowFpsRequest = PreferenceRequest(prefShowFpsKey, false) }
25
Kotlin
71
690
712ad82c0db905f8ebd0d8080328494f9c27c5ff
8,087
bv
MIT License
service/src/test/kotlin/no/nav/su/se/bakover/service/brev/DistribuerBrevServiceTest.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.service.brev import arrow.core.left import arrow.core.right import io.kotest.matchers.shouldBe import no.nav.su.se.bakover.client.ClientError import no.nav.su.se.bakover.client.dokarkiv.DokArkiv import no.nav.su.se.bakover.client.dokdistfordeling.DokDistFordeling import no.nav.su.se.bakover.client.dokdistfordeling.KunneIkkeBestilleDistribusjon import no.nav.su.se.bakover.common.AktørId import no.nav.su.se.bakover.common.Ident import no.nav.su.se.bakover.common.application.journal.JournalpostId import no.nav.su.se.bakover.domain.brev.BrevbestillingId import no.nav.su.se.bakover.domain.brev.Distribusjonstidspunkt import no.nav.su.se.bakover.domain.brev.Distribusjonstype import no.nav.su.se.bakover.domain.brev.KunneIkkeBestilleBrevForDokument import no.nav.su.se.bakover.domain.brev.KunneIkkeJournalføreDokument import no.nav.su.se.bakover.domain.dokument.Dokument import no.nav.su.se.bakover.domain.dokument.DokumentRepo import no.nav.su.se.bakover.domain.dokument.Dokumentdistribusjon import no.nav.su.se.bakover.domain.eksterneiverksettingssteg.JournalføringOgBrevdistribusjon import no.nav.su.se.bakover.domain.person.KunneIkkeHentePerson import no.nav.su.se.bakover.domain.person.Person import no.nav.su.se.bakover.domain.person.PersonService import no.nav.su.se.bakover.domain.sak.SakInfo import no.nav.su.se.bakover.domain.sak.SakService import no.nav.su.se.bakover.test.fixedTidspunkt import no.nav.su.se.bakover.test.sakinfo import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import java.time.Clock import java.util.UUID internal class DistribuerBrevServiceTest { val fnr = sakinfo.fnr val person = Person( ident = Ident( fnr = sakinfo.fnr, aktørId = AktørId(aktørId = "123"), ), navn = Person.Navn(fornavn = "Tore", mellomnavn = null, etternavn = "Strømøy"), ) val distribusjonstype = Distribusjonstype.VIKTIG val distribusjonstidspunkt = Distribusjonstidspunkt.KJERNETID @Test fun `distribuerer brev`() { val dockdistMock = mock<DokDistFordeling> { on { bestillDistribusjon( JournalpostId("journalpostId"), distribusjonstype, distribusjonstidspunkt, ) } doReturn BrevbestillingId("en bestillings id").right() } ServiceOgMocks( dokDistFordeling = dockdistMock, ).distribuerBrevService.distribuerBrev( JournalpostId("journalpostId"), distribusjonstype, distribusjonstidspunkt, ) shouldBe BrevbestillingId("en bestillings id").right() verify(dockdistMock).bestillDistribusjon( JournalpostId("journalpostId"), distribusjonstype, distribusjonstidspunkt, ) } @Test fun `journalfør dokument - finner ikke person`() { val personServiceMock = mock<PersonService> { on { hentPersonMedSystembruker(any()) } doReturn KunneIkkeHentePerson.FantIkkePerson.left() } val dokumentdistribusjon = dokumentdistribusjon() ServiceOgMocks( personService = personServiceMock, ).let { it.distribuerBrevService.journalførDokument( dokumentdistribusjon, it.sakInfo.saksnummer, it.sakInfo.type, it.sakInfo.fnr, ) shouldBe KunneIkkeJournalføreDokument.KunneIkkeFinnePerson.left() verify(personServiceMock).hentPersonMedSystembruker(fnr) it.verifyNoMoreInteraction() } } @Test fun `journalfør dokument - feil ved journalføring`() { val personServiceMock = mock<PersonService> { on { hentPersonMedSystembruker(any()) } doReturn person.right() } val dokarkivMock = mock<DokArkiv> { on { opprettJournalpost(any()) } doReturn ClientError(500, "kek").left() } val dokumentdistribusjon = dokumentdistribusjon() ServiceOgMocks( personService = personServiceMock, dokArkiv = dokarkivMock, ).let { it.distribuerBrevService.journalførDokument( dokumentdistribusjon, it.sakInfo.saksnummer, it.sakInfo.type, it.sakInfo.fnr, ) shouldBe KunneIkkeJournalføreDokument.FeilVedOpprettelseAvJournalpost.left() verify(personServiceMock).hentPersonMedSystembruker(fnr) verify(dokarkivMock).opprettJournalpost(any()) it.verifyNoMoreInteraction() } } @Test fun `journalfør dokument - dokument allerede journalført`() { val personServiceMock = mock<PersonService> { on { hentPersonMedSystembruker(any()) } doReturn person.right() } val dokumentdistribusjon = dokumentdistribusjon() .copy(journalføringOgBrevdistribusjon = JournalføringOgBrevdistribusjon.Journalført(JournalpostId("done"))) ServiceOgMocks( personService = personServiceMock, ).let { it.distribuerBrevService.journalførDokument( dokumentdistribusjon, it.sakInfo.saksnummer, it.sakInfo.type, it.sakInfo.fnr, ) shouldBe dokumentdistribusjon.right() verify(personServiceMock).hentPersonMedSystembruker(fnr) it.verifyNoMoreInteraction() } } @Test fun `journalfør dokument - happy`() { val personServiceMock = mock<PersonService> { on { hentPersonMedSystembruker(any()) } doReturn person.right() } val dokarkivMock = mock<DokArkiv> { on { opprettJournalpost(any()) } doReturn JournalpostId("happy").right() } val dokumentRepoMock = mock<DokumentRepo>() val dokumentdistribusjon = dokumentdistribusjon() val expected = dokumentdistribusjon .copy(journalføringOgBrevdistribusjon = JournalføringOgBrevdistribusjon.Journalført(JournalpostId("happy"))) ServiceOgMocks( personService = personServiceMock, dokArkiv = dokarkivMock, dokumentRepo = dokumentRepoMock, ).let { it.distribuerBrevService.journalførDokument( dokumentdistribusjon, it.sakInfo.saksnummer, it.sakInfo.type, it.sakInfo.fnr, ) shouldBe expected.right() verify(personServiceMock).hentPersonMedSystembruker(fnr) verify(dokarkivMock).opprettJournalpost(any()) verify(dokumentRepoMock).oppdaterDokumentdistribusjon(expected) it.verifyNoMoreInteraction() } } @Test fun `distribuer dokument - ikke journalført`() { val dokumentdistribusjon = dokumentdistribusjon() ServiceOgMocks().let { it.distribuerBrevService.distribuerDokument(dokumentdistribusjon) shouldBe KunneIkkeBestilleBrevForDokument.MåJournalføresFørst.left() it.verifyNoMoreInteraction() } } @Test fun `distribuer dokument - allerede distribuert`() { val dokumentdistribusjon = dokumentdistribusjon() .copy( journalføringOgBrevdistribusjon = JournalføringOgBrevdistribusjon.JournalførtOgDistribuertBrev( JournalpostId("very"), BrevbestillingId("happy"), ), ) ServiceOgMocks().let { it.distribuerBrevService.distribuerDokument(dokumentdistribusjon) shouldBe dokumentdistribusjon.right() it.verifyNoMoreInteraction() } } @Test fun `distribuer dokument - feil ved bestilling av brev`() { val dokDistMock = mock<DokDistFordeling> { on { bestillDistribusjon(any(), any(), any()) } doReturn KunneIkkeBestilleDistribusjon.left() } val dokumentdistribusjon = dokumentdistribusjon() .copy(journalføringOgBrevdistribusjon = JournalføringOgBrevdistribusjon.Journalført(JournalpostId("sad"))) ServiceOgMocks( dokDistFordeling = dokDistMock, ).let { it.distribuerBrevService.distribuerDokument(dokumentdistribusjon) shouldBe KunneIkkeBestilleBrevForDokument.FeilVedBestillingAvBrev.left() verify(dokDistMock).bestillDistribusjon( JournalpostId("sad"), Distribusjonstype.VEDTAK, distribusjonstidspunkt, ) it.verifyNoMoreInteraction() } } @Test fun `distribuer dokument - happy`() { val dokDistMock = mock<DokDistFordeling> { on { bestillDistribusjon(any(), any(), any()) } doReturn BrevbestillingId("happy").right() } val dokumentRepoMock = mock<DokumentRepo>() val dokumentdistribusjon = dokumentdistribusjon() .copy(journalføringOgBrevdistribusjon = JournalføringOgBrevdistribusjon.Journalført(JournalpostId("very"))) val expected = dokumentdistribusjon .copy( journalføringOgBrevdistribusjon = JournalføringOgBrevdistribusjon.JournalførtOgDistribuertBrev( JournalpostId("very"), BrevbestillingId("happy"), ), ) ServiceOgMocks( dokDistFordeling = dokDistMock, dokumentRepo = dokumentRepoMock, ).let { it.distribuerBrevService.distribuerDokument(dokumentdistribusjon) shouldBe expected.right() verify(dokDistMock).bestillDistribusjon( JournalpostId("very"), Distribusjonstype.VEDTAK, distribusjonstidspunkt, ) verify(dokumentRepoMock).oppdaterDokumentdistribusjon(expected) it.verifyNoMoreInteraction() } } private data class ServiceOgMocks( val dokArkiv: DokArkiv = mock(), val dokDistFordeling: DokDistFordeling = mock(), val dokumentRepo: DokumentRepo = mock(), val sakService: SakService = mock(), val personService: PersonService = mock(), val clock: Clock = mock(), val sakInfo: SakInfo = sakinfo, ) { val distribuerBrevService = DistribuerBrevService( sakService = sakService, dokumentRepo = dokumentRepo, dokDistFordeling = dokDistFordeling, personService = personService, dokArkiv = dokArkiv, ) fun verifyNoMoreInteraction() { verifyNoMoreInteractions( dokArkiv, dokDistFordeling, dokumentRepo, sakService, personService, ) } } private fun dokumentdistribusjon(): Dokumentdistribusjon = Dokumentdistribusjon( id = UUID.randomUUID(), opprettet = fixedTidspunkt, dokument = Dokument.MedMetadata.Vedtak( id = UUID.randomUUID(), opprettet = fixedTidspunkt, tittel = "tittel", generertDokument = "".toByteArray(), generertDokumentJson = "{}", metadata = Dokument.Metadata( sakId = sakinfo.sakId, bestillBrev = true, ), ), journalføringOgBrevdistribusjon = JournalføringOgBrevdistribusjon.IkkeJournalførtEllerDistribuert, ) }
0
Kotlin
0
1
d7157394e11b5b3c714a420a96211abb0a53ea45
11,642
su-se-bakover
MIT License
app/src/main/java/de/christinecoenen/code/zapp/utils/video/ScreenDimmingHandler.kt
mediathekview
68,289,398
false
null
package de.christinecoenen.code.zapp.utils.video import android.view.View import com.google.android.exoplayer2.Player import java.lang.ref.WeakReference /** * Allows the screen to turn off as soon as video playback finishes * or pauses. */ internal class ScreenDimmingHandler : Player.Listener { private var viewToKeepScreenOn: WeakReference<View?> = WeakReference(null) private var isIdleOrEnded = false private var isPaused = false /** * The given screen will only be kept on as long as any video is playing. */ fun setScreenToKeepOn(view: View) { viewToKeepScreenOn = WeakReference(view) applyScreenDimming() } override fun onPlaybackStateChanged(playbackState: Int) { isIdleOrEnded = playbackState == Player.STATE_IDLE || playbackState == Player.STATE_ENDED applyScreenDimming() } override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) { isPaused = !playWhenReady applyScreenDimming() } private fun applyScreenDimming() { viewToKeepScreenOn.get()?.keepScreenOn = !(isPaused || isIdleOrEnded) } }
57
null
33
201
7a3cadf5a8b8efd1bb5cb9a0d6175c995e2f5aaf
1,059
zapp
MIT License
lsp/src/main/kotlin/org/ksharp/lsp/client/ClientLogger.kt
ksharp-lang
573,931,056
false
{"Kotlin": 1438845, "Java": 49163, "TypeScript": 3203}
package org.ksharp.lsp.client import org.eclipse.lsp4j.MessageParams import org.eclipse.lsp4j.MessageType object ClientLogger { fun info(message: String) { withClient { it.logMessage(MessageParams(MessageType.Info, message)) } } }
3
Kotlin
0
0
a76897b8a34b4f889c64113f1f7af73bbbfed570
269
ksharp-kt
Apache License 2.0
sdk/src/main/kotlin/io/rover/sdk/ui/containers/RoverActivity.kt
RoverPlatform
55,724,334
false
null
package io.rover.sdk.ui.containers import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Parcelable import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import android.view.Menu import io.rover.sdk.services.EmbeddedWebBrowserDisplay import io.rover.sdk.R import io.rover.sdk.Rover import io.rover.sdk.logging.log import io.rover.sdk.platform.asAndroidUri import io.rover.sdk.platform.whenNotNull import io.rover.sdk.streams.androidLifecycleDispose import io.rover.sdk.streams.subscribe import io.rover.sdk.ui.concerns.MeasuredBindableView import io.rover.sdk.ui.RoverView import io.rover.sdk.ui.RoverViewModel import io.rover.sdk.ui.RoverViewModelInterface import io.rover.sdk.ui.navigation.ExperienceExternalNavigationEvent /** * This can display a Rover experience in an Activity, self-contained. * * You may use this either as a subclass for your own Activity, or as a template for embedding * a Rover [RoverView] in your own Activities. */ open class RoverActivity : AppCompatActivity() { private val experienceId: String? by lazy { this.intent.getStringExtra("EXPERIENCE_ID") } private val experienceUrl: String? by lazy { this.intent.getStringExtra("EXPERIENCE_URL") } private val useDraft: Boolean by lazy { this.intent.getBooleanExtra("USE_DRAFT", false) } private val initialScreenId: String? by lazy { intent.getStringExtra("INITIAL_SCREEN_ID") } private val campaignId: String? get() = this.intent.getStringExtra("CAMPAIGN_ID") /*** * Open a URI directly (not to be confused with a so-called Custom Tab, which is a web browser * embedded within the app). */ protected open fun openUri(uri: Uri) { val intent = Intent(Intent.ACTION_VIEW, uri) this.startActivity(intent) } /** * This method is responsible for performing external navigation events: that is, navigation * events emitted by an Experience that "break out" of the Experience's intrinsic navigation * flow (ie., moving back and forth amongst Screens). The default implementation handles * exiting the Activity and opening up a web browser. */ private fun dispatchExternalNavigationEvent(externalNavigationEvent: ExperienceExternalNavigationEvent) { when (externalNavigationEvent) { is ExperienceExternalNavigationEvent.Exit -> { finish() } is ExperienceExternalNavigationEvent.OpenUri -> { openUri(externalNavigationEvent.uri.asAndroidUri()) } is ExperienceExternalNavigationEvent.PresentWebsite -> { webDisplay?.intentForViewingWebsiteViaEmbeddedBrowser( externalNavigationEvent.url.toString() ).whenNotNull { intent -> ContextCompat.startActivity( this, intent, null ) } } is ExperienceExternalNavigationEvent.Custom -> { log.w("You have emitted a Custom event: $externalNavigationEvent, but did not handle it in your subclass implementation of RoverActivity.dispatchExternalNavigationEvent()") } } } /** * [RoverViewModel] is responsible for describing the appearance and behaviour of the * experience contents. */ private val experiencesView by lazy { RoverView(this) } /** * Holds the currently set view model, including side-effect behaviour for binding it to the * Experiences View. * * This is a mutable property because it cannot be set up at Activity construction time in the * constructor; at that stage the requesting Intent and its parameters are not available. */ private var roverViewModel: RoverViewModelInterface? = null set(viewModel) { field = viewModel experiencesView.viewModelBinding = viewModel.whenNotNull { MeasuredBindableView.Binding(it) } viewModel ?.events ?.androidLifecycleDispose(this) ?.subscribe( { event -> when (event) { is RoverViewModelInterface.Event.NavigateTo -> { log.v("Received an external navigation event: ${event.externalNavigationEvent}") dispatchExternalNavigationEvent(event.externalNavigationEvent) } } }, { error -> throw(error) } ) } /** * Provides a method for opening URIs with a Custom Chrome Tab. */ private val webDisplay: EmbeddedWebBrowserDisplay? by lazy { val rover = Rover.shared if (rover == null) { log.w("RoverActivity cannot work unless Rover has been initialized.") finish() null } else { rover.webBrowserDisplay } } override fun onBackPressed() { if (roverViewModel != null) { roverViewModel?.pressBack() } else { // default to standard Android back-button behaviour (ie., pop the activity) if our view // model isn't yet available. super.onBackPressed() } } // The View needs to know about the Activity-level window and several other // Activity/Fragment context things in order to temporarily change the backlight. private val toolbarHost by lazy { ActivityToolbarHost(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val rover = Rover.shared if (rover == null) { log.w("RoverActivity cannot work unless Rover has been initialized.") finish() return } // TODO: perhaps this arrangement is not necessary: confirm for sure that it will not pick // up the default theme set on the App (although we can hopefully check that they have an // actionbar-free theme enabled). val displayNoCustomThemeWarningMessage = this.theme.obtainStyledAttributes( intArrayOf(R.attr.displayNoCustomThemeWarningMessage) ).getBoolean(0, false) if (displayNoCustomThemeWarningMessage) { log.w("You have set no theme for RoverActivity (or your optional subclass thereof) in your AndroidManifest.xml.\n" + "In particular, this means the toolbar will not pick up your brand colours.") } setContentView( experiencesView ) // wire up the toolbar host to the RoverView. Note that the activity will be leaked // unless you remember to set it back to null in onDestroy(). experiencesView.toolbarHost = toolbarHost // obtain any possibly saved state for the experience view model. See // onSaveInstanceState. val state: Parcelable? = savedInstanceState?.getParcelable("experienceState") when { experienceId != null -> roverViewModel = experienceViewModel( rover, RoverViewModel.ExperienceRequest.ById(experienceId!!, useDraft = useDraft), campaignId, // obtain any possibly saved state for the experience view model. See // onSaveInstanceState. state, initialScreenId ) experienceUrl != null -> roverViewModel = experienceViewModel( rover, RoverViewModel.ExperienceRequest.ByUrl(experienceUrl!!), campaignId, state, initialScreenId ) else -> { log.w("Please pass either one of EXPERIENCE_ID or EXPERIENCE_URL. Consider using RoverActivity.makeIntent()") } } } override fun onDestroy() { super.onDestroy() experiencesView.toolbarHost = null } private fun experienceViewModel( rover: Rover, experienceRequest: RoverViewModel.ExperienceRequest, campaignId: String?, icicle: Parcelable?, initialScreenId: String? ): RoverViewModelInterface { return Rover.shared?.viewModels?.experienceViewModel(experienceRequest, campaignId, initialScreenId, this.lifecycle) ?: throw RuntimeException("Rover not usable until Rover.initialize has been called.") } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) // RoverView owns the toolbar, this is so RoverView can take your menu and include // it in its internal toolbar. toolbarHost.menu = menu return true } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // grab the state for the Experience view out of its view model and store it in the // activity's own bundle. outState.putParcelable("experienceState", roverViewModel?.state) } companion object { @JvmStatic @JvmOverloads fun makeIntent(packageContext: Context, experienceId: String, campaignId: String? = null, useDraft: Boolean = false, activityClass: Class<out Activity> = RoverActivity::class.java, initialScreenId: String? = null): Intent { return Intent(packageContext, activityClass).apply { putExtra("EXPERIENCE_ID", experienceId) putExtra("CAMPAIGN_ID", campaignId) putExtra("USE_DRAFT", useDraft) putExtra("INITIAL_SCREEN_ID", initialScreenId) } } @JvmStatic @JvmOverloads fun makeIntent(packageContext: Context, experienceUrl: Uri, campaignId: String? = null, activityClass: Class<out Activity> = RoverActivity::class.java, initialScreenId: String? = null): Intent { return Intent(packageContext, activityClass).apply { putExtra("EXPERIENCE_URL", experienceUrl.toString()) putExtra("CAMPAIGN_ID", campaignId) putExtra("INITIAL_SCREEN_ID", initialScreenId) } } } }
16
Java
13
6
1b6e627a1e4b3651d0cc9f6e78f995ed9e4a821a
10,410
rover-android
Apache License 2.0
app/src/test/java/com/example/android/architecture/blueprints/todoapp/statics/TestStaticsUtils.kt
GodDB
441,605,876
true
{"Kotlin": 78683}
package com.example.android.architecture.blueprints.todoapp.statics import com.example.android.architecture.blueprints.todoapp.data.Task import com.example.android.architecture.blueprints.todoapp.statistics.getActiveAndCompletedStats import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import kotlin.test.assertEquals import kotlin.test.assertFails @RunWith(JUnit4::class) class TestStaticsUtils { @Test fun 태스크_1개_일때_태스크_완료가_아닌_상태를_검증한다() { //given val task = listOf<Task>(Task("title", "desc", isCompleted = false)) //when val result = getActiveAndCompletedStats(task) //then assertEquals(result.activeTasksPercent, 100f) assertEquals(result.completedTasksPercent, 0f) } @Test fun 태스크_1개_일때_태스크_완료_상태를_검증한다() { //given val task = listOf<Task>(Task("title", "desc", isCompleted = true)) //when val result = getActiveAndCompletedStats(task) //then assertEquals(result.completedTasksPercent, 100f) assertEquals(result.activeTasksPercent, 0f) } @Test fun 태스크_4개_일때_태스크_1개_완료_상태를_검증한다() { //given val task = listOf<Task>( Task("title", "desc", false), Task("title", "desc", false), Task("title", "desc", false), Task("title", "desc", true) ) //when val result = getActiveAndCompletedStats(task) //then assertEquals(result.completedTasksPercent, 25f) assertEquals(result.activeTasksPercent, 75f) } @Test fun 태스크가_없을때_태스크_완료상태를_검증한다() { //given val task = null //when val result = getActiveAndCompletedStats(task) //then assertEquals(result.activeTasksPercent, 0f) assertEquals(result.completedTasksPercent, 0f) } }
0
Kotlin
0
0
1a31e0328a7ec7236e4383ea24819d500665320e
1,886
android-testing
Apache License 2.0
src/main/kotlin/util/NarrowPeak.kt
weng-lab
247,304,722
false
{"Kotlin": 35427, "Shell": 2486, "Dockerfile": 181}
package util import java.nio.file.Files import java.nio.file.Path import java.util.zip.GZIPInputStream data class Region ( val chromosome: String, val start: Int, val end: Int, val name: String, val score: Int, val strand: Char ) /** * Reads a BED 6+ file and processes the reigons it contains with a user-provided function. * * @param file path to the narrowPeak file to read. * @param lineRange if passed, only reads line numbers within this range. * @param processRegions function called on the complete set of regions when reading is complete. */ fun readBed6File(file: Path, lineRange: IntRange? = null, processRegions: (List<Region>) -> Unit) { val rawInputStream = Files.newInputStream(file) val inputStream = if (file.toString().endsWith(".gz")) GZIPInputStream(rawInputStream) else rawInputStream inputStream.reader().useLines { lines -> val regions = lines .filterIndexed { index, _ -> if (lineRange != null && !lineRange.contains(index)) return@filterIndexed false true } .mapNotNull { line -> val lineParts = line.trim().split("\t") if (lineParts.size < 6) return@mapNotNull null Region( chromosome = lineParts[0], start = lineParts[1].toInt(), end = lineParts[2].toInt(), name = lineParts[3], score = lineParts[4].toInt(), strand = lineParts[5][0] ) }.toList() processRegions(regions) } }
0
Kotlin
0
0
65db8a2187a22c0e70fd5064379d675298548efc
1,631
bam-aggregate-task
MIT License
Module/DebugTools/src/main/java/com/lwh/debugtools/base/item/BaseItem.kt
l-w-h
224,768,316
false
null
package com.lwh.debugtools.base.item import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.lwh.debugtools.base.context.ContextWrap import com.lwh.debugtools.base.holder.BaseViewHolder /** * @author lwh * @Date 2019/10/19 15:07 * @description BaseItem */ abstract class BaseItem { /** * 上下文对象 */ var mContextWrap: ContextWrap? = null /** * 点击方法 */ var onClick: View.OnClickListener? = null /** * 布局id */ abstract fun layoutId(): Int /** * item类型 默认布局Id */ fun getViewType(): Int = layoutId() /** * 获取View */ fun getView(parent: ViewGroup, viewType: Int): View = LayoutInflater.from(parent.context).inflate(layoutId(), parent, false) /** * 局部更新View */ open fun updateView(holder: BaseViewHolder, position: Int, payloads: MutableList<Any>) { updateView(holder, position) } /** * 更新View */ abstract fun updateView(holder: BaseViewHolder, position: Int) /** * 点击方法回调 */ open fun onClick(v: View) { } /** * 差异对比中 areItemsTheSame,获取item中的唯一标识对比 */ open fun uniqueItem(): String? { return null } /** * 差异对比中 areContentsTheSame,item中的唯一标识一致时,判断内容是否一致 */ open fun uniqueContent(): String? { return null } }
1
Kotlin
1
1
cd9ccb97577f17d77884643942a0c642be03dae8
1,389
DebugTools
Apache License 2.0
src/net/the_sinner/unn4m3d/klauncher/components/JavaMap.kt
unn4m3d
76,256,090
false
{"Java": 115773, "Kotlin": 39510, "CSS": 266}
package net.the_sinner.unn4m3d.klauncher.components /** * Created by unn4m3d on 15.12.16. */ fun <T,O>javaMap(item : List<T>, cb : (T) -> O ) = item.map(cb)
1
null
1
1
a29f2597797cc960c1f46b7234a784150387f1ce
160
klauncher
MIT License
data/api/src/commonMain/kotlin/io/github/droidkaigi/confsched2020/data/api/response/ContributorResponse.kt
DroidKaigi
202,978,106
false
null
package io.github.droidkaigi.confsched2020.data.api.response interface ContributorResponse { val contributors: List<ContributorItemResponse> }
46
null
331
785
4c5533e4611d4bf6007284dd1f61db2fc92eb0ae
148
conference-app-2020
Apache License 2.0
idea/tests/testData/compiler/asJava/lightClasses/compilationErrors/TwoOverrides.kt
JetBrains
278,369,660
false
null
// TwoOverrides class TwoOverrides : Iterable<String> { override fun iterator() = null override fun iterator() = null }
179
Kotlin
5640
82
cc81d7505bc3e9ad503d706998ae8026c067e838
129
intellij-kotlin
Apache License 2.0
chart/src/main/java/cn/jingzhuan/lib/chart3/event/OnDrawLineListener.kt
JingZhuanDuoYing
98,616,882
false
null
package cn.jingzhuan.lib.chart3.event import android.graphics.PointF import cn.jingzhuan.lib.chart3.drawline.DrawLineState /** * @since 2023-10-09 * created by lei * 画线监听 */ interface OnDrawLineListener { fun onTouchText(onSuccess: (String)-> Unit) fun onTouch(state: DrawLineState, lineKey: String, type: Int, reselected: Boolean = false) fun onDrag(bitmapPoint: PointF, translatePoint: PointF, state: Int) }
1
null
102
784
f82d4ef2408a4f59c02203c528668e31b645d5f7
430
JZAndroidChart
Apache License 2.0
build-tools/agp-gradle-core/src/main/java/com/android/build/gradle/internal/core/dsl/impl/features/DexingDslInfoImpl.kt
RivanParmar
526,653,590
false
null
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.core.dsl.impl.features import com.android.build.api.dsl.ApplicationBuildType import com.android.build.api.dsl.BuildType import com.android.build.gradle.internal.core.MergedFlavor import com.android.build.gradle.internal.core.dsl.features.DexingDslInfo import java.io.File class DexingDslInfoImpl( private val buildTypeObj: BuildType, private val mergedFlavor: MergedFlavor ): DexingDslInfo { // Only require specific multidex opt-in for legacy multidex. override val isMultiDexEnabled: Boolean? get() { // Only require specific multidex opt-in for legacy multidex. return (buildTypeObj as? ApplicationBuildType)?.multiDexEnabled ?: mergedFlavor.multiDexEnabled } override val multiDexKeepProguard: File? get() { var value = buildTypeObj.multiDexKeepProguard if (value != null) { return value } value = mergedFlavor.multiDexKeepProguard return value } override val multiDexKeepFile: File? get() { var value = buildTypeObj.multiDexKeepFile if (value != null) { return value } value = mergedFlavor.multiDexKeepFile return value } }
0
null
2
17
8fb2bb1433e734aa9901184b76bc4089a02d76ca
1,959
androlabs
Apache License 2.0
src/test/kotlin/io/kotlintest/specs/BehaviourSpecLambdaTest.kt
ruslanas
125,570,929
false
null
package io.kotlintest.specs import io.kotlintest.matchers.shouldBe class BehaviourSpecLambdaTest : BehaviorSpec({ given("string.length") { `when`("using foobar") { val subject = "foobar" then("length is 6") { subject.length shouldBe 6 } } } })
1
null
1
1
e0f8062f9bed2568601cf52d959ece5baa645b7f
321
kotlintest
Apache License 2.0
plugins/base/src/main/kotlin/templating/AddToSourcesetDependencies.kt
Kotlin
21,763,603
false
null
package org.jetbrains.dokka.base.templating data class AddToSourcesetDependencies(val moduleName: String, val content: Map<String, List<String>>) : Command
438
Kotlin
390
3,010
bec2cac91726e52884329e7997207e9777abaab7
156
dokka
Apache License 2.0
src/main/java/org/tokend/sdk/api/integrations/cards/params/CardParams.kt
TamaraGambarova
291,018,574
true
{"Kotlin": 715884, "Java": 293039, "Ruby": 13011}
package org.tokend.sdk.api.integrations.cards.params import org.tokend.sdk.api.integrations.cards.params.CardParams.Includes import org.tokend.sdk.api.v3.base.JsonApiQueryParams /** * @see Includes */ open class CardParams( include: Collection<String>? ) : JsonApiQueryParams(include) { class Includes { companion object { const val BALANCES = "balance" } } }
0
Kotlin
0
1
941186aee243d0639d72e7ee189d509afc6292b9
407
kotlin-sdk
Apache License 2.0
platform/external-system-impl/src/com/intellij/openapi/externalSystem/action/task/ExternalSystemTaskMenu.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.action.task import com.intellij.execution.Executor import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys import com.intellij.openapi.externalSystem.statistics.ExternalSystemActionsCollector import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.SimpleToolWindowPanel internal class ExternalSystemTaskMenu : DefaultActionGroup(), DumbAware { override fun getChildren(e: AnActionEvent?): Array<out AnAction?> { val project = e?.project ?: return super.getChildren(e) return Executor.EXECUTOR_EXTENSION_NAME.extensionList .filter { it.isApplicable(project) } .map { e.actionManager.getAction(it.contextActionId) } .toTypedArray() + super.getChildren(e) } internal class Listener : AnActionListener { override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) { val view = event.getData(ExternalSystemDataKeys.VIEW) ?: return if ((view as SimpleToolWindowPanel).name != event.place) return val actionId = event.actionManager.getId(action) ?: return val executor = Executor.EXECUTOR_EXTENSION_NAME.extensionList.find { it.contextActionId == actionId} ?: return val extActionId = ExternalSystemActionsCollector.ActionId.RunExternalSystemTaskAction ExternalSystemActionsCollector.trigger(view.project, view.systemId, extActionId, event, executor) } } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
1,675
intellij-community
Apache License 2.0
tools4j-base64-ktx/src/main/java/com/github/panpf/tools4j/base64/ktx/Base64x.kt
panpf
287,200,520
false
{"Java": 2110745, "Kotlin": 1577314, "Shell": 1283}
/* * Copyright (C) 2020 panpf <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package com.github.panpf.tools4j.base64.ktx import com.github.panpf.tools4j.base64.Base64x /* * Base64 related extension methods or properties */ /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @receiver the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode * @param flags controls certain features of the encoded output. * Passing `DEFAULT` results in output that * adheres to RFC 2045. */ inline fun ByteArray.base64Encode(offset: Int, len: Int, flags: Int): ByteArray = Base64x.encode(this, offset, len, flags) /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @receiver the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode */ inline fun ByteArray.base64Encode(offset: Int, len: Int): ByteArray = Base64x.encode(this, offset, len) /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @receiver the data to encode * @param flags controls certain features of the encoded output. * Passing `DEFAULT` results in output that * adheres to RFC 2045. */ inline fun ByteArray.base64Encode(flags: Int): ByteArray = Base64x.encode(this, flags) /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @receiver the data to encode */ inline fun ByteArray.base64Encode(): ByteArray = Base64x.encode(this) /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @receiver the data to encode * @param flags controls certain features of the encoded output. * Passing `DEFAULT` results in output that * adheres to RFC 2045. */ inline fun String.base64Encode(flags: Int): ByteArray = Base64x.encode(this, flags) /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @receiver the data to encode */ inline fun String.base64Encode(): ByteArray = Base64x.encode(this) /** * Base64-encode the given data and return a newly allocated * String with the result. * * @receiver the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode * @param flags controls certain features of the encoded output. * Passing `DEFAULT` results in output that * adheres to RFC 2045. */ inline fun ByteArray.base64EncodeToString(offset: Int, len: Int, flags: Int): String = Base64x.encodeToString(this, offset, len, flags) /** * Base64-encode the given data and return a newly allocated * String with the result. * * @receiver the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode */ inline fun ByteArray.base64EncodeToString(offset: Int, len: Int): String = Base64x.encodeToString(this, offset, len) /** * Base64-encode the given data and return a newly allocated * String with the result. * * @receiver the data to encode * @param flags controls certain features of the encoded output. * Passing `DEFAULT` results in output that * adheres to RFC 2045. */ inline fun ByteArray.base64EncodeToString(flags: Int): String = Base64x.encodeToString(this, flags) /** * Base64-encode the given data and return a newly allocated * String with the result. * * @receiver the data to encode */ inline fun ByteArray.base64EncodeToString(): String = Base64x.encodeToString(this) /** * Base64-encode the given data and return a newly allocated * String with the result. * * @receiver the data to encode * @param flags controls certain features of the encoded output. * Passing `DEFAULT` results in output that * adheres to RFC 2045. */ inline fun String.base64EncodeToString(flags: Int): String = Base64x.encodeToString(this, flags) /** * Base64-encode the given data and return a newly allocated * String with the result. * * @receiver the data to encode */ inline fun String.base64EncodeToString(): String = Base64x.encodeToString(this) // -------------------------------------------------------- // decoding // -------------------------------------------------------- /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the data to decode * @param offset the position within the input array at which to start * @param len the number of bytes of input to decode * @param flags controls certain features of the decoded output. * Pass `DEFAULT` to decode standard Base64. * @throws IllegalArgumentException if the input contains * incorrect padding */ inline fun ByteArray.base64Decode(offset: Int, len: Int, flags: Int): ByteArray = Base64x.decode(this, offset, len, flags) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the data to decode * @param offset the position within the input array at which to start * @param len the number of bytes of input to decode * @throws IllegalArgumentException if the input contains incorrect padding */ inline fun ByteArray.base64Decode(offset: Int, len: Int): ByteArray = Base64x.decode(this, offset, len) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the input array to decode * @param flags controls certain features of the decoded output. * Pass `DEFAULT` to decode standard Base64. * @throws IllegalArgumentException if the input contains incorrect padding */ inline fun ByteArray.base64Decode(flags: Int): ByteArray = Base64x.decode(this, flags) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the input array to decode * @throws IllegalArgumentException if the input contains incorrect padding */ inline fun ByteArray.base64Decode(): ByteArray = Base64x.decode(this) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the input String to decode, which is converted to * bytes using the default charset * @param flags controls certain features of the decoded output. * Pass `DEFAULT` to decode standard Base64. * @throws IllegalArgumentException if the input contains * incorrect padding */ inline fun String.base64Decode(flags: Int): ByteArray = Base64x.decode(this, flags) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the input String to decode, which is converted to * bytes using the default charset * @throws IllegalArgumentException if the input contains * incorrect padding */ inline fun String.base64Decode(): ByteArray = Base64x.decode(this) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the data to decode * @param offset the position within the input array at which to start * @param len the number of bytes of input to decode * @param flags controls certain features of the decoded output. * Pass `DEFAULT` to decode standard Base64. * @throws IllegalArgumentException if the input contains * incorrect padding */ inline fun ByteArray.base64DecodeToString(offset: Int, len: Int, flags: Int): String = Base64x.decodeToString(this, offset, len, flags) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the data to decode * @param offset the position within the input array at which to start * @param len the number of bytes of input to decode * @throws IllegalArgumentException if the input contains incorrect padding */ inline fun ByteArray.base64DecodeToString(offset: Int, len: Int): String = Base64x.decodeToString(this, offset, len) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the input array to decode * @param flags controls certain features of the decoded output. * Pass `DEFAULT` to decode standard Base64. * @throws IllegalArgumentException if the input contains incorrect padding */ inline fun ByteArray.base64DecodeToString(flags: Int): String = Base64x.decodeToString(this, flags) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the input array to decode * @throws IllegalArgumentException if the input contains incorrect padding */ inline fun ByteArray.base64DecodeToString(): String = Base64x.decodeToString(this) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the input String to decode, which is converted to * bytes using the default charset * @param flags controls certain features of the decoded output. * Pass `DEFAULT` to decode standard Base64. * @throws IllegalArgumentException if the input contains * incorrect padding */ inline fun String.base64DecodeToString(flags: Int): String = Base64x.decodeToString(this, flags) /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * * The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @receiver the input String to decode, which is converted to * bytes using the default charset * @throws IllegalArgumentException if the input contains * incorrect padding */ inline fun String.base64DecodeToString(): String = Base64x.decodeToString(this)
1
Java
1
3
cbdb7be9a5eb9c0a00b4a87e28a8f657fee3752a
11,785
tools4j
Apache License 2.0
tmp/arrays/youTrackTests/2876.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-38899 fun <T : A> create(modelClass: Class<T>): T { return if (modelClass.isAssignableFrom(B::class.java)) { // UNREACHABLE_CODE createViewModel() // IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION } else { throw Exception() } } @Suppress("UNCHECKED_CAST") fun <T : A> createViewModel(): T { return B() as T } open class A class B : A() fun main() { create(A::class.java) // NullPointerException }
1
null
11
1
602285ec60b01eee473dcb0b08ce497b1c254983
460
bbfgradle
Apache License 2.0
AndroidBottomView/app/src/main/kotlin/io/shtanko/androidbottomview/BottomView+Extentions.kt
ashtanko
84,250,135
false
{"Java": 27392, "Kotlin": 4350, "Shell": 1416, "C++": 1340, "CMake": 505, "C": 152}
package io.shtanko.androidbottomview import android.support.design.internal.BottomNavigationItemView import android.support.design.internal.BottomNavigationMenuView import android.support.design.widget.BottomNavigationView import android.util.Log fun removeShiftMode(view: BottomNavigationView) { val menuView = view.getChildAt(0) as BottomNavigationMenuView try { val shiftingMode = menuView.javaClass.getDeclaredField("mShiftingMode") shiftingMode.isAccessible = true shiftingMode.setBoolean(menuView, false) shiftingMode.isAccessible = false for (i in 0..menuView.childCount - 1) { val item = menuView.getChildAt(i) as BottomNavigationItemView item.setShiftingMode(false) // set once again checked value, so view will be updated item.setChecked(item.itemData.isChecked) } } catch (e: NoSuchFieldException) { Log.e("ERROR NO SUCH FIELD", "Unable to get shift mode field") } catch (e: IllegalAccessException) { Log.e("ERROR ILLEGAL ALG", "Unable to change value of shift mode") } }
1
null
1
1
bf2120a135e3fb3e578388ff0d89ab58610bf739
1,050
template-android
Apache License 2.0
Android/app/src/main/java/com/tencent/qcloud/todolist/vm/TodoViewModel.kt
tencentyun
139,822,497
false
{"Objective-C": 93121, "Kotlin": 59996, "Java": 10553, "Ruby": 3466}
package com.tencent.qcloud.todolist.vm import android.net.Uri import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.tencent.qcloud.todolist.data.Repository import com.tencent.qcloud.todolist.model.DataHolder import com.tencent.qcloud.todolist.model.TodoItem /** * <p> * </p> * Created by wjielai on 2018/6/5. * Copyright 2010-2017 Tencent Cloud. All Rights Reserved. */ class TodoViewModel : ViewModel() { private val repository = Repository.instance fun item(taskId : String) : MutableLiveData<DataHolder<TodoItem>>? { return repository.getItem(taskId) } fun list():MutableLiveData<DataHolder<MutableList<TodoItem>>> { return repository.getTodoList() } fun reloadList() { repository.getTodoList(forceReload = true) } fun insert(content: String, attachmentUri: Uri?): MutableLiveData<DataHolder<TodoItem>> { return repository.insertTodo(content, attachmentUri) } fun markDone(item: TodoItem): MutableLiveData<DataHolder<TodoItem>> { val livaItem = MutableLiveData<DataHolder<TodoItem>>() livaItem.value = DataHolder(data = item) repository.removeTodo(livaItem) return livaItem } fun markDone(item: MutableLiveData<DataHolder<TodoItem>>): MutableLiveData<DataHolder<TodoItem>> { repository.removeTodo(item) return item } }
1
Objective-C
1
2
0f713177e0d3acc4f3e78b0bafffe1125ec872f2
1,402
tac-todolist
Apache License 2.0
app/src/main/java/io/redgreen/benchpress/github/domain/User.kt
Aryan210
346,594,002
false
null
package io.redgreen.benchpress.github.domain import android.os.Parcelable import com.squareup.moshi.Json import kotlinx.android.parcel.Parcelize @Parcelize data class User( @field:Json(name = "login") val username: String, @field:Json(name = "avatar_url") val avatarUrl: String ) : Parcelable
1
null
1
1
51335bba348794403cca58d0aa9bcea224daeb8b
303
bench-mark
Apache License 2.0
ontrack-service/src/main/java/net/nemerosa/ontrack/service/dashboards/DashboardStorageService.kt
nemerosa
19,351,480
false
{"Git Config": 1, "Gradle Kotlin DSL": 67, "Markdown": 46, "Ignore List": 22, "Java Properties": 3, "Shell": 9, "Text": 3, "Batchfile": 2, "Groovy": 145, "JSON": 31, "JavaScript": 792, "JSON with Comments": 4, "GraphQL": 79, "Kotlin": 3960, "Java": 649, "HTML": 269, "PlantUML": 25, "AsciiDoc": 288, "XML": 9, "YAML": 33, "INI": 4, "Dockerfile": 7, "Less": 31, "CSS": 13, "SQL": 43, "Dotenv": 1, "Maven POM": 1, "SVG": 4}
package net.nemerosa.ontrack.service.dashboards import net.nemerosa.ontrack.model.dashboards.Dashboard import net.nemerosa.ontrack.model.structure.ID interface DashboardStorageService { fun findDashboardByUuid(uuid: String): Dashboard? fun findDashboardsByUser(id: ID): List<Dashboard> fun findSharedDashboards(): List<Dashboard> fun saveDashboard(dashboard: Dashboard): Dashboard fun deleteDashboard(uuid: String) fun ownDashboard(uuid: String, userId: ID): Boolean }
48
Kotlin
25
96
759f17484c9b507204e5a89524e07df871697e74
501
ontrack
MIT License
app/src/main/kotlin/by/deniotokiari/shikimoriclient/dagger/module/DateFormatterModule.kt
deniotokiari
79,706,194
false
null
package by.deniotokiari.shikimoriclient.dagger.module import by.deniotokiari.shikimoriclient.IDateFormatter import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class DateFormatterModule { @Provides @Singleton fun provideDateFormatter(): IDateFormatter { return IDateFormatter.newInstance() } }
0
Kotlin
0
0
834f6c35e31ed680fd7f549c732d4cbe689954da
351
shikimori-client
Apache License 2.0
qms/qms-data/src/main/java/org/softeg/slartus/forpdaplus/domain_qms/db/QmsDbModule.kt
slartus
21,554,455
false
{"HTML": 6951966, "CSS": 1246476, "Java": 1138597, "Kotlin": 744082, "JavaScript": 47541, "PHP": 3566, "Less": 1459}
package org.softeg.slartus.forpdaplus.domain_qms.db import android.content.Context import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class QmsDbModule { @Provides @Singleton fun provideDb(@ApplicationContext app: Context): QmsDatabase { return Room .databaseBuilder(app, QmsDatabase::class.java, QmsDatabase.NAME) .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun provideQmsContactsDao(db: QmsDatabase): QmsContactsDao = db.qmsContactsDao() }
16
HTML
17
86
03dfdb68c1ade272cf84ff1c89dc182f7fe69c39
769
4pdaClient-plus
Apache License 2.0
app/src/main/kotlin/eldp/robotminediffuser/LoginActivity.kt
ysuo85
97,416,205
false
null
package eldp.robotminediffuser import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.Toast import eldp.robotminediffuser.modes.MainUserModeActivity class LoginActivity : Activity() { private var password: EditText ?= null private var btnSubmit: Button ?= null private var passwordVal: String ?= null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login_mode) password = findViewById<View>(R.id.txtPassword) as EditText btnSubmit = findViewById<View>(R.id.btnSubmit) as Button passwordVal = getString(R.string.password) addListenerOnButton() val intent : Intent = getIntent() val lock_flag : Boolean = intent.getBooleanExtra("lock_flag", false) val kill_flag : Boolean = intent.getBooleanExtra("kill_flag", false) if(lock_flag) { val imgFile = File("lock.png") if (imgFile.exists()) { val myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()) val myImage = findViewById(R.id.imageviewTest) as ImageView myImage.setImageBitmap(myBitmap) } } if(kill_flag) { } } fun addListenerOnButton() { btnSubmit!!.setOnClickListener { if(passwordVal== password!!.text.toString()){ Toast.makeText(this@LoginActivity, "Password matched!", Toast.LENGTH_SHORT).show() val intent = Intent(this, MainUserModeActivity::class.java) intent.putExtra("logged_in_flag", true) startActivity(intent) } } } }
1
null
1
1
1d6ca8c0bfa6ea17a39c781d738840dd41bb5ddf
1,854
RobotMineDiffuser
MIT License
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnIntention.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.psi.KtIfExpression class FoldIfToReturnIntention : SelfTargetingRangeIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("lift.return.out.of.if.expression") ) { override fun applicabilityRange(element: KtIfExpression): TextRange? = if (BranchedFoldingUtils.canFoldToReturn(element)) element.ifKeyword.textRange else null override fun applyTo(element: KtIfExpression, editor: Editor?) { BranchedFoldingUtils.foldToReturn(element) } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
1,099
intellij-community
Apache License 2.0
compiler/testData/codegen/box/callableReference/function/local/localFunctionName.kt
damenez
176,209,431
true
{"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1}
// IGNORE_BACKEND: JVM_IR, JS_IR fun box(): String { fun OK() {} return ::OK.name }
0
Kotlin
0
2
9a2178d96bd736c67ba914b0f595e42d1bba374d
94
kotlin
Apache License 2.0
app/src/main/java/com/coolweather/coolweatherjetpack/ui/weather/WeatherViewModel.kt
msdgwzhy6
173,256,845
true
{"Kotlin": 39648}
package com.coolweather.coolweatherjetpack.ui.weather import androidx.lifecycle.ViewModel import com.coolweather.coolweatherjetpack.data.WeatherRepository import com.coolweather.coolweatherjetpack.data.model.weather.Weather class WeatherViewModel(private val repository: WeatherRepository) : ViewModel() { var weather: Weather? = null var bingPicUrl: String? = null fun getWeather(weatherId: String, key: String) = repository.getWeather(weatherId, key) fun refreshWeather(weatherId: String, key: String) = repository.refreshWeather(weatherId, key) fun isWeatherCached() = repository.isWeatherCached() fun getCachedWeather() = repository.getCachedWeather() fun getBingPic() = repository.getBingPic() }
0
Kotlin
0
1
de9a1ad6609b7d5ee0b40173067f983e6e4b600e
738
coolweatherjetpack
Apache License 2.0
catalog/src/main/kotlin/com/adevinta/spark/catalog/configurator/samples/divider/DivivderConfigurator.kt
adevinta
598,741,849
false
{"Kotlin": 2458277}
/* * Copyright (c) 2023-2024 Adevinta * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.adevinta.spark.catalog.configurator.samples.divider import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.adevinta.spark.SparkTheme import com.adevinta.spark.catalog.model.Configurator import com.adevinta.spark.catalog.themes.SegmentedButton import com.adevinta.spark.catalog.util.SampleSourceUrl import com.adevinta.spark.components.divider.DividerIntent import com.adevinta.spark.components.divider.HorizontalDivider import com.adevinta.spark.components.divider.LabelHorizontalAlignment import com.adevinta.spark.components.divider.LabelVerticalAlignment import com.adevinta.spark.components.divider.VerticalDivider import com.adevinta.spark.components.spacer.VerticalSpacer import com.adevinta.spark.components.text.Text import com.adevinta.spark.components.textfields.TextField import com.adevinta.spark.tokens.highlight public val DividerConfigurator: Configurator = Configurator( name = "Divider", description = "Divider configuration", sourceUrl = "$SampleSourceUrl/DividerSamples.kt", ) { DividerSample() } @Preview( showBackground = true, ) @Composable private fun DividerSample() { Column { var intent by remember { mutableStateOf(DividerIntent.Outline) } var hLabelAlignments by remember { mutableStateOf(LabelHorizontalAlignment.Center) } var vLabelAlignments by remember { mutableStateOf(LabelVerticalAlignment.Center) } var labelText by remember { mutableStateOf("label") } Column { Text( text = "Divider Intent", modifier = Modifier.padding(bottom = 8.dp), style = SparkTheme.typography.body2.highlight, ) val dividerIntents = DividerIntent.entries.map(DividerIntent::name) SegmentedButton( options = dividerIntents, selectedOption = intent.name, onOptionSelect = { intent = DividerIntent.valueOf(it) }, modifier = Modifier.fillMaxWidth(), ) } VerticalSpacer(8.dp) Text( text = "HorizontalDivider", style = SparkTheme.typography.headline2, ) HorizontalDivider( intent = intent, label = if (labelText.isEmpty()) { null } else { { TextComposable(label = labelText) } }, labelHorizontalAlignment = hLabelAlignments, ) VerticalSpacer(8.dp) Text( text = "VerticalDivider", style = SparkTheme.typography.headline2, ) VerticalDivider( modifier = Modifier .height(200.dp) .fillMaxWidth(), intent = intent, label = if (labelText.isEmpty()) { null } else { { TextComposable(label = labelText) } }, labelVerticalAlignment = vLabelAlignments, ) Column { Text( text = "HorizontalDivider Label Alignment", modifier = Modifier.padding(bottom = 8.dp), style = SparkTheme.typography.body2.highlight, ) val labelAlignments = LabelHorizontalAlignment.entries.map(LabelHorizontalAlignment::name) SegmentedButton( options = labelAlignments, selectedOption = hLabelAlignments.name, onOptionSelect = { hLabelAlignments = LabelHorizontalAlignment.valueOf(it) }, modifier = Modifier.fillMaxWidth(), ) } VerticalSpacer(8.dp) Column { Text( text = "VerticalDivider Label Alignment", modifier = Modifier.padding(bottom = 8.dp), style = SparkTheme.typography.body2.highlight, ) val labelAlignments = LabelVerticalAlignment.entries.map(LabelVerticalAlignment::name) SegmentedButton( options = labelAlignments, selectedOption = vLabelAlignments.name, onOptionSelect = { vLabelAlignments = LabelVerticalAlignment.valueOf(it) }, modifier = Modifier.fillMaxWidth(), ) } VerticalSpacer(8.dp) TextField( modifier = Modifier.fillMaxWidth(), value = labelText, onValueChange = { labelText = it }, label = "Change label", helper = "Divider label", ) } } @Composable private fun TextComposable(label: String = "label") { Text( modifier = Modifier, textAlign = TextAlign.Center, overflow = TextOverflow.Ellipsis, style = SparkTheme.typography.body1, text = label, ) }
46
Kotlin
24
58
40b01e08ae3b43a6d8c1c892380ceb8a1835c5ec
6,535
spark-android
MIT License
record_library/src/main/java/com/crimson/record/view/RecordVoiceView.kt
crimson0829
228,051,772
false
null
@file:Suppress("DEPRECATION") package com.crimson.record.view import android.app.Activity import android.content.Context import android.graphics.* import android.os.Handler import android.text.Layout import android.text.StaticLayout import android.text.TextPaint import android.util.AttributeSet import android.util.DisplayMetrics import android.util.SparseArray import android.util.TypedValue import android.view.* import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.RelativeLayout import androidx.core.content.ContextCompat import androidx.core.widget.NestedScrollView import com.crimson.record.R import com.crimson.record.audio.RecordConfig import com.crimson.record.bus.RxBus.Companion.get import com.crimson.record.bus.RxBusMessage import com.crimson.record.bus.RxCode import com.crimson.record.bus.RxDisposable.add import com.crimson.record.bus.RxDisposable.remove import com.crimson.record.data.RecordFile import com.crimson.record.data.RecordNodeData import com.crimson.record.data.RecordTime import com.crimson.record.data.deleteFile import com.crimson.record.player.AudioPlayer import com.crimson.record.util.RxRecordTime.Companion.recordTime import com.crimson.record.util.SoftKeyBoardListener.Companion.setListener import com.crimson.record.util.SoftKeyBoardListener.OnSoftKeyBoardChangeListener import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.io.File /** * @author crimson * @date 2019-09-05 * 录音控件 * 录音数据存储在节点对象[RecordNodeData] */ class RecordVoiceView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { //父布局 private var mParent: ViewParent? = null //计算宽度 private var widthMeasureSpec = 0 //填充屏幕后的原始高度 private var originHeight = 0 //声音模式 1:录音 2:播放 var voiceMode = 0 //圆点标签 //半径 var thumbRadius = 0 //颜色 var thumbColor = 0 //中心坐标 var mCenterX = 0 //时间距离 var mTimeDistance = 0 //速率 1000ms内重绘的速率,越小速度越快 如速率为100 则重绘1000/100=10次 var speed = 0 //初始左偏移量 var originLeft = 0 //进度线颜色 var lineColor = 0 //进度线宽度 var lineWidth = 0 //虚线颜色 var lineDashColor = 0 //虚线宽度 var lineDashWidth = 0 //时间颜色 var timeColor = 0 //时间大小 var timeSize = 0 //时间是否加粗 var timeBold = false //正在识别颜色 var recognizeColor = 0 //正在识别大小 var recognizeSize = 0 //正在识别是否加粗 var recognizeBold = false //正在识别文字 var recognizeText = "" //识别文字背景 var recognizeTextBg = 0 //节点圆颜色 var circleColor = 0 //节点圆外圈大小 var circleWidth = 0 //节点圆半径 var circleRadius = 0 //节点圆是否填充 var circleFull = false //内圆颜色 var innerCircleColor = 0 //内容颜色 var contentColor = 0 //内容大小 var contentSize = 0 //翻译内容padding var contentPadding = 30 //最小节点高度 var minNodeHeight = 150 //录音目录 var recordDir: String? = null //录音文件设置 var recordConfig: RecordConfig? = null //录音文件名称 private var recordFileName: String? = null //虚线路径 private var mPath = Path() //画笔 private var mThumbPaint = Paint() private var mLinePaint = Paint() private var mDashLinePaint = Paint() private var mTimePaint = Paint() private var mCirclePaint = Paint() private var mInnerCirclePaint = Paint() private var mContentPaint = TextPaint() private var mRecognizingPaint = Paint() private var mRecognizeBgPaint = Paint() //初始偏移量 private val originY = 24 //偏移量 private var thumbY = originY //初始Y坐标 private val startY = originY //图标等底部之后的滑动坐标 private var overScrollY = 0 private var mParentScrollY = 0 private val overScrollYPreY = 200 private val calculateHeightY = 500 private var status = Status.IDLE //状态 0:初始状态 1:录音状态 2:录音暂定状态 3:播放状态 4:播放暂停状态,5.播放空闲状态 6.编辑内容状态 enum class Status { IDLE, RECORDING, RECORD_PAUSE, PLAYING, PLAY_PAUSE, PLAY_IDLE, EDIT_CONTENT } //节点容器 private var nodes = arrayListOf<RecordNodeData>() //当前节点 private var currentNode = 0 //是否需创建新的节点 private var needNewNode = false //rx sub private var mRecSub: Disposable? = null private var mTimeSub: Disposable? = null private var mClipSub: Disposable? = null private var mPcmDataSub: Disposable? = null /** * 录音接口 */ private var recorder: IRecorder? = null //分 private var mini: Long = 0 //秒 private var seco: Long = 0 //播放状态进度线条绘制的高度 private var lineDrawHeight = 0 //播放器 private var mPlayer: AudioPlayer? = null //节点文字content sb 容器 private val arrays = SparseArray<StringBuilder?>() //临时转化文字 private var psg: String? = null //是否可以点击和移动进度 private var canMoveIcon = false //是否可以编辑内容 private var canEditContent = false //前一个编辑框索引 private var prevEditIndex = -1 private var mHandler = Handler() private var mRunnable = Runnable { thumbY++ if (voiceMode == 1) { //录音模式 startRecord() } else { //播放模式 if (thumbY < lineDrawHeight) { //播放 startPlay() } else { //暂停 pausePlay() } } if (status == Status.RECORDING && thumbY > height - overScrollYPreY) { scrollTo(0, overScrollY) overScrollY++ if (nodes[currentNode].distance <= overScrollY + 20) { pauseRecord() startRecord() } } else { invalidate() } } init { initAttrs(context, attrs) init() initRxBus() } /** * 初始化属性 * * @param context * @param attrs */ private fun initAttrs(context: Context, attrs: AttributeSet?) { context.obtainStyledAttributes(attrs, R.styleable.RecordVoiceView) .apply { thumbRadius = getInt(R.styleable.RecordVoiceView_rvv_thumb_radius, dip2px(5)) thumbColor = getColor( R.styleable.RecordVoiceView_rvv_thumb_color, Color.parseColor("#14c691") ) voiceMode = getInt(R.styleable.RecordVoiceView_rvv_voice_mode, 1) speed = getInt(R.styleable.RecordVoiceView_rvv_speed, 80) originLeft = getInt(R.styleable.RecordVoiceView_rvv_line_leftPadding, dip2px(70)) lineWidth = getInt(R.styleable.RecordVoiceView_rvv_line_width, dip2px(3)) lineColor = getColor( R.styleable.RecordVoiceView_rvv_line_color, Color.parseColor("#14c691") ) lineDashColor = getColor( R.styleable.RecordVoiceView_rvv_line_dash_color, Color.parseColor("#999999") ) lineDashWidth = getInt(R.styleable.RecordVoiceView_rvv_line_dash_width, dip2px(2)) timeColor = getColor( R.styleable.RecordVoiceView_rvv_node_time_color, Color.parseColor("#666666") ) timeSize = getInt(R.styleable.RecordVoiceView_rvv_node_time_size, dip2px(15)) timeBold = getBoolean(R.styleable.RecordVoiceView_rvv_node_time_bold, false) recognizeColor = getColor( R.styleable.RecordVoiceView_rvv_recognize_color, Color.parseColor("#999999") ) recognizeSize = getInt(R.styleable.RecordVoiceView_rvv_recognize_size, dip2px(14)) recognizeBold = getBoolean(R.styleable.RecordVoiceView_rvv_recognize_bold, true) recognizeTextBg = getColor( R.styleable.RecordVoiceView_rvv_recognize_text_bg, Color.parseColor("#f5f5f5") ) circleColor = getColor( R.styleable.RecordVoiceView_rvv_circle_color, Color.parseColor("#14c691") ) circleWidth = getInt(R.styleable.RecordVoiceView_rvv_circle_width, dip2px(2)) circleRadius = getInt(R.styleable.RecordVoiceView_rvv_circle_radius, dip2px(4)) circleFull = getBoolean(R.styleable.RecordVoiceView_rvv_circle_full, false) innerCircleColor = getColor(R.styleable.RecordVoiceView_rvv_innerCircle_color, Color.WHITE) contentColor = getColor( R.styleable.RecordVoiceView_rvv_content_color, Color.parseColor("#333333") ) contentSize = getInt(R.styleable.RecordVoiceView_rvv_content_size, dip2px(15)) recycle() } } /** * 初始化 */ private fun init() { initPaint() initVoiceMode() } /** * 初始化画笔 */ private fun initPaint() { mCenterX = originLeft + thumbRadius mThumbPaint.color = thumbColor mLinePaint.color = lineColor mDashLinePaint.run { color = lineDashColor style = Paint.Style.STROKE strokeWidth = lineDashWidth.toFloat() pathEffect = DashPathEffect(floatArrayOf(10f, 10f), 0f) } mTimePaint.run { color = timeColor style = Paint.Style.FILL isAntiAlias = true textSize = timeSize.toFloat() isFakeBoldText = timeBold textAlign = Paint.Align.CENTER } mTimeDistance = startY + thumbRadius mRecognizingPaint.run { color = recognizeColor style = Paint.Style.FILL isAntiAlias = true textSize = recognizeSize.toFloat() isFakeBoldText = recognizeBold textAlign = Paint.Align.CENTER style = Paint.Style.FILL isAntiAlias = true } mRecognizeBgPaint.run { color = recognizeTextBg } recognizeText = context.getString(R.string.recording) mCirclePaint.run { color = circleColor style = if (circleFull) Paint.Style.FILL else Paint.Style.STROKE strokeWidth = circleWidth.toFloat() isAntiAlias = true } mInnerCirclePaint.run { color = innerCircleColor style = Paint.Style.FILL isAntiAlias = true } mContentPaint.run { color = contentColor style = Paint.Style.FILL isAntiAlias = true textSize = contentSize.toFloat() textAlign = Paint.Align.LEFT } setBackgroundColor(ContextCompat.getColor(context, android.R.color.white)) } /** * 根据不同录音模式初始化 */ private fun initVoiceMode() { if (voiceMode == 1) { //设置图层类型,不要开启硬件加速 setLayerType(LAYER_TYPE_SOFTWARE, null) //录音模式 nodes.add(RecordNodeData(0, mTimeDistance, "00:00", "")) //翻译内容布局 nodes[0].contentLayout = createContentLayout(0, "") //recorder实现 recorder = RecorderImpl(context) } else { //播放模式。相当于处于暂停状态 status = Status.PLAY_IDLE mPlayer = AudioPlayer() if (context is Activity) { //软键盘监听 setListener( (context as Activity), object : OnSoftKeyBoardChangeListener { override fun keyBoardShow(height: Int) { if (mStatusCallBack != null) { mStatusCallBack?.onKeyBoardShow(height) } } override fun keyBoardHide(height: Int) { if (mStatusCallBack != null) { mStatusCallBack?.onKeyBoardHide(height) } removeCurrentEditText(mParent as ViewGroup?) } }) } } } /** * 语音识别内容回调注册 */ private fun initRxBus() { mRecSub = get() ?.toObservable(RxCode.ONLINE_RECORD_STATUS_CODE, RxBusMessage::class.java) ?.subscribe { (code, error) -> when (code) { RxCode.ONLINE_RECORD_PARTIAL -> { psg = error as String if (mStatusCallBack != null) { mStatusCallBack?.onVoiceRecordPartial(psg) } RecorderImpl.clipTime = 0 var sbp = arrays[currentNode] var preMsg = "" if (sbp == null) { sbp = StringBuilder() arrays.put(currentNode, sbp) } else { preMsg = sbp.toString() } nodes[currentNode].content = preMsg + psg nodes[currentNode].contentLayout = createContentLayout(currentNode, nodes[currentNode].content) calculateContentHeight() if (status != Status.RECORDING) { postInvalidate() } } RxCode.ONLINE_RECORD_FINISHED -> { val sb: StringBuilder? if (arrays[currentNode] == null) { sb = StringBuilder() arrays.put(currentNode, sb) } else { sb = arrays[currentNode] } val msg = error as String if (mStatusCallBack != null) { mStatusCallBack?.onVoiceRecordFinished(msg) } RecorderImpl.clipTime = 0 sb?.append(msg) val content = nodes[currentNode].content if (psg != null) { nodes[currentNode].content = content.replace(psg!!, "") + msg } nodes[currentNode].contentLayout = createContentLayout(currentNode, nodes[currentNode].content) calculateContentHeight() if (status != Status.RECORDING) { postInvalidate() } } RxCode.ONLINE_RECORD_ERROR -> { if (arrays[currentNode] != null) { val sbe = arrays[currentNode] sbe?.append(nodes[currentNode].content) } if (error is String) { if (mStatusCallBack != null) { mStatusCallBack?.onVoiceRecordError(Error(error)) } RecorderImpl.clipTime = 0 //这里是实现了百度asr的错误码,如果是2001,代表的是网络错误,不做处理 //其他的错误码就重新开启 if ("2001" != error) { if (recorder == null) { return@subscribe } recorder?.restartRecord() } } else if (error is Error) { if (mStatusCallBack != null) { mStatusCallBack?.onVoiceRecordError(error) } } } } } mClipSub = get() ?.toObservable(RxCode.RECORD_CLIP_CODE, Integer::class.java) ?.subscribeOn(Schedulers.io()) ?.subscribe { //这里切割会出现一种极端的情况:当正好需要切割节点的时候,按了暂停,这样这里就回调了两次这样就会报错了 val sb = arrays[currentNode] if (sb != null && sb.toString().trim().isNotEmpty() || recorder?.recordMode() === IRecorder.RecordMode.LOCAL || status == Status.RECORD_PAUSE ) { if (mStatusCallBack != null) { mStatusCallBack?.onRecordClip() } //只有当断点的地方有识别内容,才断下一个点 needNewNode = true //关闭当前node对象文件流 val recordFile = nodes[currentNode].recordFile recordFile?.pcmToWav() } } /** * * 统一处理从online 或者local 过来的pcm数据 * 存储为file文件,格式为Y_年月日时分秒.wav * 存入当前节点对象的file current file */ mPcmDataSub = get() ?.toObservable(RxCode.POST_PCM_DATA, ByteArray::class.java) ?.subscribeOn(Schedulers.io()) ?.subscribe { data: ByteArray? -> if (status == Status.RECORD_PAUSE) { return@subscribe } if (nodes.size - 1 < currentNode) { //会出现一种情况,还没有生成节点 return@subscribe } if (mStatusCallBack != null) { mStatusCallBack?.onPcmDataResult(data) } val node = nodes[currentNode] if (node.recordFile == null) { node.recordFile = createRecordFile() } val recordFile = node.recordFile if (recordFile != null && !recordFile.isClosed) { recordFile.writeData(data) } } mTimeSub = get() ?.toObservable(RxCode.RECORD_TIME_CODE, RecordTime::class.java) ?.subscribe { (min, sec) -> mini = min seco = sec } add(mRecSub) add(mPcmDataSub) add(mClipSub) add(mTimeSub) } /** * 设置联网状态下录音实现类 */ fun setOnlineRecord(onlineRecorderImpl: IRecorder.IOnlineRecorder) { if (recorder is RecorderImpl) { (recorder as RecorderImpl).onlineRecorder(onlineRecorderImpl) } } /** * 设置有网条件下切割时间间隔,当为0时不自动切割节点 */ fun setOnlineClipTime(time: Int) { if (recorder is RecorderImpl) { (recorder as RecorderImpl).onlineClipTime(time) } } /** * 设置本地条件下切割时间,当为0时不自动切割节点 */ fun setLocalClipTime(time: Int) { if (recorder is RecorderImpl) { (recorder as RecorderImpl).localClipTime(time) } } /** * 设置录音模式 */ fun setRecordMode(mode: IRecorder.RecordMode) { if (recorder is RecorderImpl) { (recorder as RecorderImpl).recordMode(mode) } } /** * 计算内容的高度 */ private fun calculateContentHeight() { val distance = nodes[currentNode].distance val height = nodes[currentNode].contentLayout?.height if (height!! > 50 && thumbY < distance + height) { //如果偏移量小于识别文字的高度,就将偏移量设置成该高度 //计算新增的偏移量 val offsetY = distance + height - thumbY //赋值新的thumbY thumbY = distance + height if (thumbY > getHeight() - overScrollYPreY) { //赋值scrollY overScrollY += offsetY } } } /** * 创建内容绘制布局 * * @param node * @param content * @return */ private fun createContentLayout(node: Int, content: String): StaticLayout { //置空 if (nodes.size - 1 > node && nodes[node].contentLayout != null) { nodes[node].contentLayout = null } return StaticLayout( content, mContentPaint, windowWidth - thumbRadius * 2 - originLeft - contentPadding * 2, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false ) } /** * 新增节点 */ private fun addNewNode(): RecordNodeData { val min = if (mini < 10) "0$mini" else mini.toString() val sec = if (seco < 10) "0$seco" else seco.toString() val distance = nodes[currentNode].distance //设置偏移量 //第一种情况,设置默认节点最小高度150 if (thumbY < distance + minNodeHeight) { val offsetY = distance + minNodeHeight - thumbY thumbY = distance + minNodeHeight if (thumbY > height - overScrollYPreY) { //赋值scrollY overScrollY += offsetY } } else { //有识别内容的时候,加75 val cl = nodes[currentNode].contentLayout if (cl != null) { val height = cl.height //第一种情况,设置最小间距 if (thumbY < distance + height + minNodeHeight / 2) { //如果偏移量小于识别文字的高度,就将偏移量设置成该高度 //计算新增的偏移量 val offsetY = distance + height + minNodeHeight / 2 - thumbY //赋值新的thumbY thumbY = distance + height + minNodeHeight / 2 if (thumbY > getHeight() - overScrollYPreY) { //赋值scrollY overScrollY += offsetY } } } } val node = RecordNodeData(++currentNode, thumbY, "$min:$sec", "") if (node.recordFile == null) { node.recordFile = createRecordFile() } nodes.add(node) return node } // /** // * 总时间 // * // * @return // */ fun totalTime(): Int { return recordTime } override fun onMeasure( widthMeasureSpec: Int, heightMeasureSpec: Int ) { if (parent is ViewGroup) { val width = (parent as ViewGroup).width val height = (parent as ViewGroup).height MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY) MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) } this.widthMeasureSpec = widthMeasureSpec super.onMeasure(widthMeasureSpec, heightMeasureSpec) } override fun onLayout( changed: Boolean, l: Int, t: Int, r: Int, b: Int ) { } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) //初始状态 //默认虚线 mPath.reset() mPath.moveTo(mCenterX.toFloat(), startY - 8.toFloat()) mPath.lineTo(mCenterX.toFloat(), height + overScrollY.toFloat()) canvas.drawPath(mPath, mDashLinePaint) //默认初始时间 if (nodes.isNotEmpty()) { canvas.drawText( nodes[0].time, originLeft / 2.toFloat(), nodes[0].distance.toFloat(), mTimePaint ) } canvas.drawCircle(mCenterX.toFloat(), thumbY.toFloat(), thumbRadius.toFloat(), mThumbPaint) if (status != Status.IDLE) { //绘制状态 //画进度 canvas.drawRect( mCenterX - lineWidth / 2.toFloat(), startY.toFloat(), mCenterX + lineWidth / 2.toFloat(), (if (voiceMode == 1) thumbY else lineDrawHeight) + thumbRadius.toFloat(), mLinePaint ) //画初始节点 canvas.drawCircle( mCenterX.toFloat(), startY.toFloat(), circleRadius.toFloat(), mCirclePaint ) if (!circleFull) { canvas.drawCircle( mCenterX.toFloat(), startY.toFloat(), circleRadius - 3.toFloat(), mInnerCirclePaint ) } //根据节点容器长度,画节点跟时间 for (i in 1 until nodes.size) { val (_, distance, time) = nodes[i] //时间 canvas.drawText( time, originLeft / 2.toFloat(), distance + mTimeDistance.toFloat(), mTimePaint ) //节点 canvas.drawCircle( mCenterX.toFloat(), distance.toFloat() + mTimeDistance.toFloat() / 2, circleRadius.toFloat(), mCirclePaint ) if (!circleFull) { canvas.drawCircle( mCenterX.toFloat(), distance + mTimeDistance / 2.toFloat(), circleRadius - 3.toFloat(), mInnerCirclePaint ) } } //图标 canvas.drawCircle( mCenterX.toFloat(), thumbY.toFloat(), thumbRadius.toFloat(), mThumbPaint ) if (status == Status.RECORDING && recorder?.recordMode() === IRecorder.RecordMode.ONLINE) { //展示正在识别 val rectF = RectF( (originLeft + thumbRadius * 2 + contentPadding).toFloat(), (thumbY + contentPadding).toFloat(), (originLeft + thumbRadius * 2 + contentPadding + dip2px(100)).toFloat(), (thumbY + contentPadding + dip2px(35)).toFloat() ) canvas.drawRoundRect(rectF, 50f, 50f, mRecognizeBgPaint) //计算baseline val fontMetrics = mRecognizingPaint.fontMetrics val distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom val baseline = rectF.centerY() + distance canvas.drawText(recognizeText, rectF.centerX(), baseline, mRecognizingPaint) } // 根据节点长度画翻译内容 for (i in nodes.indices) { canvas.save() if (i == 0) { val dy = nodes[i].distance - mTimeDistance canvas.translate( originLeft + thumbRadius * 2 + contentPadding.toFloat(), if (dy < 0) 0f else dy.toFloat() ) } else { canvas.translate( originLeft + thumbRadius * 2 + contentPadding.toFloat(), nodes[i].distance.toFloat() ) } var contentLayout = nodes[i].contentLayout if (contentLayout == null) { contentLayout = createContentLayout(i, nodes[i].content) } contentLayout.draw(canvas) canvas.restore() } } } override fun onTouchEvent(event: MotionEvent): Boolean { if (voiceMode != 2) { return false } val x = event.x var y = event.y when (event.action) { MotionEvent.ACTION_DOWN -> { canMoveIcon = x < originLeft + thumbRadius * 2 + contentPadding && y < lineDrawHeight canEditContent = x > originLeft + thumbRadius * 2 + contentPadding && y < lineDrawHeight if (canMoveIcon) { //如果可移动,请求父控件不拦截事件 thumbY = y.toInt() val parent = parent (parent as? ViewGroup)?.requestDisallowInterceptTouchEvent(true) } removeCurrentEditText(mParent as ViewGroup?) } MotionEvent.ACTION_MOVE -> { if (canMoveIcon) { val startY = 10 if (y < startY) { y = startY.toFloat() } if (y > lineDrawHeight) { y = lineDrawHeight.toFloat() } thumbY = y.toInt() postInvalidate() } else { return super.onTouchEvent(event) } if (canMoveIcon) { //直接播放 if (thumbY != lineDrawHeight) { val positon = calculateCurrentPlaySeekPosition() val path = nodes[currentNode].recordFile?.file?.absolutePath if (mPlayer != null) { mPlayer?.play(path, positon * 1000) } if (!isPlaying) { startPlay() } } if (mStatusCallBack != null) { mStatusCallBack?.onStatusChanged(status) } } else { //在move的区域外点击,弹出并编辑框 if (voiceMode == 2 && canEditContent) { addEditText(y.toInt()) } } } MotionEvent.ACTION_UP -> if (canMoveIcon) { if (thumbY != lineDrawHeight) { val positon = calculateCurrentPlaySeekPosition() val path = nodes[currentNode].recordFile?.file?.absolutePath if (mPlayer != null) { mPlayer?.play(path, positon * 1000) } if (!isPlaying) { startPlay() } } if (mStatusCallBack != null) { mStatusCallBack?.onStatusChanged(status) } } else { if (voiceMode == 2 && canEditContent) { addEditText(y.toInt()) } } } return true } /** * 添加编辑框 * * @param y */ private fun addEditText(y: Int) { mParent = parent.parent if (mParent is RelativeLayout) { val nodeIndex = calculateCurrentNodeIndex(y) if (nodes.size - 1 >= nodeIndex) { removeCurrentEditText(mParent as ViewGroup?) val node = nodes[nodeIndex] val child = EditText(context) //设置lp val width = windowWidth - thumbRadius * 2 - originLeft val lp = RelativeLayout.LayoutParams(width, RelativeLayout.LayoutParams.WRAP_CONTENT) lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT) val parent = parent if (parent is NestedScrollView) { mParentScrollY = parent.scrollY if (nodeIndex == 0) { val topMargin = node.distance - mTimeDistance - 5 lp.topMargin = if (topMargin < 0) 0 else topMargin } else { lp.topMargin = node.distance - 5 - mParentScrollY } } child.layoutParams = lp //这是edittext属性 child.setTextSize(TypedValue.COMPLEX_UNIT_PX, contentSize.toFloat()) child.setTextColor(contentColor) child.setPadding(contentPadding, 0, contentPadding, 0) child.setBackgroundColor( ContextCompat.getColor( context, android.R.color.white ) ) child.setText(node.content) child.gravity = Gravity.TOP (mParent as RelativeLayout).addView(child) node.contentLayout = createContentLayout(nodeIndex, "") node.content = "" invalidate() child.requestFocus() hideOrShowSoftInput() node.editText = child //赋值 prevEditIndex = nodeIndex child.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> val height = v.height //剩余的就是多个节点的时候 //计算节点的高度,如果et的高度大于节点的高度,就循环赋值计算 if (nodes.size == 1) { //只有一个节点的时候,只要height大于总进度长度就赋值重绘 if (height > lineDrawHeight) { lineDrawHeight = height + mTimeDistance + minNodeHeight / 2 invalidate() //改变了进度高度,要重新计算速率重新计算speed } } else if (nodeIndex == nodes.size - 1) { //多个节点编辑最后一个节点的时候,计算最后一个节点的进度高度 if (height > lineDrawHeight - nodes[nodeIndex].distance) { lineDrawHeight = nodes[nodeIndex].distance + height + mTimeDistance + minNodeHeight / 2 invalidate() } } else { val dis0 = nodes[nodeIndex].distance val dis1 = nodes[nodeIndex + 1].distance val nodeHeight = dis1 - dis0 if (height > minNodeHeight && height < nodeHeight + minNodeHeight / 2) { //多出来的高度 val moreHeight = height - nodeHeight + minNodeHeight / 2 for (i in nodeIndex + 1 until nodes.size) { nodes[i].distance = nodes[i].distance + moreHeight + mTimeDistance } lineDrawHeight += moreHeight + mTimeDistance invalidate() } } calculateHeight() status = Status.EDIT_CONTENT if (mStatusCallBack != null) { mStatusCallBack?.onStatusChanged(status) } } } } } /** * 移除当前添加的edittext * * @param parent */ private fun removeCurrentEditText(parent: ViewGroup?) { if (prevEditIndex != -1) { //移除当前的edittext val pNode = nodes[prevEditIndex] val et = pNode.editText if (et != null) { et.clearFocus() pNode.content = et.text.toString() pNode.contentLayout = createContentLayout(prevEditIndex, pNode.content) invalidate() parent?.removeView(et) pNode.editText = null prevEditIndex = -1 } calculateHeight() } } /** * 开始录音 */ fun startRecord() { if (currentNode == 0) { //第一次点击开始的时候,需创建file val node = nodes[currentNode] if (node.recordFile == null) { node.recordFile = createRecordFile() } } if (needNewNode) { needNewNode = false //新建node节点 val node = addNewNode() if (mStatusCallBack != null) { mStatusCallBack?.onCreateNewNode(node) } } mHandler.postDelayed(mRunnable, speed.toLong()) if (recorder != null && recorder?.recordStatus() !== IRecorder.RecordStatus.RECORDING) { recorder?.startRecord() } status = Status.RECORDING mStatusCallBack?.onStatusChanged(status) } @Synchronized private fun createRecordFile(): RecordFile { val recordFile = RecordFile( File( recordDir ?: context.filesDir.absolutePath, recordFileName ?: "rvv_${System.currentTimeMillis()}.pcm" ), recordConfig ?: RecordConfig() ) mStatusCallBack?.onCreateRecordFile(recordFile) return recordFile } //是否正在录音 val isRecording: Boolean get() = status == Status.RECORDING /** * 暂停录音 */ fun pauseRecord() { status = Status.RECORD_PAUSE mHandler.removeCallbacks(mRunnable) if (recorder != null) { recorder?.pauseRecord() } //生成一个节点 get()?.post(RxCode.RECORD_CLIP_CODE, 0) if (mStatusCallBack != null) { mStatusCallBack?.onStatusChanged(status) } } /** * 完成录音,返回节点容器 */ fun completeRecord(): List<RecordNodeData>? { if (voiceMode == 1) { if (isRecording) { pauseRecord() } nodes[currentNode].recordFile?.checkFileConvert() } else { removeCurrentEditText(mParent as ViewGroup?) } return nodes } /** * 在播放模式下构建节点 * * totalTime 总时长,用于计算绘制线条高度 */ fun buildPlayNode(datas: List<RecordNodeData>?, totalHeight: Int, totalTime: Int) { if (lineDrawHeight == 0) { lineDrawHeight = totalHeight } if (voiceMode == 1) { //如果是录音状态,就先清空node nodes.clear() } nodes.addAll(datas!!) if (voiceMode == 1) { //如果是录音状态,就滑动标签到最底部 thumbY = lineDrawHeight //需要新节点 currentNode = nodes.size - 1 needNewNode = true //设置时间 recordTime = totalTime seco = totalTime % 60.toLong() mini = totalTime / 60.toLong() post { //滚动 if (lineDrawHeight > height - 100) { //如果录音的高度小于控件高度,计算超出高度的部分,滑动到改位置 overScrollY = lineDrawHeight - height + overScrollYPreY scrollTo(0, overScrollY) } } } if (voiceMode == 2) { calculateHeight() } invalidate() status = Status.RECORD_PAUSE } //如果是播放模式,就重新计算控件的大小, //如果进度高于控件在屏幕的高度,就重新绘制高度 private fun calculateHeight() { post { if (lineDrawHeight + calculateHeightY > (if (originHeight == 0) height else originHeight)) { if (originHeight == 0) { originHeight = height } setMeasuredDimension(widthMeasureSpec, lineDrawHeight + calculateHeightY) layout(left, top, right, lineDrawHeight + calculateHeightY) if (mParentScrollY != 0) { //重新滑动到之前滑动的位置 val parent1 = parent if (parent1 is NestedScrollView) { parent1.postDelayed({ setMeasuredDimension( widthMeasureSpec, lineDrawHeight + calculateHeightY ) layout( left, top, right, lineDrawHeight + calculateHeightY ) val parent = parent if (parent is NestedScrollView) { parent.scrollTo(0, mParentScrollY) } }, 200) } } } } } /** * 开始播放 */ fun startPlay() { //在到达底部之后开始重新播放播放 if (thumbY == lineDrawHeight) { thumbY = originY } //根据当前节点偏移量计算出当前node索引 val index = calculateCurrentNodeIndex() if (currentNode != index) { currentNode = index } //播放node file mPlayer?.play(nodes[index].recordFile?.file?.absolutePath) //计算播放速率 //高度 val height: Int height = if (nodes.size - 1 == index || nodes.size == 1) { //最后一个节点或者只有一个节点的时候 lineDrawHeight - nodes[index].distance } else { //其他情况 nodes[index + 1].distance - nodes[index].distance } //时间 val duration = nodes[index].duration if (duration != null && !duration.isEmpty()) { speed = duration.toInt() * 1000 / height } mHandler.postDelayed(mRunnable, speed.toLong()) status = Status.PLAYING if (mStatusCallBack != null) { mStatusCallBack?.onStatusChanged(status) } } /** * 是否有节点 * * @return */ fun hasNode(): Boolean { return nodes.size != 0 } /** * 获取录音线条总高度 */ fun totalHeight(): Int { return if (voiceMode == 1) thumbY else lineDrawHeight } /** * 计算当前的node索引 * * @return */ private fun calculateCurrentNodeIndex(y: Int = thumbY): Int { var index = 0 for (i in 1 until nodes.size) { //第一个节点 val disF = nodes[1].distance if (y >= originY && y < disF - thumbRadius) { break } //中间节点 val dis0 = nodes[i - 1].distance val dis1 = nodes[i].distance if (y >= dis0 - thumbRadius && y < dis1 - thumbRadius) { index = i - 1 break } //最后一个节点 if (i + 1 == nodes.size) { val disL = nodes[i].distance - thumbRadius if (y >= disL) { index = i break } } } return index } /** * 计算当前播放的seek进度 * * @return */ private fun calculateCurrentPlaySeekPosition(): Int { val index = calculateCurrentNodeIndex() //时长 var duration = nodes[index].duration?.toInt() if (duration == null) { duration = 0 } val position: Int position = if (nodes.size == 1) { //只有一个节点 (thumbY - originY) * duration / (lineDrawHeight - originY) } else { if (index == 0) { //第一个节点 val dis0 = nodes[0].distance val dis1 = nodes[1].distance (thumbY - dis0) * duration / (dis1 - dis0) } else if (index == nodes.size - 1) { //最后一个节点 val dis = nodes[nodes.size - 1].distance (thumbY - dis) * duration / (lineDrawHeight - dis) } else { //中间节点 val dis0 = nodes[index].distance val dis1 = nodes[index + 1].distance (thumbY - dis0) * duration / (dis1 - dis0) } } return position } /** * 暂停播放 */ fun pausePlay() { mPlayer?.pause() mHandler.removeCallbacks(mRunnable) status = Status.PLAY_PAUSE if (mStatusCallBack != null) { mStatusCallBack?.onStatusChanged(status) } } /** * 是否处于播放状态 * * @return */ val isPlaying: Boolean get() = status == Status.PLAYING /** * 删除录音文件 */ fun deleteFiles() { for (i in nodes.indices) { val node = nodes[i] val recordFile = node.recordFile if (recordFile != null) { val file = recordFile.file deleteFile(file) } } } /** * 释放 */ fun release() { remove(mRecSub) remove(mPcmDataSub) remove(mClipSub) remove(mTimeSub) mHandler.removeCallbacksAndMessages(null) nodes.clear() recorder?.release() mPlayer?.stop() mPlayer = null mStatusCallBack = null } private var mStatusCallBack: ViewStatusCallBack? = null fun setCallBack(listener: CallBack.() -> Unit) { val callBack = CallBack() callBack.listener() this.mStatusCallBack = callBack } private fun dip2px(dpValue: Int): Int { val density = context.resources.displayMetrics.density return (dpValue * density + 0.5f).toInt() } /** * 获取屏幕宽度 * * @return */ private val windowWidth: Int get() { val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager val dm = DisplayMetrics() wm.defaultDisplay.getMetrics(dm) return dm.widthPixels } /** * 隐藏或显示软键盘 */ private fun hideOrShowSoftInput() { val imm = context .getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager imm?.toggleSoftInput( InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS ) } } interface ViewStatusCallBack { //状态改变 fun onStatusChanged(status: RecordVoiceView.Status?) //新增节点 fun onCreateNewNode(node: RecordNodeData?) //部分语音识别 fun onVoiceRecordPartial(msg: String?) //一段话语音识别结束 fun onVoiceRecordFinished(msg: String?) //语音识别错误 fun onVoiceRecordError(error: Error?) //切割节点回调 fun onRecordClip() //当创建录音时候 fun onCreateRecordFile(file: RecordFile) //录音 pcm 字节流回调 fun onPcmDataResult(data: ByteArray?) //键盘展示 fun onKeyBoardShow(height: Int) //键盘隐藏 fun onKeyBoardHide(height: Int) } class CallBack : ViewStatusCallBack { private var status: (RecordVoiceView.Status?) -> Unit = {} private var newNode: (RecordNodeData?) -> Unit = {} private var recordPartial: (String?) -> Unit = {} private var recordFinished: (String?) -> Unit = {} private var recordError: (Error?) -> Unit = {} private var recordClip: () -> Unit = {} private var createRecordFile: (RecordFile?) -> Unit = {} private var pcmDataResult: (ByteArray?) -> Unit = {} private var keyBoardShow: (Int?) -> Unit = {} private var keyBoardHide: (Int?) -> Unit = {} /** * 状态改变回调 */ fun statusChangedCallBack(callback: (RecordVoiceView.Status?) -> Unit) { status = callback } /** * 创建新节点回调 */ fun createNewNodeCallBack(callback: (RecordNodeData?) -> Unit) { newNode = callback } /** * 部分语音转换回调 */ fun voiceToTextPartialCallBack(callback: (String?) -> Unit) { recordPartial = callback } /** * 一段语音结束转换回调 */ fun voiceToTextFinishedCallBack(callback: (String?) -> Unit) { recordFinished = callback } /** * 语音转换错误回调 */ fun voiceToTextErrorCallBack(callback: (Error?) -> Unit) { recordError = callback } /** * 语音切割时回调 */ fun recordClipCallBack(callback: () -> Unit) { recordClip = callback } /** * 创建录音文件时回调 */ fun createRecordFileCallBack(callback: (RecordFile?) -> Unit) { createRecordFile = callback } /** * pcm录音数据回调 */ fun pcmDataResultCallBack(callback: (ByteArray?) -> Unit) { pcmDataResult = callback } /** * 键盘显示回调 */ fun keyBoardShowCallBack(callback: (Int?) -> Unit) { keyBoardShow = callback } /** * 键盘隐藏回调 */ fun keyBoardHideCallBack(callback: (Int?) -> Unit) { keyBoardHide = callback } override fun onStatusChanged(status: RecordVoiceView.Status?) { this.status.invoke(status) } override fun onCreateNewNode(node: RecordNodeData?) { newNode.invoke(node) } override fun onVoiceRecordPartial(msg: String?) { recordPartial.invoke(msg) } override fun onVoiceRecordFinished(msg: String?) { recordFinished.invoke(msg) } override fun onVoiceRecordError(error: Error?) { recordError.invoke(error) } override fun onRecordClip() { recordClip.invoke() } override fun onCreateRecordFile(file: RecordFile) { createRecordFile.invoke(file) } override fun onPcmDataResult(data: ByteArray?) { pcmDataResult.invoke(data) } override fun onKeyBoardShow(height: Int) { keyBoardShow.invoke(height) } override fun onKeyBoardHide(height: Int) { keyBoardHide.invoke(height) } }
0
Kotlin
1
3
a2f44bfe47528a9dd94f29ef0ad2bc8bad5ba54f
48,189
RecordVoiceView
Apache License 2.0
api/src/main/kotlin/com.willfp.modelenginebridge/ModelEngineBridge.kt
Auxilor
723,880,470
false
{"Kotlin": 8779}
package com.willfp.modelenginebridge import org.bukkit.Bukkit import org.bukkit.entity.Entity import java.util.UUID interface ModelEngineBridge { fun createActiveModel(id: String): BridgedActiveModel? fun createModeledEntity(entity: Entity): BridgedModeledEntity fun getModeledEntity(entity: Entity): BridgedModeledEntity? { return getModeledEntity(entity.uniqueId) } fun getModeledEntity(uuid: UUID): BridgedModeledEntity? companion object { val instance: ModelEngineBridge = createInstance() private fun createInstance(): ModelEngineBridge { val plugin = Bukkit.getPluginManager().getPlugin("ModelEngine") ?: throw IllegalStateException("ModelEngineBridge requires ModelEngine to be installed.") @Suppress("DEPRECATION") val version = plugin.description.version return if (version.startsWith("R3")) { val clazz = Class.forName("com.willfp.modelenginebridge.v3.ModelEngineBridgeV3") clazz.constructors[0].newInstance() as ModelEngineBridge } else if (version.startsWith("R4")) { val clazz = Class.forName("com.willfp.modelenginebridge.v4.ModelEngineBridgeV4") clazz.constructors[0].newInstance() as ModelEngineBridge } else { throw IllegalStateException("ModelEngineBridge requires version 3 or 4 of Model Engine!") } } } }
0
Kotlin
0
0
c3a153242e7ea666c814f7adce2f65ec4b3cf625
1,474
ModelEngineBridge
MIT License
idea/testData/editor/quickDoc/OnMethodUsageWithMultilineParam.kt
JakeWharton
99,388,807
false
null
/** * Some documentation * on two lines. * * @param test String * on two lines */ fun testMethod(test: String) { } fun test() { <caret>testMethod("") } //INFO: <pre><b>public</b> <b>fun</b> testMethod(test: String): Unit <i>defined in</i> root package <i>in file</i> OnMethodUsageWithMultilineParam.kt</pre><p>Some documentation on two lines.</p> //INFO: <dl><dt><b>Parameters:</b></dt><dd><code>test</code> - String on two lines</dd></dl>
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
451
kotlin
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/media/key/MediaKeySystemMediaCapability.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.media.key import kotlinx.js.JsPlainObject @JsPlainObject external interface MediaKeySystemMediaCapability { val contentType: String? val encryptionScheme: String? val robustness: String? }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
260
types-kotlin
Apache License 2.0
app/src/main/java/com/plcoding/composepaging3caching/data/database/BeerEntity.kt
IbrahemSalah
697,611,909
false
{"Kotlin": 19426}
package com.plcoding.composepaging3caching.data.database import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class BeerEntity( @PrimaryKey val id: Int, val name: String, val tagline: String, val description: String, val firstBrewed: String, val imageUrl: String? )
0
Kotlin
0
0
094519bf0265c97f55aa35f78ab46a79cea4176b
316
compose_paging_api_3
MIT License
music/src/main/java/com/swensun/music/service/MusicService.kt
SnowyTomorrow
255,544,737
true
{"Kotlin": 312894, "Java": 106595}
package com.swensun.music.service import MusicLibrary import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.media.AudioManager import android.media.MediaPlayer import android.net.Uri import android.os.* import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.RatingCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import android.view.KeyEvent import androidx.core.content.ContextCompat import androidx.media.MediaBrowserServiceCompat import com.swensun.music.MusicHelper import putDuration class MusicService : MediaBrowserServiceCompat() { private var mRepeatMode: Int = PlaybackStateCompat.REPEAT_MODE_NONE /** * 播放状态,通过 MediaSession 回传给 UI 端。 */ private var mState = PlaybackStateCompat.Builder().build() /** * UI 可能被销毁,Service 需要保存播放列表,并处理循环模式 */ private var mPlayList = arrayListOf<MediaSessionCompat.QueueItem>() /** * 当前播放音乐的相关信息 */ private var mMusicIndex = -1 private var mCurrentMedia: MediaSessionCompat.QueueItem? = null /** * 播放会话,将播放状态信息回传给 UI 端。 */ private lateinit var mSession: MediaSessionCompat /** * 真正的音乐播放器 */ private var mMediaPlayer: MediaPlayer = MediaPlayer() /** * 前台通知的相关内容 */ private lateinit var mNotificationManager: MediaNotificationManager /** * 音频焦点处理 */ private lateinit var mAudioFocusHelper: AudioFocusHelper /** * 记录耳机按下的次数 */ private var mHeadSetClickCount = 0 private var handler = HeadSetHandler() inner class HeadSetHandler: Handler() { override fun handleMessage(msg: Message) { super.handleMessage(msg) // 根据耳机按下的次数决定执行什么操作 when(mHeadSetClickCount) { 1 -> { if (mMediaPlayer.isPlaying) { mSessionCallback.onPause() } else { mSessionCallback.onPlay() } } 2 -> { mSessionCallback.onSkipToNext() } 3 -> { mSessionCallback.onSkipToPrevious() } 4 -> { mSessionCallback.onSkipToPrevious() mSessionCallback.onSkipToPrevious() } } mHeadSetClickCount = 0 } } /** * 播放控制器的事件回调,UI 端通过播放控制器发出的指令会在这里接收到,交给真正的音乐播放器处理。 */ private var mSessionCallback = object : MediaSessionCompat.Callback() { override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean { val action = mediaButtonEvent?.action val keyevent = mediaButtonEvent?.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT) MusicHelper.log("action: $action, keyEvent: $keyevent") return if (keyevent?.keyCode == KeyEvent.KEYCODE_HEADSETHOOK ) { if (keyevent.action == KeyEvent.ACTION_UP) { //耳机单机操作 mHeadSetClickCount += 1 if (mHeadSetClickCount == 1) { handler.sendEmptyMessageDelayed(1, 800) } } true } else { super.onMediaButtonEvent(mediaButtonEvent) } } override fun onRewind() { super.onRewind() } override fun onSeekTo(pos: Long) { super.onSeekTo(pos) mMediaPlayer.seekTo(pos.toInt()) setNewState(mState.state) } override fun onAddQueueItem(description: MediaDescriptionCompat) { super.onAddQueueItem(description) // 客户端添加歌曲 if (mPlayList.find { it.description.mediaId == description.mediaId } == null) { mPlayList.add( MediaSessionCompat.QueueItem(description, description.hashCode().toLong()) ) } mMusicIndex = if (mMusicIndex == -1) 0 else mMusicIndex mSession.setQueue(mPlayList) } override fun onRemoveQueueItem(description: MediaDescriptionCompat?) { super.onRemoveQueueItem(description) mPlayList.remove(MediaSessionCompat.QueueItem(description, description.hashCode().toLong())) mMusicIndex = if (mPlayList.isEmpty()) -1 else mMusicIndex mSession.setQueue(mPlayList) } override fun onSkipToPrevious() { super.onSkipToPrevious() if (mPlayList.isEmpty()) { MusicHelper.log("not playlist") return } mMusicIndex = if (mMusicIndex > 0) mMusicIndex - 1 else mPlayList.size - 1 mCurrentMedia = null onPlay() } override fun onSkipToNext() { super.onSkipToNext() if (mPlayList.isEmpty()) { MusicHelper.log("not playlist") return } mMusicIndex = (++mMusicIndex % mPlayList.size) mCurrentMedia = null onPlay() } override fun onCustomAction(action: String?, extras: Bundle?) { super.onCustomAction(action, extras) } override fun onPrepare() { super.onPrepare() if (mPlayList.isEmpty()) { MusicHelper.log("not playlist") return } if (mMusicIndex < 0 || mMusicIndex >= mPlayList.size) { MusicHelper.log("media index error") return } mCurrentMedia = mPlayList[mMusicIndex] val uri = mCurrentMedia?.description?.mediaUri MusicHelper.log("uri, $uri") if (uri == null) { return } // 加载资源要重置 mMediaPlayer.reset() try { if (uri.toString().startsWith("http")) { mMediaPlayer.setDataSource(applicationContext, uri) } else { // assets 资源 val assetFileDescriptor = applicationContext.assets.openFd(uri.toString()) mMediaPlayer.setDataSource( assetFileDescriptor.fileDescriptor, assetFileDescriptor.startOffset, assetFileDescriptor.length ) } mMediaPlayer.prepare() } catch (e: Exception) { e.printStackTrace() } } override fun onFastForward() { super.onFastForward() } override fun onPlay() { super.onPlay() if (mCurrentMedia == null) { onPrepare() } if (mCurrentMedia == null) { return } if (mAudioFocusHelper.requestAudioFocus()) { mMediaPlayer.start() setNewState(PlaybackStateCompat.STATE_PLAYING) } } override fun onPause() { super.onPause() if (!mAudioFocusHelper.mPlayOnAudioFocus) { mAudioFocusHelper.abandonAudioFocus() } mMediaPlayer.pause() setNewState(PlaybackStateCompat.STATE_PAUSED) } override fun onStop() { super.onStop() mAudioFocusHelper.abandonAudioFocus() mMediaPlayer.stop() setNewState(PlaybackStateCompat.STATE_STOPPED) } override fun onSkipToQueueItem(id: Long) { super.onSkipToQueueItem(id) } override fun onPrepareFromMediaId(mediaId: String?, extras: Bundle?) { super.onPrepareFromMediaId(mediaId, extras) } override fun onSetRepeatMode(repeatMode: Int) { super.onSetRepeatMode(repeatMode) mRepeatMode = repeatMode } override fun onCommand(command: String?, extras: Bundle?, cb: ResultReceiver?) { super.onCommand(command, extras, cb) } override fun onPrepareFromSearch(query: String?, extras: Bundle?) { super.onPrepareFromSearch(query, extras) } override fun onPlayFromMediaId(mediaId: String?, extras: Bundle?) { super.onPlayFromMediaId(mediaId, extras) MusicHelper.log("cur mp3: ${mCurrentMedia?.description?.mediaUri}") if (mediaId == mCurrentMedia?.description?.mediaId) { // 同一首歌曲 if (!mMediaPlayer.isPlaying) { onPlay() return } } mMusicIndex = mPlayList.indexOfFirst { it.description.mediaId == mediaId} mCurrentMedia = null onPlay() } override fun onSetShuffleMode(shuffleMode: Int) { super.onSetShuffleMode(shuffleMode) } override fun onPrepareFromUri(uri: Uri?, extras: Bundle?) { super.onPrepareFromUri(uri, extras) } override fun onPlayFromSearch(query: String?, extras: Bundle?) { super.onPlayFromSearch(query, extras) } override fun onPlayFromUri(uri: Uri?, extras: Bundle?) { super.onPlayFromUri(uri, extras) } override fun onSetRating(rating: RatingCompat?) { super.onSetRating(rating) } override fun onSetRating(rating: RatingCompat?, extras: Bundle?) { super.onSetRating(rating, extras) } override fun onSetCaptioningEnabled(enabled: Boolean) { super.onSetCaptioningEnabled(enabled) } } // 播放器的回调 private var mCompletionListener: MediaPlayer.OnCompletionListener = MediaPlayer.OnCompletionListener { MusicHelper.log("OnCompletionListener") setNewState(PlaybackStateCompat.STATE_PAUSED) when (mRepeatMode) { PlaybackStateCompat.REPEAT_MODE_ONE -> { mSessionCallback.onPlay() } PlaybackStateCompat.REPEAT_MODE_ALL -> { mSessionCallback.onSkipToNext() } PlaybackStateCompat.REPEAT_MODE_NONE -> { if (mMusicIndex != mPlayList.size - 1) { mSessionCallback.onSkipToNext() } } } } private var mPreparedListener: MediaPlayer.OnPreparedListener = MediaPlayer.OnPreparedListener { val mediaId = mCurrentMedia?.description?.mediaId ?: "" val metadata = MusicLibrary.getMeteDataFromId(mediaId) mSession.setMetadata(metadata.putDuration(mMediaPlayer.duration.toLong())) mSessionCallback.onPlay() } override fun onLoadChildren( parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>> ) { MusicHelper.log("onLoadChildren, $parentId") result.detach() val list = mPlayList.map { MediaBrowserCompat.MediaItem(it.description, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE) } result.sendResult(list as MutableList<MediaBrowserCompat.MediaItem>?) mCurrentMedia?.let { val mediaId = it?.description?.mediaId ?: "" val metadata = MusicLibrary.getMeteDataFromId(mediaId) mSession.setMetadata(metadata.putDuration(mMediaPlayer.duration.toLong())) setNewState(mState.state) } } override fun onGetRoot( clientPackageName: String, clientUid: Int, rootHints: Bundle? ): BrowserRoot? { return BrowserRoot("MusicService", null) } override fun onCreate() { super.onCreate() mSession = MediaSessionCompat(applicationContext, "MusicService") mSession.setCallback(mSessionCallback) mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS) sessionToken = mSession.sessionToken mMediaPlayer.setOnCompletionListener(mCompletionListener) mMediaPlayer.setOnPreparedListener(mPreparedListener) mMediaPlayer.setOnErrorListener { mp, what, extra -> true } mNotificationManager = MediaNotificationManager(this) mAudioFocusHelper = AudioFocusHelper(this) } override fun onDestroy() { handler.removeMessages(1) super.onDestroy() } /** * 根据当前播放状态,设置 MediaSession 支持的相关操作 */ @PlaybackStateCompat.Actions private fun getAvailableActions(state: Int): Long { var actions = (PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) actions = when (state) { PlaybackStateCompat.STATE_STOPPED -> actions or (PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE) PlaybackStateCompat.STATE_PLAYING -> actions or (PlaybackStateCompat.ACTION_STOP or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_SEEK_TO) PlaybackStateCompat.STATE_PAUSED -> actions or (PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_STOP) else -> actions or (PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_STOP or PlaybackStateCompat.ACTION_PAUSE) } return actions } private fun setNewState(state: Int) { val stateBuilder = PlaybackStateCompat.Builder() stateBuilder.setActions(getAvailableActions(state)) stateBuilder.setState( state, mMediaPlayer.currentPosition.toLong(), 1.0f, SystemClock.elapsedRealtime() ) mState = stateBuilder.build() mSession.setPlaybackState(mState) sessionToken?.let { val description = mCurrentMedia?.description ?: MediaDescriptionCompat.Builder().build() when(state) { PlaybackStateCompat.STATE_PLAYING -> { val notification = mNotificationManager.getNotification(description, mState, it) ContextCompat.startForegroundService( this@MusicService, Intent(this@MusicService, MusicService::class.java) ) startForeground(MediaNotificationManager.NOTIFICATION_ID, notification) } PlaybackStateCompat.STATE_PAUSED -> { val notification = mNotificationManager.getNotification( description, mState, it ) mNotificationManager.notificationManager .notify(MediaNotificationManager.NOTIFICATION_ID, notification) } PlaybackStateCompat.STATE_STOPPED -> { stopSelf() } } } } /** * Helper class for managing audio focus related tasks. */ private inner class AudioFocusHelper(val context: Context) : AudioManager.OnAudioFocusChangeListener { private val MEDIA_VOLUME_DUCK: Float = 0.2f private val MEDIA_VOLUME_DEFAULT: Float = 1.0f public var mPlayOnAudioFocus: Boolean = false private var mAudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager private var mAudioNoisyReceiverRegistered = false /** * 耳机拨出的相关广播 */ private var AUDIO_NOISY_INTENT_FILTER = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY) private var mAudioNoisyReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (AudioManager.ACTION_AUDIO_BECOMING_NOISY == intent?.action) { if (mMediaPlayer.isPlaying) { mSessionCallback.onPause() } } } } fun requestAudioFocus(): Boolean { registerAudioNoisyReceiver() val result = mAudioManager.requestAudioFocus( this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN ) return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED } fun abandonAudioFocus() { unregisterAudioNoisyReceiver() mAudioManager.abandonAudioFocus(this) } override fun onAudioFocusChange(focusChange: Int) { when (focusChange) { /** * 获取音频焦点 */ AudioManager.AUDIOFOCUS_GAIN -> { if (mPlayOnAudioFocus && !mMediaPlayer.isPlaying) { mSessionCallback.onPlay() } else if (mMediaPlayer.isPlaying) { setVolume(MEDIA_VOLUME_DEFAULT) } mPlayOnAudioFocus = false } /** * 暂时失去音频焦点,但可降低音量播放音乐,类似导航模式 */ AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> setVolume(MEDIA_VOLUME_DUCK) /** * 暂时失去音频焦点,一段时间后会重新获取焦点,比如闹钟 */ AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> if (mMediaPlayer.isPlaying) { mPlayOnAudioFocus = true mSessionCallback.onPause() } /** * 失去焦点 */ AudioManager.AUDIOFOCUS_LOSS -> { mAudioManager.abandonAudioFocus(this) mPlayOnAudioFocus = false // 这里暂停播放 mSessionCallback.onPause() } } } private fun setVolume(volume: Float) { mMediaPlayer.setVolume(volume, volume) } fun registerAudioNoisyReceiver() { if (!mAudioNoisyReceiverRegistered) { context.registerReceiver(mAudioNoisyReceiver, AUDIO_NOISY_INTENT_FILTER) mAudioNoisyReceiverRegistered = true } } fun unregisterAudioNoisyReceiver() { if (mAudioNoisyReceiverRegistered) { context.unregisterReceiver(mAudioNoisyReceiver) mAudioNoisyReceiverRegistered = false } } } }
0
null
0
0
518cc93d335dce24db05e4bc2f43d9f29acc934c
18,867
Potato
Apache License 2.0
KodexServer/src/nativeMain/kotlin/com/kodices/kodex/server/plugins/Sockets.kt
Iktwo
732,393,783
false
{"Kotlin": 150536, "Swift": 544}
package com.kodices.kodex.server.plugins import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.routing.routing import io.ktor.server.websocket.WebSockets import io.ktor.server.websocket.webSocket import io.ktor.websocket.Frame import io.ktor.websocket.readText fun Application.configureSockets() { install(WebSockets) { pingPeriodMillis = 15000 timeoutMillis = 15000 maxFrameSize = Long.MAX_VALUE masking = false } routing { webSocket("/kodices") { send(Frame.Text("{}")) for (frame in incoming) { if (frame is Frame.Text) { // TODO: forward messages val text = frame.readText() // outgoing.send(Frame.Text("")) } } } } }
0
Kotlin
0
0
bae9d54ea7244de2d96718de66497928bb0fbcd0
872
Kodices
Apache License 2.0
feature/settings/src/main/kotlin/com/alexeymerov/radiostations/feature/settings/theme/ThemeSettings.kt
AlexeyMerov
636,705,016
false
{"Kotlin": 585746}
package com.alexeymerov.radiostations.feature.settings.theme import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.alexeymerov.radiostations.core.domain.usecase.settings.theme.ThemeSettingsUseCase import com.alexeymerov.radiostations.core.ui.R import com.alexeymerov.radiostations.core.ui.extensions.maxDialogHeight import com.alexeymerov.radiostations.core.ui.extensions.maxDialogWidth import com.alexeymerov.radiostations.core.ui.view.BasicText import com.alexeymerov.radiostations.feature.settings.SettingsTestTags import com.alexeymerov.radiostations.feature.settings.SettingsViewModel @Composable internal fun ThemeSettings( modifier: Modifier, themeState: ThemeSettingsUseCase.ThemeState, onAction: (SettingsViewModel.ViewAction) -> Unit ) { var needShowThemeDialog by rememberSaveable { mutableStateOf(false) } Button( modifier = modifier .background( brush = Brush.linearGradient( colors = listOf( Color(0xFF00639C), Color(0xFF1D6C30), Color(0xFF954A05), ) ), shape = ButtonDefaults.shape ) .height(ButtonDefaults.MinHeight) .testTag(SettingsTestTags.THEME_BUTTON), colors = ButtonDefaults.buttonColors( containerColor = Color.Transparent, contentColor = Color.White ), onClick = { needShowThemeDialog = !needShowThemeDialog } ) { BasicText(text = stringResource(R.string.theme_settings)) } if (needShowThemeDialog) { ThemeDialog( themeState = themeState, onDismiss = { needShowThemeDialog = !needShowThemeDialog }, onViewAction = onAction ) } } @Composable private fun ThemeDialog( themeState: ThemeSettingsUseCase.ThemeState, onDismiss: () -> Unit, onViewAction: (SettingsViewModel.ViewAction) -> Unit ) { val config = LocalConfiguration.current AlertDialog( modifier = Modifier .sizeIn( maxWidth = config.maxDialogWidth(), maxHeight = config.maxDialogHeight() ) .testTag(SettingsTestTags.THEME_DIALOG), onDismissRequest = onDismiss, confirmButton = { Text( modifier = Modifier.clickable(onClick = onDismiss), text = stringResource(R.string.done) ) }, title = { Text(text = stringResource(R.string.theme_settings)) }, text = { Column( modifier = Modifier.verticalScroll(rememberScrollState()) ) { BasicText( modifier = Modifier.padding(horizontal = 16.dp), text = stringResource(R.string.dark_mode), textStyle = MaterialTheme.typography.titleMedium ) DarkThemeOptions(themeState.darkLightMode, onAction = onViewAction) //val isS = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S check is show BasicText( modifier = Modifier.padding(top = 8.dp, start = 16.dp, end = 16.dp), text = stringResource(R.string.dynamic_color), textStyle = MaterialTheme.typography.titleMedium ) DynamicColorOptions(themeState.useDynamicColor, onAction = onViewAction) // AnimatedVisibility - feels like frame drop, smth with AlertDialog, maybe add later if (!themeState.useDynamicColor) { ColorOptions(themeState.colorTheme, onAction = onViewAction) } } } ) } @Composable private fun DarkThemeOptions( darkLightMode: ThemeSettingsUseCase.DarkLightMode, onAction: (SettingsViewModel.ViewAction) -> Unit ) { BasicRadioButton( isSelected = darkLightMode == ThemeSettingsUseCase.DarkLightMode.SYSTEM, text = stringResource(R.string.system), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeDarkMode(ThemeSettingsUseCase.DarkLightMode.SYSTEM)) } ) BasicRadioButton( isSelected = darkLightMode == ThemeSettingsUseCase.DarkLightMode.LIGHT, text = stringResource(R.string.light), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeDarkMode(ThemeSettingsUseCase.DarkLightMode.LIGHT)) } ) BasicRadioButton( isSelected = darkLightMode == ThemeSettingsUseCase.DarkLightMode.DARK, text = stringResource(R.string.dark), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeDarkMode(ThemeSettingsUseCase.DarkLightMode.DARK)) } ) BasicRadioButton( isSelected = darkLightMode == ThemeSettingsUseCase.DarkLightMode.NIGHT, text = stringResource(R.string.night), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeDarkMode(ThemeSettingsUseCase.DarkLightMode.NIGHT)) } ) } @Composable private fun DynamicColorOptions( useDynamicColor: Boolean, onAction: (SettingsViewModel.ViewAction) -> Unit ) { BasicRadioButton( isSelected = useDynamicColor, text = stringResource(R.string.yes), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeDynamicColor(true)) } ) BasicRadioButton( isSelected = !useDynamicColor, text = stringResource(R.string.no), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeDynamicColor(false)) } ) } @Composable private fun ColorOptions( colorTheme: ThemeSettingsUseCase.ColorTheme, onAction: (SettingsViewModel.ViewAction) -> Unit ) { Text( modifier = Modifier.padding(top = 8.dp, start = 16.dp, end = 16.dp), text = stringResource(R.string.color), style = MaterialTheme.typography.titleMedium ) BasicRadioButton( isSelected = colorTheme == ThemeSettingsUseCase.ColorTheme.DEFAULT_BLUE, text = stringResource(R.string.default_blue), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeColorScheme(ThemeSettingsUseCase.ColorTheme.DEFAULT_BLUE)) } ) BasicRadioButton( isSelected = colorTheme == ThemeSettingsUseCase.ColorTheme.GREEN, text = stringResource(R.string.green), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeColorScheme(ThemeSettingsUseCase.ColorTheme.GREEN)) } ) BasicRadioButton( isSelected = colorTheme == ThemeSettingsUseCase.ColorTheme.ORANGE, text = stringResource(R.string.orange), action = { onAction.invoke(SettingsViewModel.ViewAction.ChangeColorScheme(ThemeSettingsUseCase.ColorTheme.ORANGE)) } ) } @Composable private fun BasicRadioButton( isSelected: Boolean, text: String, action: () -> Unit ) { Row( modifier = Modifier .wrapContentWidth() .selectable( selected = isSelected, role = Role.RadioButton, onClick = action, ) .padding(start = 24.dp, end = 16.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { RadioButton( modifier = Modifier.padding(top = 2.dp), //by default not aligned with text center selected = isSelected, onClick = null ) Text( modifier = Modifier.padding(start = 8.dp), text = text ) } } @Composable @Preview private fun PreviewRadioButton() { BasicRadioButton(true, "Some text", {}) }
0
Kotlin
0
2
cff341b2e7072da7bb75d934f025e96e0b92ac60
9,072
RadioStations
MIT License
app/src/main/java/com/tripletres/platformscience/data/repo/ShipmentRepository.kt
daniel553
540,959,283
false
null
package com.tripletres.platformscience.data.repo import com.tripletres.platformscience.data.db.shipment.ShipmentDao import com.tripletres.platformscience.data.db.shipment.ShipmentEntity import javax.inject.Inject /** * Shipments Repository */ class ShipmentRepository @Inject constructor( private val shipmentDao: ShipmentDao ) { suspend fun saveShipments(shipments: List<ShipmentEntity>) = shipmentDao.insertAll(shipments) suspend fun getShipmentsFromDB(): List<ShipmentEntity> = shipmentDao.getAll() suspend fun clearShipmentsFromDB() = shipmentDao.deleteAll() }
0
Kotlin
0
0
2ea5962dc0ad349ae97b277ab4ecf9e9a0aee1e6
586
PlatformScience
FSF All Permissive License
src/models/area/AreaRepository.kt
raquezha
367,705,578
false
{"Kotlin": 16719, "HTML": 171}
package com.raquezha.heograpiya.models.area class AreaRepository { private val records = mutableListOf<Province>() val all: Areas get() = Areas(records) fun insert(provinceName: String, cityMunicipality: MutableList<CityMunicipality>) { records += Province( province = provinceName, cityMuncipality = cityMunicipality ) } } val areaRecord = AreaRepository().apply { insert( provinceName = "Albay", cityMunicipality = mutableListOf( "Legazpi City", "Ligao City", "Tabaco City", "Bacacay", "Camalig", "Daraga", "Guinobatan", "Jovellar", "Libon", "Malilipot", "Malinao", "Manito", "Oas", "Pio Duran", "Polangui", "Rapu-Rapu", "Santo Domingo", "Tiwi" ).toCityMunicipality() ) insert( provinceName = "Camarines Norte", cityMunicipality = mutableListOf( "Basud", "Capalonga", "Daet", "<NAME>", "Labo", "Mercedes", "Paracale", "San Lorenzo Ruiz", "San Vicente", "Santa Elena", "Vinzons", "Talisay" ).toCityMunicipality() ) insert( provinceName = "Camarines Sur", cityMunicipality = mutableListOf( "Iriga City", "Naga City", "Nabua", "Baao", "Pili", "Calabanga", "Pasacao", "Tinambac", "Ragay", "Sagñay", "Tigaon", "Tinamabac", "Minalabac", "Milaor", "Canaman", "Magarao", "Pamplona", "Lupi", "Libmanan", "Lagonoy", "Goa", "Garchitorena", "Gainza", "Del Gallego", "Caramoan", "Camaligan", "Buhi", "Bombon", "Cabusa", "Balatan" ).toCityMunicipality() ) insert( provinceName = "Masbate", cityMunicipality = mutableListOf( "Mabaste City", "Aroroy", "Baleno", "Balud", "Batuan", "Cataingan", "Cawayan", "Claveria", "Dimasalan", "Esperanza", "Mandaon", "Milagros", "Mobo", "Monreal", "Palanas", "Pio V<NAME>", "Placer", "San Fernando", "San Jacinto", "San Pascual", "Uson" ).toCityMunicipality() ) insert( provinceName = "Sorsogon", cityMunicipality = mutableListOf( "Bagamanoc", "Baras", "Bato", "Caramoran", "Gigmoto", "Pandan", "Panganiban", "San Adres", "San Miguel", "Viga", ).toCityMunicipality() ) insert( provinceName = "Catanduanes", cityMunicipality = mutableListOf( "Barcelona", "Bulan", "Bulusan", "Casiguran", "Castilla", "Donsol", "Gubat", "Irosin", "Juban", "Magallanes", "Matnog", "Pilar", "Prieto Diaz", "Santa Magdalena" ).toCityMunicipality() ) } fun MutableList<String>.toCityMunicipality(): MutableList<CityMunicipality> { return map { CityMunicipality(it) }.toMutableList() }
0
Kotlin
0
0
755c09f806606aaa6a48d76ade46d45a05a587ca
3,821
heograpiya-server
MIT License
app/src/main/java/org/simple/clinic/monthlyreports/list/MonthlyReportsUpdate.kt
simpledotorg
132,515,649
false
{"Kotlin": 6129044, "Shell": 1660, "HTML": 545}
package org.simple.clinic.monthlyreports.list import com.spotify.mobius.Next import com.spotify.mobius.Update import org.simple.clinic.mobius.dispatch class MonthlyReportsUpdate : Update<MonthlyReportsModel, MonthlyReportsEvent, MonthlyReportsEffect> { override fun update(model: MonthlyReportsModel, event: MonthlyReportsEvent): Next<MonthlyReportsModel, MonthlyReportsEffect> { return when (event) { is BackButtonClicked -> Next.dispatch(setOf(GoBack)) is CurrentFacilityLoaded -> Next.next(model.currentFacilityLoaded(event.facility)) is MonthlyReportsFetched -> Next.next(model.monthlyReportsLoaded(event.responseList)) is MonthlyReportItemClicked -> dispatch(OpenMonthlyReportForm(event.questionnaireType, event.questionnaireResponse)) } } }
13
Kotlin
73
236
ff699800fbe1bea2ed0492df484777e583c53714
795
simple-android
MIT License
base/src/main/java/ru/androidpirates/aiweather/common/util/UiUtils.kt
Luckyss
135,089,769
false
{"Kotlin": 111674}
package ru.androidpirates.aiweather.common.util import android.content.res.Resources import android.graphics.drawable.ColorDrawable import android.graphics.drawable.StateListDrawable import android.support.annotation.ColorInt object UiUtils { fun dpToPx(value: Float): Int { val density = Resources.getSystem().displayMetrics.density return if (value != 0f) Math.ceil((density * value).toDouble()).toInt() else 0 } fun getSelectableBackground(@ColorInt colorSelected: Int, @ColorInt colorNormal: Int): StateListDrawable { val states = StateListDrawable() val clrActive = ColorDrawable(adjustAlpha(colorSelected, 0x3A)) states.addState(intArrayOf(android.R.attr.state_selected), clrActive) states.addState(intArrayOf(), ColorDrawable(colorNormal)) states.setEnterFadeDuration(200) states.setExitFadeDuration(200) return states } fun adjustAlpha(color: Int, alpha: Int): Int { return alpha shl 24 or (color and 0x00ffffff) } }
0
Kotlin
0
0
e1f4e39a153de104f5983b48b478ae751feaa36d
1,059
aiweather
Apache License 2.0
stubs/src/main/kotlin/android/app/IntentService.kt
JuulLabs
233,767,951
false
{"Kotlin": 94016}
package android.app import android.content.Intent @Suppress("UNUSED_PARAMETER") // This is a stub abstract class IntentService(name: String) : Service() { abstract fun onHandleIntent(intent: Intent?): Unit }
6
Kotlin
2
8
633c778879edd1661e42a65cbdbe3ee822284251
214
exercise
Apache License 2.0
compiler/testData/diagnostics/testsWithStdLib/contracts/dsl/errors/nestedConditionalEffects.fir.kt
JetBrains
3,432,266
false
null
// LANGUAGE: +AllowContractsForCustomFunctions +UseReturnsEffect // OPT_IN: kotlin.contracts.ExperimentalContracts // DIAGNOSTICS: -INVISIBLE_REFERENCE -INVISIBLE_MEMBER import kotlin.contracts.* fun foo(boolean: Boolean) { contract { <!ERROR_IN_CONTRACT_DESCRIPTION!>(returns() implies (boolean)) <!UNRESOLVED_REFERENCE!>implies<!> (!boolean)<!> } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
368
kotlin
Apache License 2.0
src/kz/seasky/tms/route/api/v1/User.kt
task-management-system
316,950,217
false
null
package kz.seasky.tms.route.api.v1 import io.ktor.application.* import io.ktor.http.* import io.ktor.request.* import io.ktor.routing.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.uuid.UUID import kz.seasky.tms.exceptions.ErrorException import kz.seasky.tms.extensions.* import kz.seasky.tms.features.withPermission import kz.seasky.tms.model.authentication.AuthenticationPrincipal import kz.seasky.tms.model.user.UserChangePassword import kz.seasky.tms.model.user.UserInsert import kz.seasky.tms.model.user.UserUpdate import kz.seasky.tms.repository.user.UserService import kz.seasky.tms.utils.Permission import org.koin.ktor.ext.inject fun Route.user() { val service: UserService by inject() route("/user") { get("current") { val principal = call.getPrincipal<AuthenticationPrincipal>() call.success(data = service.getById(principal.id)) } withPermission(Permission.ViewUser.power or Permission.Administrator.power) { get { val id = call.getId<String>() call.success(data = service.getById(id)) } } withPermission(Permission.InsertUser.power or Permission.Administrator.power) { put { val user = call.receiveAndValidate<UserInsert>() call.success( statusCode = HttpStatusCode.Created, message = "Пользователь успешно добавлен", data = service.insert(user) ) } } withPermission(Permission.DeleteUser.power or Permission.Administrator.power) { delete { val id = call.getId<String>() service.deleteById(id) call.success( message = "Пользователь успешно удален", data = mapOf("id" to id) ) } } patch { val principal = call.getPrincipal<AuthenticationPrincipal>() val user = call.receiveAndValidate<UserUpdate>() val permission = Permission.Administrator.power val isCurrentUser = principal.id == user.id val isPermissionEnough = principal.power and permission != 0L if (!isCurrentUser) { if (!isPermissionEnough) throw ErrorException("У вас недостаточно прав") } val result = if (isCurrentUser && !isPermissionEnough) service.updateAsUser(user) else service.update(user) call.success( message = "Пользователь успешно обновлен", data = result ) } patch("/change-password") { val principal = call.getPrincipal<AuthenticationPrincipal>() val user = call.receiveAndValidate<UserChangePassword>() if (principal.id != user.id) throw ErrorException("Не пытайтесь поменять пароль другому пользователю") service.validatePassword(user.id.asUUID(), user.oldPassword) call.success( message = "Пароль успешно изменен", data = service.changePassword(user.id.asUUID(), user.newPassword) ) } patch("/upload-avatar") { val userId = call.getPrincipal<AuthenticationPrincipal>().id.asUUID() val contentType = call.request.contentType() if (contentType != ContentType.Image.JPEG && contentType != ContentType.Image.PNG) throw ErrorException("Неверный формат файла") val stream = withContext(Dispatchers.IO) { call.receiveStream() } call.success( message = "Аватарка успешно сохранена", data = service.uploadAvatar(userId, contentType, stream) ) } withPermission(Permission.UpdateUser.power or Permission.Administrator.power) { patch("/lock") { val id = call.getId<UUID>() call.success( message = "Пользователь заблокирован", data = service.lock(id) ) } patch("/unlock") { val id = call.getId<UUID>() call.success( message = "Пользователь разблокирован", data = service.unlock(id) ) } } } route("/users") { withPermission(Permission.ViewUser.power or Permission.Administrator.power) { get { call.success(data = service.getAll()) } get("/available") { val userId = call.getPrincipal<AuthenticationPrincipal>().id.asUUID() call.success(data = service.getAllAvailable(userId)) } } withPermission(Permission.UpdateUser.power or Permission.Administrator.power) { //FIXME put { val users = call.receiveOrException<Array<UserInsert>>().toList() call.success( message = "Пользователи успешно добавлены", data = service.batchInsert(users) ) } } } }
2
Kotlin
0
0
2b04062328d79ac2f77bece9ae7d660c06911ecd
5,232
backend
MIT License
app/src/main/java/com/raassh/gemastik15/di/NetworkModule.kt
raassh-23
540,716,155
false
null
package com.raassh.gemastik15.di import com.raassh.gemastik15.BuildConfig import com.raassh.gemastik15.api.ApiService import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory val networkModule = module { single { OkHttpClient.Builder() .addInterceptor( HttpLoggingInterceptor().setLevel( if (BuildConfig.DEBUG) { HttpLoggingInterceptor.Level.BODY } else { HttpLoggingInterceptor.Level.NONE } ) ) .build() } single { Retrofit.Builder() .baseUrl(BuildConfig.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(get()) .build() .create(ApiService::class.java) } }
4
Kotlin
0
1
b374d5fe9636db1af6623804b2bdcce301aa55d3
971
PPL-Gemastik-15-Android
MIT License
app/src/main/java/com/example/temi_beta/api/confirm_order.kt
kaomao1234
700,679,188
false
{"Kotlin": 96630, "Python": 6013}
package com.example.temi_beta.api import fuel.HttpResponse import fuel.httpPut suspend fun confirm_order(status: String): Boolean? { val body = mapOf( "order_status" to status ) val response: HttpResponse = "https://fastapideta-1-v4049125.deta.app/confirm_order/{orders}".httpPut(body = body.toString()) return if(response.statusCode == 200){ true }else{ null } }
0
Kotlin
0
0
3645e45cce1dedcb6f1da327f57344641f1b069f
422
temibeta
MIT License
immersionbar/src/main/java/com/gyf/immersionbar/EMUI3NavigationBarObserver.kt
jacyayj
391,803,949
false
null
package com.gyf.immersionbar import android.app.Application import android.database.ContentObserver import android.os.Build import android.os.Handler import android.os.Looper import android.provider.Settings import java.util.* /** * 华为Emui3状态栏监听器 * * @author geyifeng * @date 2019/4/10 6:02 PM */ internal object EMUI3NavigationBarObserver : ContentObserver(Handler(Looper.getMainLooper())) { private var mCallbacks: ArrayList<ImmersionCallback>? = null private lateinit var mApplication: Application private var mIsRegister = false fun register(application: Application) { mApplication = application if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mApplication.contentResolver != null && !mIsRegister) { val uri = Settings.System.getUriFor(Constants.IMMERSION_EMUI_NAVIGATION_BAR_HIDE_SHOW) if (uri != null) { mApplication.contentResolver.registerContentObserver(uri, true, this) mIsRegister = true } } } override fun onChange(selfChange: Boolean) { super.onChange(selfChange) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mApplication.contentResolver != null && mCallbacks != null && !mCallbacks!!.isEmpty()) { val show = Settings.System.getInt( mApplication.contentResolver, Constants.IMMERSION_EMUI_NAVIGATION_BAR_HIDE_SHOW, 0 ) for (callback in mCallbacks!!) { callback.onNavigationBarChange(show != 1) } } } fun addOnNavigationBarListener(callback: ImmersionCallback?) { if (callback == null) { return } if (mCallbacks == null) { mCallbacks = ArrayList() } if (!mCallbacks!!.contains(callback)) { mCallbacks!!.add(callback) } } fun removeOnNavigationBarListener(callback: ImmersionCallback?) { if (callback == null || mCallbacks == null) { return } mCallbacks!!.remove(callback) } }
0
Kotlin
0
1
d562ff1c2179d760f7267a5a5077211e8c71d63e
2,133
ImmersionBar_Fork
Apache License 2.0
app/src/main/java/com/liflymark/normalschedule/logic/utils/GetDataUtil.kt
sasaju
395,209,845
false
null
package com.liflymark.normalschedule.logic.utils import android.annotation.SuppressLint import java.text.SimpleDateFormat import java.util.* internal object GetDataUtil { // 修改开学日期仅需修改此处 如2021.8.23 则 GregorianCalendar(2021, 7, 23),January-0 private val firstWeekMondayDate = GregorianCalendar(2021, 7, 23) //获取当前完整的日期和时间 @SuppressLint("SimpleDateFormat") fun getNowDateTime(): String? { val sdf = SimpleDateFormat("yyyy/MM/dd") return sdf.format(Date()) } @SuppressLint("SimpleDateFormat") fun getNowMonth(whichColumn:Int, whichWeek:Int): String { val sdf = SimpleDateFormat("MM月dd日") val column = when(whichColumn){ 1 -> "周一" 2 -> "周二" 3 -> "周三" 4 -> "周四" 5 -> "周五" 6 -> "周六" 7 -> "周日" else -> "错误" } return sdf.format(Date())+" | "+column } @SuppressLint("SimpleDateFormat") fun getThreeDay():List<String>{ val threeDay = mutableListOf<String>() val sdf = SimpleDateFormat("yyyy-MM-dd") val calendar = GregorianCalendar() calendar.add(Calendar.DATE, -1) threeDay.add(sdf.format(calendar.time)) repeat(2){ calendar.add(Calendar.DATE, 1) threeDay.add(sdf.format(calendar.time)) } threeDay.add("2021-08-29") return threeDay.toList() } @SuppressLint("SimpleDateFormat") fun getNowSimpleDateFormat(): SimpleDateFormat { val sdf = SimpleDateFormat() sdf.format(Date()) return sdf } /** * 根据毫秒转换为yyyy-MM-dd */ @SuppressLint("SimpleDateFormat") fun getDateStrByMillis(millis:Long): String { val sdf = SimpleDateFormat("yyyy-MM-dd") val date = GregorianCalendar() date.timeInMillis = millis return sdf.format(date.time) } /** * 计算几天之后的日期并转换为毫秒 */ fun getDayMillis(afterToady:Int):Long{ val calendar = GregorianCalendar() calendar.add(Calendar.DATE, afterToady) return calendar.timeInMillis } /** * 判断当前周几 * 周一-》1 * 周二-》2 ... */ fun getNowWeekNum(): Int { val now = GregorianCalendar() // Log.d("GEtDataUtil", sdf.format(Date())) return when(now.get(Calendar.DAY_OF_WEEK)){ Calendar.MONDAY -> 1 Calendar.TUESDAY -> 2 Calendar.WEDNESDAY -> 3 Calendar.THURSDAY -> 4 Calendar.FRIDAY -> 5 Calendar.SATURDAY -> 6 Calendar.SUNDAY -> 7 else -> 7 } } fun dateMinusDate(first: GregorianCalendar, second: GregorianCalendar): Int{ /** * 如果年数一致则DAY_OF_YEAR直接相减 * 否则就进行判断 */ var result = 0 val firstDayOfYear = first.get(Calendar.DAY_OF_YEAR) val secondDayOfYear = second.get(Calendar.DAY_OF_YEAR) result = if (first.get(Calendar.YEAR)==second.get(Calendar.YEAR)){ firstDayOfYear - secondDayOfYear } else { val firstAllYearDay = if (first.isLeapYear(first.get(Calendar.YEAR))){ 366 } else { 365 } val secondAllYearDay = if (first.isLeapYear(first.get(Calendar.YEAR))){ 366 } else { 365 } if (first.after(second)){ secondAllYearDay - secondDayOfYear + firstDayOfYear } else{ -(firstAllYearDay-firstDayOfYear + secondDayOfYear) } } return result } fun whichWeekNow(): Int { val now = GregorianCalendar() val result = dateMinusDate(now, firstWeekMondayDate) if (result < 0){ return 0 } return result / 7 } fun startSchool(): Boolean{ val now = GregorianCalendar() val result = dateMinusDate(now, firstWeekMondayDate) return result >= 0 } fun startSchoolDay(): Int { val now = GregorianCalendar() return dateMinusDate(now, firstWeekMondayDate) } //获取当前时间 fun getNowTime(): GregorianCalendar { return GregorianCalendar() } fun getFirstWeekMondayDate() = firstWeekMondayDate /** * 2021年-year-2021 * 2月-month-1 */ fun getMonthAllDay(year:Int,month:Int):List<String>{ val calendar = GregorianCalendar() calendar.set(Calendar.YEAR, year) calendar.set(Calendar.MONTH, month) val maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH) return (1..maxDay).toList().map { it.toString() } } fun getCalendarByMillis(millis: Long): GregorianCalendar { val calendar = GregorianCalendar() calendar.timeInMillis = millis return calendar } }
0
Kotlin
0
1
50bc2e8ca2a9711046ddaef276793285867dd98e
4,753
NormalSchedulePublic
Apache License 2.0
sample/src/main/kotlin/br/com/zup/beagle/sample/AppAnalytics.kt
ZupIT
391,144,851
false
null
/* * Copyright 2020, 2022 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 br.com.zup.beagle.sample import android.util.Log import br.com.zup.beagle.android.analytics.AnalyticsConfig import br.com.zup.beagle.android.analytics.AnalyticsProvider import br.com.zup.beagle.android.analytics.AnalyticsRecord import br.com.zup.beagle.android.annotation.BeagleComponent @BeagleComponent class AppAnalytics : AnalyticsProvider { override fun getConfig(): AnalyticsConfig = object : AnalyticsConfig { override var actions: Map<String, List<String>>? = hashMapOf( "beagle:alert" to listOf("message", "title") ) override var enableScreenAnalytics: Boolean? = true } override fun createRecord(record: AnalyticsRecord) { Log.i("analytics2", record.toString()) } }
0
Kotlin
13
20
0240e15aa07e31d390e67dbeed4789b2b7ab76da
1,382
beagle-android
Apache License 2.0
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/device/TabletFill.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.TabletFill: ImageVector get() { if (_tabletFill != null) { return _tabletFill!! } _tabletFill = Builder(name = "TabletFill", 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(5.0f, 2.0f) horizontalLineTo(19.0f) curveTo(19.552f, 2.0f, 20.0f, 2.448f, 20.0f, 3.0f) verticalLineTo(21.0f) curveTo(20.0f, 21.552f, 19.552f, 22.0f, 19.0f, 22.0f) horizontalLineTo(5.0f) curveTo(4.448f, 22.0f, 4.0f, 21.552f, 4.0f, 21.0f) verticalLineTo(3.0f) curveTo(4.0f, 2.448f, 4.448f, 2.0f, 5.0f, 2.0f) close() moveTo(12.0f, 17.0f) curveTo(11.448f, 17.0f, 11.0f, 17.448f, 11.0f, 18.0f) curveTo(11.0f, 18.552f, 11.448f, 19.0f, 12.0f, 19.0f) curveTo(12.552f, 19.0f, 13.0f, 18.552f, 13.0f, 18.0f) curveTo(13.0f, 17.448f, 12.552f, 17.0f, 12.0f, 17.0f) close() } } .build() return _tabletFill!! } private var _tabletFill: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,095
compose-icon-collections
MIT License
app/src/main/java/com/otus/securehomework/security/AesKeystoreWrapperImpl.kt
flaming565
469,196,622
true
{"Kotlin": 36792}
package com.otus.securehomework.security; import android.content.Context import android.os.Build import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import androidx.annotation.RequiresApi import androidx.biometric.BiometricPrompt import java.security.SecureRandom import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec class AesKeystoreWrapperImpl( private val context: Context, private val rsaEncryptionService: RsaEncryptionService ) : KeystoreWrapper, BaseKeystoreWrapperImpl() { private val sharedPreferences by lazy { context.getSharedPreferences("AesKeystoreWrapper", Context.MODE_PRIVATE) } override fun encryptData(data: ByteArray): Pair<ByteArray, ByteArray> { val cipher = getCipher() cipher.init(Cipher.ENCRYPT_MODE, getSymmetricKey()) return cipher.iv to cipher.doFinal(data) } override fun decryptData(encryptedData: ByteArray, ivBytes: ByteArray): ByteArray { val cipher = getCipher() getCipher().init(Cipher.DECRYPT_MODE, getSymmetricKey(), GCMParameterSpec(128, ivBytes)) return cipher.doFinal(encryptedData) } fun getBiometricCryptoObject(): BiometricPrompt.CryptoObject { val cipher = getCipher() val secretKey = getSymmetricKey() cipher.init(Cipher.ENCRYPT_MODE, secretKey) return BiometricPrompt.CryptoObject(cipher) } private fun getCipher(): Cipher = Cipher.getInstance(AES_NOPAD_TRANS) private fun getSymmetricKey(): SecretKey { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!isKeyExists(keyStore)) { createSymmetricKey() } keyStore.getKey(KEY_ALIAS, null) as SecretKey } else { getSymmetricKeyFromPrefs() } } @RequiresApi(Build.VERSION_CODES.M) private fun createSymmetricKey(): SecretKey { val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE) val keyGenParameterSpec = KeyGenParameterSpec.Builder( KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT ) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .setUserAuthenticationRequired(true) .setRandomizedEncryptionRequired(true) .build() keyGenerator.init(keyGenParameterSpec) return keyGenerator.generateKey() } private fun getSymmetricKeyFromPrefs(): SecretKey { val base64Key = sharedPreferences.getString(RSA_KEY_NAME, null) return base64Key?.let { base64 -> rsaEncryptionService.decrypt(base64)?.let { SecretKeySpec(it.toByteArray(Charsets.UTF_8), "AES") } } ?: createSymmetricKeyInPrefs() } private fun createSymmetricKeyInPrefs(): SecretKey { val key = ByteArray(32) SecureRandom().run { nextBytes(key) } val encryptedKey = rsaEncryptionService.encrypt(key) sharedPreferences.edit().apply { putString(RSA_KEY_NAME, encryptedKey) apply() } return SecretKeySpec(key, "AES") } companion object { const val AES_NOPAD_TRANS = "AES/GCM/NoPadding" const val RSA_KEY_NAME = "key_rsa_key_name" } }
0
Kotlin
0
0
397155b13ea894b7fb84aa95236f864ba6011a3e
3,536
homework_secure_storage
The Unlicense
app/src/main/java/com/yugyd/idiomatic/android/gradle/ui/sample21/Sample1Fragment.kt
Yugyd
686,269,894
false
{"Kotlin": 313957, "Shell": 2314}
package com.yugyd.idiomatic.android.gradle.ui.sample21 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.yugyd.idiomatic.android.gradle.data.sample21.Sample21Repository import com.yugyd.idiomatic.android.gradle.data.sample21.Sample21RepositoryImpl import com.yugyd.idiomatic.android.gradle.databinding.FragmentSample21Binding import com.yugyd.idiomatic.android.gradle.domain.sample21.Sample21UseCase import kotlinx.coroutines.launch class Sample21Fragment : Fragment() { private var _binding: FragmentSample21Binding? = null private val binding get() = _binding!! private val viewModelFactory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { val repository: Sample21Repository = Sample21RepositoryImpl() val useCase = Sample21UseCase(repository) return Sample21ViewModel(useCase) as T } } private val viewModel: Sample21ViewModel by viewModels { viewModelFactory } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSample21Binding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textTitle val button: Button = binding.buttonAction button.setOnClickListener { Toast.makeText(requireContext(), "Click!", Toast.LENGTH_SHORT).show() } lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.CREATED) { viewModel.state.collect { textView.text = it.title button.text = it.title } } } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
1
2
9d5b99856a9e0cf3bbc7c40676725113236d73ac
2,337
idiomatic-android-gradle
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/ui/theme/Type.kt
fumiyasac
344,090,494
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp val typography = Typography( h4 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 34.sp, letterSpacing = (0.25).sp ), h5 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 24.sp ), subtitle1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, letterSpacing = (0.5).sp ), body2 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 14.sp, letterSpacing = (0.25).sp ), button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 14.sp, letterSpacing = (1.25).sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp, letterSpacing = (0.4).sp ) )
0
Kotlin
0
0
f1ee1adcd84f105228468d741072aa0382b497a9
1,904
JetpackComposePractice1
Apache License 2.0
idea/testData/refactoring/introduceVariable/extractToScope/implicitThisInsideNestedLamba.kt
JakeWharton
99,388,807
true
null
// IGNORE_K2 class A(val a: Int) class B(val b: Int) fun foo(f: A.() -> Int) = A(1).f() fun bar(f: B.() -> Int) = B(2).f() fun test() { foo { bar { a + <selection>b</selection> } } }
251
Kotlin
5079
83
4383335168338df9bbbe2a63cb213a68d0858104
188
kotlin
Apache License 2.0
src/main/kotlin/com/github/vhromada/common/provider/UuidProvider.kt
vhromada
795,933,875
false
null
package com.github.vhromada.catalog.provider /** * An interface represents provider for UUID. * * @author <NAME> */ interface UuidProvider { /** * Returns UUID. * * @return UUID */ fun getUuid(): String }
0
Kotlin
0
0
9feab9abeb8b1ae84ae9c5e1d3c81ef7df7d0f97
240
catalog-be
MIT License
src/main/kotlin/no/nav/sokos/skattekort.person/config/PropertiesConfig.kt
navikt
576,396,849
false
{"Kotlin": 69131, "Shell": 1582, "Dockerfile": 143}
package no.nav.sokos.skattekort.person.config import com.natpryce.konfig.ConfigurationMap import com.natpryce.konfig.ConfigurationProperties import com.natpryce.konfig.EnvironmentVariables import com.natpryce.konfig.Key import com.natpryce.konfig.overriding import com.natpryce.konfig.stringType import java.io.File object PropertiesConfig { private val defaultProperties = ConfigurationMap( mapOf( "NAIS_APP_NAME" to "sokos-skattekort-person", "NAIS_NAMESPACE" to "okonomi", ) ) private val localDevProperties = ConfigurationMap( mapOf( "USE_AUTHENTICATION" to "true", "APPLICATION_PROFILE" to Profile.LOCAL.toString(), "DATABASE_HOST" to "databaseHost", "DATABASE_PORT" to "databasePort", "DATABASE_NAME" to "databaseName", "DATABASE_SCHEMA" to "databaseSchema", "DATABASE_USERNAME" to "databaseUsername", "DATABASE_PASSWORD" to "<PASSWORD>", "AZURE_APP_CLIENT_ID" to "azure-app-client-id", "AZURE_APP_WELL_KNOWN_URL" to "azure-app-well-known-url", "PDL_HOST" to "pdlHost", "PDL_SCOPE" to "pdlScope" ) ) private val devProperties = ConfigurationMap(mapOf("APPLICATION_PROFILE" to Profile.DEV.toString())) private val prodProperties = ConfigurationMap(mapOf("APPLICATION_PROFILE" to Profile.PROD.toString())) private val config = when (System.getenv("NAIS_CLUSTER_NAME") ?: System.getProperty("NAIS_CLUSTER_NAME")) { "dev-fss" -> ConfigurationProperties.systemProperties() overriding EnvironmentVariables() overriding devProperties overriding defaultProperties "prod-fss" -> ConfigurationProperties.systemProperties() overriding EnvironmentVariables() overriding prodProperties overriding defaultProperties else -> ConfigurationProperties.systemProperties() overriding EnvironmentVariables() overriding ConfigurationProperties.fromOptionalFile( File("defaults.properties") ) overriding localDevProperties overriding defaultProperties } private operator fun get(key: String): String = config[Key(key, stringType)] data class Configuration( val naisAppName: String = get("NAIS_APP_NAME"), val profile: Profile = Profile.valueOf(this["APPLICATION_PROFILE"]), val useAuthentication: Boolean = get("USE_AUTHENTICATION").toBoolean(), val azureAdConfig: AzureAdConfig = AzureAdConfig(), val databaseConfig: OseskattDatabaseConfig = OseskattDatabaseConfig() ) data class AzureAdConfig( val clientId: String = this["AZURE_APP_CLIENT_ID"], val wellKnownUrl: String = this["AZURE_APP_WELL_KNOWN_URL"] ) data class OseskattDatabaseConfig( val host: String = get("DATABASE_HOST"), val port: String = get("DATABASE_PORT"), val name: String = get("DATABASE_NAME"), val schema: String = get("DATABASE_SCHEMA"), val username: String = get("DATABASE_USERNAME"), val password: String = get("DATABASE_PASSWORD"), val jdbcDriver: String = "oracle.jdbc.OracleDriver", val poolName: String = "HikariPool-OSESKATT" ) { val jdbcUrl: String = "jdbc:oracle:thin:@$host:$port/$name" } data class AzureAdClientConfig( val clientId: String = get("AZURE_APP_CLIENT_ID"), val wellKnownUrl: String = get("AZURE_APP_WELL_KNOWN_URL"), val tenantId: String = get("AZURE_APP_TENANT_ID"), val clientSecret: String = get("AZURE_APP_CLIENT_SECRET"), ) data class PdlConfig( val pdlHost: String = get("PDL_HOST"), val pdlScope: String = get("PDL_SCOPE") ) enum class Profile { LOCAL, DEV, PROD } }
1
Kotlin
0
0
b3b85c516c19cacda311d862a49c600321e6c1c5
3,807
sokos-skattekort-person
MIT License
app_ios/locolaser-kotlin-multiplatform-example/src/main/kotlin/ru/pocketbyte/locolaser/example/repository/IosStringRepository.kt
aspineon
286,246,019
true
{"JavaScript": 96117, "Kotlin": 9581, "Swift": 5998, "Objective-C": 549, "HTML": 521}
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the LocoLaser tool. * It should not be modified by hand. */ package ru.pocketbyte.locolaser.example.repository import kotlinx.cinterop.* import platform.Foundation.* import ru.pocketbyte.locolaser.example.repository.StringRepository public class IosStringRepository(private val bundle: NSBundle, private val tableName: String): StringRepository { constructor(bundle: NSBundle) : this(bundle, "Localizable") constructor(tableName: String) : this(NSBundle.mainBundle(), tableName) constructor() : this(NSBundle.mainBundle(), "Localizable") override public val app_name: String get() = this.bundle.localizedStringForKey("app_name", "", this.tableName) override public val screen_main_hello_text: String get() = this.bundle.localizedStringForKey("screen_main_hello_text", "", this.tableName) }
0
null
0
0
05c0fb7ec72bbe393e4c373dd7df3ec8bd77987a
921
locolaser-kotlin-mpp-example
Apache License 2.0
src/main/kotlin/uk/co/alephn/koptim/domain/Expression.kt
breandan
289,413,166
true
{"Kotlin": 24176}
package uk.co.alephn.koptim.domain import uk.co.alephn.koptim.LPSolver sealed class Expr { lateinit var solver: LPSolver operator fun plus(other: Expr) = Add(this, other).apply { solver = [email protected] } operator fun plus(other: Number) = Add(this, Const(other)).apply { solver = [email protected] } operator fun minus(other: Expr) = Sub(this, other).apply { solver = [email protected] } operator fun minus(other: Number) = Sub(this, Const(other)).apply { solver = [email protected] } operator fun times(other: Expr): Expr { require(this !is LPVar || other !is LPVar, { "Non linear functions are not allowed" }) return Mult(this, other).apply { solver = [email protected] } } operator fun times(other: Number) = Mult(this, Const(other)).apply { solver = [email protected] } operator fun unaryMinus() = Mult(Const(-1), this).apply { solver = [email protected] } operator fun compareTo(c: Number): Int { solver.constraints += Constraint(this, c) return 1 } } data class Const(var number: Number) : Expr() data class LPVar(val index: Int) : Expr() { var value = 0.0 } data class Add(val e1: Expr, val e2: Expr) : Expr() data class Sub(val e1: Expr, val e2: Expr) : Expr() data class Mult(val e1: Expr, val e2: Expr) : Expr() data class Constraint(val e: Expr, val b: Number)
0
Kotlin
0
0
8d78cb53bcf5e5449ff74c1d30c7b216abda700d
1,365
koptim
Apache License 2.0
inject/src/main/java/com/heyanle/inject/core/InjectMain.kt
easybangumiorg
413,723,669
false
{"Kotlin": 1490799, "Java": 761739, "Shell": 450}
package com.heyanle.inject.core import com.heyanle.inject.api.InjectScope import com.heyanle.inject.api.fullType import com.heyanle.inject.api.get /** * 顶层默认 scope * Created by HeYanLe on 2023/7/29 20:00. * https://github.com/heyanLE */ val Inject: InjectScope = DefaultInjectScope() inline fun <reified T : Any> injectLazy(): Lazy<T> { return lazy { Inject.get(fullType<T>()) } } inline fun <reified T : Any> injectValue(): Lazy<T> { return lazyOf(Inject.get(fullType<T>())) } inline fun <reified T : Any> injectLazy(key: Any): Lazy<T> { return lazy { Inject.get(fullType<T>(), key) } } inline fun <reified T : Any> injectValue(key: Any): Lazy<T> { return lazyOf(Inject.get(fullType<T>(), key)) }
30
Kotlin
82
2,892
e1f67cc997884e4f6e0e7074c2bae599d3996c9a
723
EasyBangumi
Apache License 2.0
src/main/kotlin/com/bh/planners/api/event/PlayerJumpEvent.kt
postyizhan
754,476,430
false
{"Kotlin": 652703, "Java": 215}
package com.bh.planners.api.event import org.bukkit.entity.Player import taboolib.common.platform.event.SubscribeEvent import taboolib.platform.event.PlayerJumpEvent import taboolib.platform.type.BukkitProxyEvent class PlayerJumpEvent(val player: Player) : BukkitProxyEvent() { companion object { @SubscribeEvent(ignoreCancelled = false) fun e(e: PlayerJumpEvent) { com.bh.planners.api.event.PlayerJumpEvent(e.player).call() } } }
0
Kotlin
1
0
dea343908592d722cd03d9dbadbc659372131dfe
481
planners
Creative Commons Zero v1.0 Universal
app/src/main/java/com/baymax104/bookmanager20compose/ui/screen/IndexScreen.kt
Baymax104
670,902,320
false
null
package com.baymax104.bookmanager20compose.ui.screen import androidx.activity.compose.BackHandler import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.baymax104.bookmanager20compose.R import com.baymax104.bookmanager20compose.ui.components.BottomBar import com.baymax104.bookmanager20compose.ui.components.Drawer import com.baymax104.bookmanager20compose.ui.components.IndexTransition import com.baymax104.bookmanager20compose.ui.components.TopBar import com.baymax104.bookmanager20compose.ui.screen.destinations.ScanScreenDestination import com.baymax104.bookmanager20compose.ui.theme.BookManagerTheme import com.blankj.utilcode.util.ToastUtils import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.annotation.RootNavGraph import com.ramcosta.composedestinations.navigation.DestinationsNavigator import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator import com.ramcosta.composedestinations.result.EmptyResultRecipient import com.ramcosta.composedestinations.result.NavResult import com.ramcosta.composedestinations.result.ResultRecipient import kotlinx.coroutines.launch /** * 主页 */ @OptIn( ExperimentalMaterial3Api::class, ) @RootNavGraph(start = true) @Destination(style = IndexTransition::class) @Composable fun IndexScreen( navigator: DestinationsNavigator, resultRecipient: ResultRecipient<ScanScreenDestination, String> ) { val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) val scope = rememberCoroutineScope() resultRecipient.onNavResult { when (it) { is NavResult.Canceled -> { ToastUtils.showShort("取消") } is NavResult.Value -> { ToastUtils.showShort(it.value) } } } if (drawerState.isOpen) { BackHandler { scope.launch { drawerState.close() } } } Drawer(drawerState) { IndexContent( navigator = navigator, onLeftNavClick = { scope.launch { drawerState.open() } }, onActionClick = { ToastUtils.showShort("Action") } ) } } /** * 主页框架 * @param onLeftNavClick 左侧导航按钮回调 * @param onActionClick 右侧行为按钮回调 */ @OptIn( ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class ) @Composable private fun IndexContent( onLeftNavClick: () -> Unit, onActionClick: () -> Unit, navigator: DestinationsNavigator ) { val pagerState = rememberPagerState() Scaffold( topBar = { TopBar(onLeftNavClick, onActionClick) }, bottomBar = { BottomBar(pagerState = pagerState, indexPages = indexPages) }, ) { paddingValues -> HorizontalPager( pageCount = 2, modifier = Modifier.padding(paddingValues), state = pagerState, key = { indexPages[it].key }, userScrollEnabled = false ) { when (it) { 0 -> ProgressScreen(navigator) 1 -> FinishScreen() } } } } sealed class IndexPage( val key: String, val label: String, val icon: Int ) { object Progress : IndexPage("progress", "进度", R.drawable.progress) object Finish: IndexPage("finish", "读过", R.drawable.finish) } val indexPages = listOf( IndexPage.Progress, IndexPage.Finish ) @Preview @Composable fun Preview() { BookManagerTheme { IndexScreen(EmptyDestinationsNavigator, EmptyResultRecipient()) } }
0
Kotlin
0
0
1573321ce49bd41de33b3d76694e10ecac887766
4,132
BookManager2.0-compose
MIT License
app/src/main/java/com/github/jan222ik/gamification/ui/components/PCard.kt
jan222ik
453,740,147
false
null
package com.github.jan222ik.gamification.ui.components import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.github.jan222ik.gamification.ui.logic.PlayedCard @Composable fun PCard(playedCard: PlayedCard) { Surface( modifier = Modifier .fillMaxSize() .padding(vertical = 16.dp) .padding(end = 16.dp), shape = RoundedCornerShape(16.dp), tonalElevation = 16.dp ) { Column( modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp) ) { Text( text = when (playedCard.isCrossEffect) { true -> "Nebeneffekt von: " else -> "Gespielt von: " } ) PlayerNameChip(player = playedCard.sender) } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp) ) { playedCard.recipient?.let { Text(text = " an: ") PlayerNameChip(player = it) } } Surface( modifier = Modifier .weight(1f) .padding(all = 16.dp), shape = RoundedCornerShape(16.dp), tonalElevation = 32.dp ) { Box( modifier = Modifier.padding(8.dp), contentAlignment = Alignment.Center ) { Text(text = buildAnnotatedString { val senderTag = "<sender>" val startIdx = playedCard.data.description.indexOf(senderTag) if (startIdx != -1) { append(playedCard.data.description.substring(startIndex = 0, endIndex = startIdx)) withStyle(SpanStyle(color = playedCard.sender.color)) { append(playedCard.sender.name) } append(playedCard.data.description.substring(startIndex = startIdx + senderTag.length)) } else { append(playedCard.data.description) } }) Text( text = "ID:${playedCard.data.id}", style = LocalTextStyle.current.copy(fontSize = 10.sp), modifier= Modifier .align(Alignment.BottomEnd) .padding(5.dp) ) } } Row( horizontalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically ) { val effectSender = playedCard.data.effectForSender val indication = when { effectSender > 0 -> "+" effectSender == 0 -> " " else -> "" } Text(text = "Sender: $indication$effectSender") playedCard.recipient?.let { val effectRecipient = playedCard.data.effectForReceiver val indicationR = when { effectRecipient > 0 -> "+" effectRecipient == 0 -> " " else -> "" } Text(text = "Empfänger: $indicationR$effectRecipient") } } } } }
0
Kotlin
0
0
073f387a9f23af97acda3b7a299081aa0187968d
4,366
MSc-S3-FAS-KON-Gamification
MIT License
app/src/main/java/com/kasuminotes/action/InjuredEnergy.kt
chilbi
399,723,451
false
{"Kotlin": 876150}
package com.kasuminotes.action import com.kasuminotes.R import com.kasuminotes.data.SkillAction fun SkillAction.getInjuredEnergy(): D { return if (actionValue1 == 0.0) { D.Format(R.string.action_no_injured_energy) } else { D.Format( R.string.action_injured_energy1, arrayOf(D.Text("${(actionValue1 * 100).toNumStr()}%")) ) } }
0
Kotlin
0
1
fcc809a132cdd518285ef75a5bae31d4b14c03d7
389
KasumiNotes
Apache License 2.0
wrapper/godot-library/src/main/kotlin/godot/generated/CSGShape.kt
payload
189,718,948
true
{"Kotlin": 3888394, "C": 6051, "Batchfile": 714, "Shell": 574}
@file:Suppress("unused", "ClassName", "EnumEntryName", "FunctionName", "SpellCheckingInspection", "PARAMETER_NAME_CHANGED_ON_OVERRIDE", "UnusedImport", "PackageDirectoryMismatch") package godot import godot.gdnative.* import godot.core.* import godot.utils.* import godot.icalls.* import kotlinx.cinterop.* // NOTE: THIS FILE IS AUTO GENERATED FROM JSON API CONFIG open class CSGShape : VisualInstance { private constructor() : super("") constructor(variant: Variant) : super(variant) internal constructor(mem: COpaquePointer) : super(mem) internal constructor(name: String) : super(name) // Enums enum class Operation(val id: Long) { OPERATION_UNION(0), OPERATION_INTERSECTION(1), OPERATION_SUBTRACTION(2), ; companion object { fun fromInt(value: Long) = values().single { it.id == value } } } // Signals class Signal { companion object { } } companion object { infix fun from(other: VisualInstance): CSGShape = CSGShape("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Spatial): CSGShape = CSGShape("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Node): CSGShape = CSGShape("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Object): CSGShape = CSGShape("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Variant): CSGShape = fromVariant(CSGShape(""), other) // Constants const val OPERATION_UNION: Long = 0 const val OPERATION_INTERSECTION: Long = 1 const val OPERATION_SUBTRACTION: Long = 2 } // Properties open var operation: Long get() = _icall_Long(getOperationMethodBind, this.rawMemory) set(value) = _icall_Unit_Long(setOperationMethodBind, this.rawMemory, value) open var useCollision: Boolean get() = _icall_Boolean(isUsingCollisionMethodBind, this.rawMemory) set(value) = _icall_Unit_Boolean(setUseCollisionMethodBind, this.rawMemory, value) open var snap: Double get() = _icall_Double(getSnapMethodBind, this.rawMemory) set(value) = _icall_Unit_Double(setSnapMethodBind, this.rawMemory, value) // Methods open fun _update_shape() { } private val isRootShapeMethodBind: CPointer<godot_method_bind> by lazy { getMB("CSGShape", "is_root_shape") } open fun isRootShape(): Boolean { return _icall_Boolean(isRootShapeMethodBind, this.rawMemory) } private val setOperationMethodBind: CPointer<godot_method_bind> by lazy { getMB("CSGShape", "set_operation") } open fun setOperation(operation: Long) { _icall_Unit_Long(setOperationMethodBind, this.rawMemory, operation) } private val getOperationMethodBind: CPointer<godot_method_bind> by lazy { getMB("CSGShape", "get_operation") } open fun getOperation(): CSGShape.Operation { return CSGShape.Operation.fromInt(_icall_Long(getOperationMethodBind, this.rawMemory)) } private val setUseCollisionMethodBind: CPointer<godot_method_bind> by lazy { getMB("CSGShape", "set_use_collision") } open fun setUseCollision(operation: Boolean) { _icall_Unit_Boolean(setUseCollisionMethodBind, this.rawMemory, operation) } private val isUsingCollisionMethodBind: CPointer<godot_method_bind> by lazy { getMB("CSGShape", "is_using_collision") } open fun isUsingCollision(): Boolean { return _icall_Boolean(isUsingCollisionMethodBind, this.rawMemory) } private val setSnapMethodBind: CPointer<godot_method_bind> by lazy { getMB("CSGShape", "set_snap") } open fun setSnap(snap: Double) { _icall_Unit_Double(setSnapMethodBind, this.rawMemory, snap) } private val getSnapMethodBind: CPointer<godot_method_bind> by lazy { getMB("CSGShape", "get_snap") } open fun getSnap(): Double { return _icall_Double(getSnapMethodBind, this.rawMemory) } }
0
Kotlin
1
2
70473f9b9a0de08d82222b735e7f9b07bbe91700
3,997
kotlin-godot-wrapper
Apache License 2.0
basic/src/main/java/dev/entao/web/sql/ConnectionInsert.kt
yangentao
532,703,720
false
null
package dev.entao.web.sql import dev.entao.web.base.Prop import dev.entao.web.base.getPropValue import dev.entao.web.base.plusAssign import dev.entao.web.base.useX import dev.entao.web.log.logd import java.sql.Connection import kotlin.reflect.KClass fun Connection.insert(modelCls: KClass<*>, kvs: List<Pair<Prop, Any?>>): Boolean { return this.insert(modelCls.nameSQL, kvs.map { it.first.nameSQL to it.second }) } fun Connection.insert(table: String, kvs: List<Pair<String, Any?>>): Boolean { val ks = kvs.joinToString(", ") { it.first } val vs = kvs.joinToString(", ") { "?" } val sql = "INSERT INTO $table ($ks) VALUES ($vs) " val args = kvs.map { it.second } return this.update(sql, args) > 0 } fun Connection.insertGenKey(modelCls: KClass<*>, kvs: List<Pair<Prop, Any?>>): Long { return this.insertGenKey(modelCls.nameSQL, kvs.map { it.first.nameSQL to it.second }) } fun Connection.insertGenKey(table: String, kvs: List<Pair<String, Any?>>): Long { val ks = kvs.joinToString(", ") { it.first } val vs = kvs.joinToString(", ") { "?" } val sql = "INSERT INTO $table ($ks) VALUES ($vs) " val args = kvs.map { it.second } return this.insertGen(sql, args) } fun Connection.insertGen(sql: String, args: List<Any?>): Long { val st = this.prepareStatement(sql, java.sql.Statement.RETURN_GENERATED_KEYS) st.setParams(args) if (ConnPick.enableLog) { logd(sql) logd(args) } st.useX { val n = it.executeUpdate() return if (n <= 0) { 0L } else { it.generatedKeys.firstLong() ?: 0L } } } fun Connection.insertOrUpdate(modelCls: KClass<*>, kvs: List<Pair<Prop, Any?>>, uniqColumns: List<Prop>): Boolean { return this.insertOrUpdate(modelCls.nameSQL, kvs.map { it.first.nameSQL to it.second }, uniqColumns.map { it.nameSQL }) } fun Connection.insertOrUpdate(table: String, kvs: List<Pair<String, Any?>>, uniqColumns: List<String>): Boolean { if (uniqColumns.isEmpty()) { throw IllegalArgumentException("insertOrUpdate $table uniqColumns 参数不能是空") } val ks = kvs.joinToString(", ") { it.first } val vs = kvs.joinToString(", ") { "?" } val buf = StringBuilder(512) buf.append("INSERT INTO $table ($ks ) VALUES ( $vs ) ") val updateCols = kvs.filter { it.first !in uniqColumns } buf += " ON DUPLICATE KEY UPDATE " buf += updateCols.joinToString(", ") { "${it.first} = ? " } return this.update(buf.toString(), kvs.map { it.second } + updateCols.map { it.second }) > 0 } //现有记录和要插入的记录完全一样, 也会返回false, 表示没有更新 fun Connection.insertOrUpdate(model: OrmModel): Boolean { val pks = model::class._PrimaryKeys assert(pks.isNotEmpty()) val cs = model._PropertiesExists return this.insertOrUpdate(model::class, cs.map { it to it.getPropValue(model) }, pks) }
0
Kotlin
0
0
f6431e275c77539efb27bde89b0292e0f783413b
2,699
WebSweet
Apache License 2.0
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/regular/SmileWink.kt
DevSrSouza
311,134,756
false
null
package compose.icons.fontawesomeicons.regular import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.fontawesomeicons.RegularGroup public val RegularGroup.SmileWink: ImageVector get() { if (_smileWink != null) { return _smileWink!! } _smileWink = Builder(name = "SmileWink", defaultWidth = 496.0.dp, defaultHeight = 512.0.dp, viewportWidth = 496.0f, viewportHeight = 512.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(248.0f, 8.0f) curveTo(111.0f, 8.0f, 0.0f, 119.0f, 0.0f, 256.0f) reflectiveCurveToRelative(111.0f, 248.0f, 248.0f, 248.0f) reflectiveCurveToRelative(248.0f, -111.0f, 248.0f, -248.0f) reflectiveCurveTo(385.0f, 8.0f, 248.0f, 8.0f) close() moveTo(248.0f, 456.0f) curveToRelative(-110.3f, 0.0f, -200.0f, -89.7f, -200.0f, -200.0f) reflectiveCurveTo(137.7f, 56.0f, 248.0f, 56.0f) reflectiveCurveToRelative(200.0f, 89.7f, 200.0f, 200.0f) reflectiveCurveToRelative(-89.7f, 200.0f, -200.0f, 200.0f) close() moveTo(365.8f, 309.6f) curveToRelative(-10.2f, -8.5f, -25.3f, -7.1f, -33.8f, 3.1f) curveToRelative(-20.8f, 25.0f, -51.5f, 39.4f, -84.0f, 39.4f) reflectiveCurveToRelative(-63.2f, -14.3f, -84.0f, -39.4f) curveToRelative(-8.5f, -10.2f, -23.7f, -11.5f, -33.8f, -3.1f) curveToRelative(-10.2f, 8.5f, -11.5f, 23.6f, -3.1f, 33.8f) curveToRelative(30.0f, 36.0f, 74.1f, 56.6f, 120.9f, 56.6f) reflectiveCurveToRelative(90.9f, -20.6f, 120.9f, -56.6f) curveToRelative(8.5f, -10.2f, 7.1f, -25.3f, -3.1f, -33.8f) close() moveTo(168.0f, 240.0f) curveToRelative(17.7f, 0.0f, 32.0f, -14.3f, 32.0f, -32.0f) reflectiveCurveToRelative(-14.3f, -32.0f, -32.0f, -32.0f) reflectiveCurveToRelative(-32.0f, 14.3f, -32.0f, 32.0f) reflectiveCurveToRelative(14.3f, 32.0f, 32.0f, 32.0f) close() moveTo(328.0f, 180.0f) curveToRelative(-25.7f, 0.0f, -55.9f, 16.9f, -59.9f, 42.1f) curveToRelative(-1.7f, 11.2f, 11.5f, 18.2f, 19.8f, 10.8f) lineToRelative(9.5f, -8.5f) curveToRelative(14.8f, -13.2f, 46.2f, -13.2f, 61.0f, 0.0f) lineToRelative(9.5f, 8.5f) curveToRelative(8.5f, 7.4f, 21.6f, 0.3f, 19.8f, -10.8f) curveToRelative(-3.8f, -25.2f, -34.0f, -42.1f, -59.7f, -42.1f) close() } } .build() return _smileWink!! } private var _smileWink: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
3,451
compose-icons
MIT License
src/test/kotlin/ch/veehait/devicecheck/appattest/common/AuthenticatorDataTest.kt
veehaitch
287,712,692
false
null
package ch.veehait.devicecheck.appattest.common import ch.veehait.devicecheck.appattest.TestExtensions.encode import ch.veehait.devicecheck.appattest.TestUtils import ch.veehait.devicecheck.appattest.attestation.AttestationObject import ch.veehait.devicecheck.appattest.attestation.AttestationSample import io.kotest.assertions.throwables.shouldNotThrowAny import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import nl.jqno.equalsverifier.EqualsVerifier import java.util.UUID class AuthenticatorDataTest : FreeSpec() { init { "equals/hashCode" - { "AttestedCredentialData" { EqualsVerifier.forClass(AttestedCredentialData::class.java).verify() } "AuthenticatorData" { EqualsVerifier.forClass(AuthenticatorData::class.java).verify() } } "Would read extensions with attestedCredentials" { val sample = AttestationSample.all.random() val objectReader = TestUtils.cborObjectMapper.readerFor(AttestationObject::class.java) val attestationObject: AttestationObject = objectReader.readValue(sample.attestation) val authenticatorData = AuthenticatorData.parse(attestationObject.authData) val authDataWithExtensions = authenticatorData.copy( flags = authenticatorData.flags.plus(AuthenticatorDataFlag.ED), extensions = linkedMapOf( "wurzel" to "pfropf", ), ).encode() val authenticatorDataWithExtensions = shouldNotThrowAny { AuthenticatorData.parse(authDataWithExtensions) } authenticatorDataWithExtensions.extensions.shouldNotBeNull() } "Would read extensions without attestedCredentials" { val sample = AttestationSample.all.random() val objectReader = TestUtils.cborObjectMapper.readerFor(AttestationObject::class.java) val attestationObject: AttestationObject = objectReader.readValue(sample.attestation) val authenticatorData = AuthenticatorData.parse(attestationObject.authData) val authDataWithExtensions = authenticatorData.copy( flags = authenticatorData.flags .plus(AuthenticatorDataFlag.ED) .minus(AuthenticatorDataFlag.AT), attestedCredentialData = null, extensions = linkedMapOf( "wurzel" to "pfropf", ), ).encode() val authenticatorDataWithExtensions = shouldNotThrowAny { AuthenticatorData.parse(authDataWithExtensions) } authenticatorDataWithExtensions.extensions.shouldNotBeNull() } "Creates correct development AAGUID (appattestdevelop)" { val expected = UUID.fromString("61707061-7474-6573-7464-6576656c6f70") val actual = AppleAppAttestEnvironment.DEVELOPMENT.aaguid expected shouldBe actual } "Creates correct production AAGUID (appattest)" { val expected = UUID.fromString("61707061-7474-6573-7400-000000000000") val actual = AppleAppAttestEnvironment.PRODUCTION.aaguid expected shouldBe actual } } }
2
Kotlin
7
51
cb26211f63c1e2e7949deafe2efdf352daca27fa
3,385
devicecheck-appattest
Apache License 2.0
src/main/kotlin/no/nav/helse/spole/Nais.kt
navikt
204,685,762
false
null
package no.nav.helse.spole import io.ktor.application.call import io.ktor.response.respondText import io.ktor.routing.Routing import io.ktor.routing.get import io.micrometer.prometheus.PrometheusMeterRegistry fun Routing.nais(collectorRegistry: PrometheusMeterRegistry) { get("/isalive") { call.respondText { "ALIVE" } } get("/isready") { call.respondText { "READY" } } get("/internal/metrics") { call.respondText(collectorRegistry.scrape()) } }
0
Kotlin
0
1
0201d89f599ead9c2c3e5acd0cacede463847df6
495
helse-spole
MIT License
app/src/main/kotlin/io/shtanko/picasagallery/data/photo/PhotosDataModule.kt
ashtanko
99,620,302
false
null
/* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.shtanko.picasagallery.data.photo import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class PhotosDataModule { @Provides @Singleton fun providePhotosRepository(dataSource: PhotosDataSource): PhotosRepository = PhotosRepositoryImpl(dataSource) }
1
Kotlin
1
4
ad6961aa1d60668786797a443b64e6710f464f8c
887
Picasa-Gallery-Android
Apache License 2.0
server/src/main/kotlin/com/thoughtworks/archguard/code/module/domain/dubbo/XmlConfigServiceImpl.kt
archguard
460,910,110
false
{"Kotlin": 1540609, "Java": 593833, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2263, "Shell": 926, "C": 696, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32}
package com.thoughtworks.archguard.code.module.domain.dubbo import com.thoughtworks.archguard.code.module.domain.model.JClassVO import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class XmlConfigServiceImpl : XmlConfigService { private val log = LoggerFactory.getLogger(XmlConfigServiceImpl::class.java) @Autowired lateinit var dubboConfigRepository: DubboConfigRepository override fun getRealCalleeModuleByXmlConfig(systemId: Long, callerClass: JClassVO, calleeClass: JClassVO): List<SubModuleDubbo> { val callerModule = callerClass.module ?: throw RuntimeException("callerModule is null, is impossible") val callerSubModule = dubboConfigRepository.getSubModuleByName(systemId, callerModule) ?: return emptyList() val referenceConfigs = dubboConfigRepository.getReferenceConfigBy(systemId, calleeClass.name, callerSubModule) val serviceConfigs = referenceConfigs.map { referenceConfig -> dubboConfigRepository.getServiceConfigBy(systemId, referenceConfig) }.flatten() return serviceConfigs.map { it.subModule } } }
3
Kotlin
86
557
92c0c8b577c7462b290e8fe89fa47d769ef98e64
1,176
archguard
MIT License