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/galaxysoftware/musicplayer/type/TabType.kt
GalaxyDGamer
143,671,146
false
null
package galaxysoftware.musicplayer.type /** * Defining Tab Type */ enum class TabType { LIBRARY, ALBUM, ARTIST, PLAYLIST }
0
Kotlin
0
0
ed139670a7e4a5a18ec77b5d4f29f91e08e33955
141
MusicPlayer
Apache License 2.0
src/main/java/site/hirecruit/hr/global/exception/model/ExceptionResponseEntity.kt
themoment-team
473,691,285
false
{"Kotlin": 205045, "Dockerfile": 1004, "Shell": 97}
package site.hirecruit.hr.global.exception.model /** * Exception발생시 클라이언트에 반환할 Response 객체입니다. * * 해당 클래스는 정적 팩토리 매서드로도 생성할 수 있습니다. 다음은 Spring RestControllerAdvice로 예외를 핸들링하는 예제입니다.. * ```kotlin * @ExceptionHandler(HttpStatusCodeException::class) * private fun httpStatusException(ex: HttpClientErrorException): ResponseEntity<ExceptionResponseEntity> = * ResponseEntity.status(ex.statusCode.value()) * .body(ExceptionResponseEntity.of(ex)) * ``` * @see ExceptionResponseEntity.of * @author 정시원 * @since 1.0 */ class ExceptionResponseEntity ( val message: String? ) { companion object{ fun <T : Throwable> of(exception: T): ExceptionResponseEntity = ExceptionResponseEntity(exception.message) } }
2
Kotlin
0
16
6dbf1779257a5ecde9f51c9878bc0cb8871f5336
746
HiRecruit-server
MIT License
app/src/main/java/com/dicoding/asclepius/view/MainActivity.kt
xirf
791,855,561
false
{"Kotlin": 38984}
package com.dicoding.asclepius.view import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.lifecycle.ViewModelProvider import com.dicoding.asclepius.R import com.dicoding.asclepius.data.entity.HistoryEntity import com.dicoding.asclepius.databinding.ActivityMainBinding import com.dicoding.asclepius.helper.ImageClassifierHelper import com.dicoding.asclepius.helper.MediaStorageHelper import com.dicoding.asclepius.viewmodel.HistoryViewModel import com.dicoding.asclepius.viewmodel.ViewModelFactory import com.yalantis.ucrop.UCrop import org.tensorflow.lite.task.vision.classifier.Classifications private const val REQUEST_IMAGE_CAPTURE = 1 class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var historyViewModel: HistoryViewModel private lateinit var mediaStorageHelper: MediaStorageHelper private var currentImageUri: Uri? = null private var toast: Toast? = null private var isSameImage = false private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { if (it) { showToast("Permission Granted") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) initViewModelAndHelper() if (!checkPermissions()) requestPermissionLauncher.launch(REQUIRE_PERMISSION); if (currentImageUri == null) binding.analyzeButton.visibility = View.GONE; with(binding) { progressIndicator.visibility = View.GONE analyzeButton.setOnClickListener { analyzeImage() } galleryButton.setOnClickListener { launcherGallery.launch( PickVisualMediaRequest( ActivityResultContracts.PickVisualMedia.ImageOnly ) ) } cameraButton.setOnClickListener { startCamera() } historyButton.setOnClickListener { startActivity(Intent(this@MainActivity, HistoryActivity::class.java)) } } } private fun initViewModelAndHelper() { val factory = ViewModelFactory.getInstance(application) historyViewModel = ViewModelProvider(this, factory)[HistoryViewModel::class.java] mediaStorageHelper = MediaStorageHelper(this) } private fun checkPermissions() = ContextCompat.checkSelfPermission( this, REQUIRE_PERMISSION ) == PackageManager.PERMISSION_GRANTED private val launcherGallery = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri: Uri? -> if (uri != null) { cropImage(uri) isSameImage = false binding.analyzeButton.visibility = View.VISIBLE } else { showErrorMessage() } } private fun showErrorMessage() { if (currentImageUri == null) { showToast(getString(R.string.empty_image_warning)) } else { showToast(getString(R.string.cancel_action)) } } private fun startCamera() { currentImageUri = mediaStorageHelper.getImageUri() launcherIntentCamera.launch(currentImageUri) } private val launcherIntentCamera = registerForActivityResult( ActivityResultContracts.TakePicture() ) { success -> if (success) { cropImage(currentImageUri!!) isSameImage = false binding.analyzeButton.visibility = View.VISIBLE } else { showErrorMessage() } } private fun cropImage(uri: Uri) { val destinationUri: Uri = mediaStorageHelper.getImageUri() UCrop.of(uri, destinationUri) .withAspectRatio(1f, 1f) .start(this) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) { val resultUri: Uri? = UCrop.getOutput(data!!) currentImageUri = resultUri showImage() } else if (resultCode == UCrop.RESULT_ERROR) { val cropError = UCrop.getError(data!!) showToast("Gagal memotong gambar: $cropError") } } private fun showImage() { with(binding) { currentImageUri?.let { previewImageView.visibility = View.VISIBLE clWelcome.visibility = View.GONE previewImageView.setImageURI(it) } } } private fun analyzeImage() { currentImageUri?.let { binding.progressIndicator.visibility = View.VISIBLE val imageClassifierHelper = ImageClassifierHelper(this, object : ImageClassifierHelper.ClassifierListener { override fun onError(error: String) { showToast(error) binding.progressIndicator.visibility = View.GONE } override fun onResults(results: List<Classifications>?) { if (results != null) { if (!isSameImage) insertIntoHistory(results); isSameImage = true moveToResult(results) } binding.progressIndicator.visibility = View.GONE } }) imageClassifierHelper.classifyStaticImage(it) } ?: showToast(getString(R.string.empty_image_warning)) } private fun insertIntoHistory(results: List<Classifications>) { if (currentImageUri != null) { val imagePath = mediaStorageHelper.saveImageToGallery(currentImageUri!!) historyViewModel.insertHistory( HistoryEntity( label = results[0].categories?.get(0)?.label ?: "Cancer", confidence = results[0].categories?.get(0)?.score ?: 0f, image = imagePath ) ) } } private fun moveToResult(analyzeResult: List<Classifications>) { val topClassifications = analyzeResult[0].categories if (topClassifications != null) { val intent = Intent(this, ResultActivity::class.java) Log.d("RESULT", topClassifications[0].toString()) intent.putExtra(ResultActivity.EXTRA_RESULT, topClassifications[0].label) intent.putExtra(ResultActivity.EXTRA_CONFIDENCE_SCORE, topClassifications[0].score) intent.putExtra(ResultActivity.EXTRA_IMAGE_URI, currentImageUri.toString()) startActivity(intent) } else { showToast(getString(R.string.classification_failed)) } } private fun showToast(message: String) { toast?.cancel() toast = Toast.makeText(this, message, Toast.LENGTH_SHORT) toast?.show() } companion object { private const val REQUIRE_PERMISSION = Manifest.permission.CAMERA } }
0
Kotlin
0
0
74d5bfae46ec8328f7c02e05f3d7b6e7d698b2fe
7,741
asclepius
MIT License
wow-opentelemetry/src/main/kotlin/me/ahoo/wow/opentelemetry/messaging/MessageTextMapSetter.kt
Ahoo-Wang
628,167,080
false
{"Kotlin": 1902621, "Java": 34050, "TypeScript": 31834, "HTML": 11619, "Lua": 3978, "JavaScript": 2288, "Dockerfile": 820, "SCSS": 500, "Less": 342}
/* * Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)]. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.ahoo.wow.opentelemetry.messaging import io.opentelemetry.context.propagation.TextMapSetter import me.ahoo.wow.api.messaging.Message import org.slf4j.LoggerFactory class MessageTextMapSetter<M : Message<*, *>> : TextMapSetter<M> { companion object { private val log = LoggerFactory.getLogger(MessageTextMapSetter::class.java) } override fun set(carrier: M?, key: String, value: String) { if (carrier == null) { return } if (carrier.isReadOnly) { if (log.isWarnEnabled) { log.warn("carrier is read only. key:[{}],value:[{}]", key, value) } return } carrier.header[key] = value } }
6
Kotlin
10
98
eed438bab2ae009edf3a1db03396de402885c681
1,358
Wow
Apache License 2.0
kbloc_core/src/commonTest/kotlin/com/beyondeye/kbloc/bloc_overrides_test.kt
beyondeye
509,066,769
false
null
package com.beyondeye.kbloc import com.beyondeye.kbloc.concurrency.EventTransformer_sequential import com.beyondeye.kbloc.core.BlocObserver import com.beyondeye.kbloc.core.BlocOverrides import com.beyondeye.kbloc.core.EventTransformer import kotlin.test.Test import kotlin.test.assertTrue class FakeBlocObserver<T:Any> :BlocObserver<T> { } class BlocOverridesTest { @Test fun BlocOverrides_uses_default_BlocObserver_when_not_specified() { BlocOverrides.runWithOverrides { val overrides=BlocOverrides.current assertTrue { overrides?.blocObserver is BlocObserver } } } @Test fun BlocOverrides_uses_default_EventTransformer_when_not_specified() { BlocOverrides.runWithOverrides { val overrides=BlocOverrides.current assertTrue { overrides?.eventTransformer is EventTransformer<Any> } } } @Test fun BlocOverrides_uses_custom_BlocObserver_when_specified() { val blocObserver=FakeBlocObserver<Any>() BlocOverrides.runWithOverrides(blocObserver=blocObserver) { val overrides=BlocOverrides.current assertTrue { overrides?.blocObserver === blocObserver } } } @Test fun BlocOverrides_uses_custom_EventTransformer_when_specified() { val eventTransformer:EventTransformer<Any> = EventTransformer_sequential() //{events, mapper -> events.asyncExpand(mapper) } BlocOverrides.runWithOverrides(eventTransformer = eventTransformer) { val overrides=BlocOverrides.current assertTrue { overrides?.eventTransformer === eventTransformer } } } @Test fun BlocOverrides_uses_current_BlocObserver_when_not_specified() { val blocObserver=FakeBlocObserver<Any>() BlocOverrides.runWithOverrides(blocObserver=blocObserver) { BlocOverrides.runWithOverrides { val overrides=BlocOverrides.current assertTrue { overrides?.blocObserver === blocObserver } } } } @Test fun BlocOverrides_uses_current_EventTransformer_when_not_specified() { val eventTransformer:EventTransformer<Any> = EventTransformer_sequential() //{events, mapper -> events.asyncExpand(mapper) } BlocOverrides.runWithOverrides(eventTransformer = eventTransformer) { BlocOverrides.runWithOverrides { val overrides=BlocOverrides.current assertTrue { overrides?.eventTransformer === eventTransformer } } } } @Test fun BlocOverrides_uses_nested_BlocObserver_when_specified() { val rootBlocObserver=FakeBlocObserver<Any>() BlocOverrides.runWithOverrides(blocObserver=rootBlocObserver) { val overrides=BlocOverrides.current assertTrue { overrides?.blocObserver === rootBlocObserver } val nestedBlocObserver=FakeBlocObserver<Any>() BlocOverrides.runWithOverrides(blocObserver = nestedBlocObserver) { val overrides=BlocOverrides.current assertTrue { overrides?.blocObserver === nestedBlocObserver } } } } @Test fun BlocOverrides_uses_nested_EventTransformer_when_specified() { val rootEventTransformer:EventTransformer<Any> = EventTransformer_sequential() //{events, mapper -> events.asyncExpand(mapper) } BlocOverrides.runWithOverrides(eventTransformer = rootEventTransformer) { val overrides = BlocOverrides.current assertTrue { overrides?.eventTransformer === rootEventTransformer } val nestedEventTransformer: EventTransformer<Any> = EventTransformer_sequential() //{ events, mapper -> events.asyncExpand(mapper) } BlocOverrides.runWithOverrides(eventTransformer = nestedEventTransformer) { val overrides = BlocOverrides.current assertTrue { overrides?.eventTransformer === nestedEventTransformer } } } } @Test fun BlocOverrides_overrides_cannot_be_mutated_after_zone_created() { val originalBlocObserver=FakeBlocObserver<Any>() val otherBlocObserver=FakeBlocObserver<Any>() var blocObserver=originalBlocObserver BlocOverrides.runWithOverrides(blocObserver=blocObserver) { blocObserver=otherBlocObserver val overrides=BlocOverrides.current assertTrue(originalBlocObserver===overrides?.blocObserver) assertTrue { overrides?.blocObserver!==otherBlocObserver } } } }
0
Kotlin
0
9
3d5e4998c9215b1cef94f6d56db0a2c4eef8d676
4,569
compose_bloc
Apache License 2.0
src/main/java/com/what3words/addressvalidator/javawrapper/addresslookupservice/swiftcomplete/What3WordsAddressValidatorSwiftComplete.kt
what3words
538,914,401
false
{"Kotlin": 115964}
package com.what3words.addressvalidator.javawrapper.addresslookupservice.swiftcomplete import com.what3words.addressvalidator.javawrapper.What3WordsAddressValidator import com.what3words.addressvalidator.javawrapper.model.address.W3WAddressValidatorLeafNode import com.what3words.addressvalidator.javawrapper.model.address.W3WAddressValidatorNode import com.what3words.addressvalidator.javawrapper.model.address.W3WAddressValidatorParentNode import com.what3words.addressvalidator.javawrapper.model.address.W3WAddressValidatorRootNode import com.what3words.addressvalidator.javawrapper.model.error.W3WAddressValidatorError import com.what3words.addressvalidator.javawrapper.utils.Either import com.what3words.addressvalidator.javawrapper.utils.makeRequest import com.what3words.addressvalidator.javawrapper.addresslookupservice.swiftcomplete.mappers.toW3WStreetAddress import com.what3words.addressvalidator.javawrapper.addresslookupservice.swiftcomplete.mappers.toW3WAddressValidatorNode import com.what3words.addressvalidator.javawrapper.addresslookupservice.swiftcomplete.network.SwiftCompleteAPIService import com.what3words.addressvalidator.javawrapper.model.address.streetaddress.W3WStreetAddress import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext internal class What3WordsAddressValidatorSwiftComplete( private val coroutineDispatcher: CoroutineDispatcher, private val swiftCompleteApiKey: String, private val swiftCompleteAPIService: SwiftCompleteAPIService ) : What3WordsAddressValidator { override suspend fun search(near: String): Either<W3WAddressValidatorError, W3WAddressValidatorRootNode> { return withContext(coroutineDispatcher) { val result = makeRequest { swiftCompleteAPIService.search( key = swiftCompleteApiKey, threeWordAddress = formatThreeWordAddress(near) ) } when (result) { is Either.Right -> { val root = W3WAddressValidatorRootNode( threeWordAddress = near, children = mutableListOf() ) Either.Right( root.apply { children.addAll( result.b.map { it.toW3WAddressValidatorNode(root) } ) } ) } is Either.Left -> { result } } } } override suspend fun list(node: W3WAddressValidatorParentNode): Either<W3WAddressValidatorError, List<W3WAddressValidatorNode>> { return withContext(coroutineDispatcher) { val result = makeRequest { swiftCompleteAPIService.list( key = swiftCompleteApiKey, container = node.container, threeWordAddress = formatThreeWordAddress(node.threeWordAddress) ) } when (result) { is Either.Right -> { Either.Right(result.b.map { it.toW3WAddressValidatorNode(parentNode = node) }) } is Either.Left -> { result } } } } override suspend fun info( node: W3WAddressValidatorLeafNode ): Either<W3WAddressValidatorError, W3WStreetAddress> { val parentNode = node.parent val nodeIndex = parentNode?.children?.indexOf(node) ?: 0 return withContext(coroutineDispatcher) { val result = makeRequest { // If the info call was made from the parent node, then perform a search request, and pass the // when it is a root node (i.e ancestor without a key) then group the results to be returned by road, and emptyRoad before making the request if (parentNode is W3WAddressValidatorRootNode) { swiftCompleteAPIService.search( key = swiftCompleteApiKey, populateIndex = nodeIndex, threeWordAddress = formatThreeWordAddress(node.threeWordAddress), ) } else { swiftCompleteAPIService.list( key = swiftCompleteApiKey, container = parentNode?.container ?: "", populateIndex = nodeIndex, threeWordAddress = formatThreeWordAddress(node.threeWordAddress), ) } } when (result) { is Either.Right -> { Either.Right(result.b[nodeIndex].toW3WStreetAddress()) } is Either.Left -> { result } } } } private fun formatThreeWordAddress(address: String): String { return "///${address.trim()}" } }
0
Kotlin
0
0
27a9e74284e56338ab7574e228100b4d9eed31e1
5,134
w3w-address-validator-java-wrapper
MIT License
StockMonitor/app/src/main/java/com/system/stockmonitor/views/RegisterActivity.kt
enirsilvaferraz
207,636,640
false
null
package com.system.stockmonitor.views import android.os.Bundle import android.text.Editable import android.text.InputFilter import android.text.TextWatcher import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.room.Room import com.google.android.material.textfield.TextInputEditText import com.google.gson.Gson import com.system.stockmonitor.R import com.system.stockmonitor.repository.ApiRepository import com.system.stockmonitor.repository.AppDatabase import com.system.stockmonitor.repository.StockRepository import com.system.stockmonitor.repository.StockStored import kotlinx.android.synthetic.main.activity_register.* import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlin.random.Random class RegisterActivity : AppCompatActivity() { val storage: StockRepository by lazy { Room.databaseBuilder(this, AppDatabase::class.java, "mydb").allowMainThreadQueries().build() .stockStoredDao() } val business: ApiRepository by lazy { ApiRepository() } var stockStored: StockStored? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) if (intent.hasExtra("MODEL")) { stockStored = Gson().fromJson(intent.getStringExtra("MODEL"), StockStored::class.java) stockSymbol.setText(stockStored!!.symbol) stockName.setText(stockStored!!.name) amount.setText(stockStored!!.amount.toString()) buyValue.setText(stockStored!!.buyValue.toString()) buySuggest.setText(stockStored!!.buySuggest.toString()) saleSuggest.setText(stockStored!!.saleSuggest.toString()) } stockSymbol.filters = arrayOf(InputFilter.AllCaps(), InputFilter.LengthFilter(5)) stockSymbol.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { if (!p0.isNullOrBlank()) { GlobalScope.launch(Main) { try { val credentials = business.getCredentials() val stockInfo = business.getStockInfo(stockSymbol.text.toString(), credentials) stockName.setText(stockInfo.company_name) } catch (e: Exception) { Toast.makeText(this@RegisterActivity, e.message, Toast.LENGTH_SHORT) .show() } } } else { stockName.setText("") } } }) deleteButton.setOnClickListener { if (stockStored != null) { storage.delete(stockStored!!) Toast.makeText(this, "Removed!", Toast.LENGTH_SHORT).show() finish() } } saveButton.setOnClickListener { if (verifyField(stockSymbol, "Stock Code", 5, 5) && verifyField(stockName, "Stock Name", null, null) && verifyField(amount, "Amount", null, null) && verifyField(buyValue, "Buy Value", null, null) ) { val id = if (stockStored != null) stockStored!!.id else Random.nextInt() val stored = StockStored( id = id, symbol = stockSymbol.text.toString(), name = stockName.text.toString(), buyValue = buyValue.text.toString().toDouble(), amount = amount.text.toString().toInt(), buySuggest = buySuggest.text.toString().toDouble(), saleSuggest = saleSuggest.text.toString().toDouble(), saleValue = 0.0 ) storage.save(stored) finish() } } } private fun verifyField( field: TextInputEditText, name: String, minLength: Int?, maxLength: Int? ) = if (field.text.toString().isBlank()) { Toast.makeText(this, "$name is required!", Toast.LENGTH_SHORT).show() false } else if (minLength != null && field.text.toString().length < minLength) { Toast.makeText(this, "Minimum length for $name is $minLength!", Toast.LENGTH_SHORT) .show() false } else if (maxLength != null && field.text.toString().length < maxLength) { Toast.makeText(this, "Maximum length for $name is $maxLength!", Toast.LENGTH_SHORT) .show() false } else true }
0
Kotlin
0
0
e792045158f33caca2499d140fb5ed88f273a4fa
5,001
stockmonitor
Apache License 2.0
LudoSpringBoot/src/main/kotlin/hu/bme/aut/alkfejl/ludospringboot/web/GameController.kt
Kis-Benjamin
693,261,151
false
{"Kotlin": 123208, "Java": 182}
package hu.bme.aut.alkfejl.ludospringboot.web import hu.bme.aut.alkfejl.ludospringboot.data.datasources.GameEntityRepository import hu.bme.aut.alkfejl.ludospringboot.domain.model.* import hu.bme.aut.alkfejl.ludospringboot.domain.services.Registrar import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController @RestController class GameController( private val gameEntityRepository: GameEntityRepository, private val registrar: Registrar, ) { @GetMapping("/games") fun getAll(): List<Game> = gameEntityRepository.findAll().map { it.toDomainModel() } @PostMapping("/games") fun register(@RequestBody name: String) = registrar.register(name) @PostMapping("/games/{id}/select/{name}") fun select(@RequestParam id: Int, @RequestParam name: String) { val gameEntity = gameEntityRepository.findById(id).get() val game = gameEntity.toDomainModel() game.select(name) gameEntity.update(game) gameEntityRepository.save(gameEntity) } @PostMapping("/games/{id}/step/{name}") fun step(@PathVariable(name = "id") id: Int, @PathVariable(name = "name") name: String) { val gameEntity = gameEntityRepository.findById(id).get() val game = gameEntity.toDomainModel() game.step(name) gameEntity.update(game) gameEntityRepository.save(gameEntity) } }
0
Kotlin
0
0
8593b3544705623dbbb363f36e9ccb03b5c7d5df
1,658
Ludo
Apache License 2.0
app/src/main/java/com/sakura/anime/data/remote/api/AnimeApi.kt
laqooss
871,490,049
false
{"Kotlin": 596746}
package com.sakura.anime.data.remote.api import com.sakura.anime.data.remote.dto.AnimeBean import com.sakura.anime.data.remote.dto.AnimeDetailBean import com.sakura.anime.data.remote.dto.HomeBean import com.sakura.anime.data.remote.dto.VideoBean import com.sakura.anime.util.SourceMode interface AnimeApi { suspend fun getHomeAllData(): List<HomeBean> suspend fun getAnimeDetail(detailUrl: String, mode: SourceMode): AnimeDetailBean suspend fun getVideoData(episodeUrl: String, mode: SourceMode): VideoBean suspend fun getSearchData(query: String, page: Int, mode: SourceMode): List<AnimeBean> suspend fun getWeekDate(): Map<Int, List<AnimeBean>> } } }
0
Kotlin
0
0
a1f8ef588689c8d346196d43794bd9eda887a523
683
projects
Apache License 2.0
app/src/free/java/com/capyreader/app/ui/settings/CrashReportingCheckbox.kt
jocmp
610,083,236
false
{"Kotlin": 674590, "Ruby": 1236, "Makefile": 1211}
package com.capyreader.app.ui.settings import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import com.capyreader.app.common.AppPreferences import com.capyreader.app.setupCommonModules import com.capyreader.app.ui.theme.CapyTheme import org.koin.android.ext.koin.androidContext import org.koin.compose.KoinApplication import org.koin.compose.koinInject @Composable fun CrashReportingCheckbox() { Text("Stub") } @Preview @Composable private fun CrashReportingCheckboxPreview() { val context = LocalContext.current KoinApplication( application = { androidContext(context) setupCommonModules() } ) { CapyTheme { CrashReportingCheckbox() } } }
15
Kotlin
3
91
f8ac7e8c4a6fccfe8f26f1b492261a4f5ce7dafa
860
capyreader
MIT License
core/src/main/kotlin/com/github/haschi/dominium/haushaltsbuch/core/application/InventurApi.kt
haschi
52,821,330
false
null
package com.github.haschi.dominium.haushaltsbuch.core.application import com.github.haschi.dominium.haushaltsbuch.core.model.commands.BeendeInventur import com.github.haschi.dominium.haushaltsbuch.core.model.commands.BeginneInventur import com.github.haschi.dominium.haushaltsbuch.core.model.commands.ErfasseInventar import com.github.haschi.dominium.haushaltsbuch.core.model.values.Aggregatkennung import java.util.concurrent.CompletableFuture interface InventurApi { fun send(anweisung: BeginneInventur): CompletableFuture<Aggregatkennung> fun send(anweisung: ErfasseInventar): CompletableFuture<Any> fun send(anweisung: BeendeInventur): CompletableFuture<Any> }
11
Kotlin
2
4
e3222c613c369b4a58026ce42c346b575b3082e5
679
dominium
MIT License
src/main/kotlin/cc/suffro/bpmanalyzer/bpmanalyzing/analyzers/startingposition/StartingPositionCacheAnalyzerParams.kt
xsoophx
579,535,622
false
{"Kotlin": 113450}
package cc.suffro.bpmanalyzer.bpmanalyzing.analyzers.startingposition import cc.suffro.bpmanalyzer.bpmanalyzing.analyzers.AnalyzerParams data class StartingPositionCacheAnalyzerParams( val bpm: Double, ) : AnalyzerParams
0
Kotlin
0
0
fd8db56ee5c8e4ce1d3770cbe5602c3bea6d2372
227
BPM-Analyzer
MIT License
app/src/main/java/br/com/github/domain/model/user/UserDetailModel.kt
petersongfarias
642,393,181
false
null
package br.com.github.domain.model.user import kotlinx.parcelize.Parcelize import kotlinx.parcelize.RawValue @Parcelize data class UserDetailModel( override val login: String?, override val id: Int?, override val nodeId: String?, override val avatarUrl: String?, override val gravatarId: String?, override val url: String?, val htmlUrl: String?, val followersUrl: String?, val followingUrl: String?, val gistsUrl: String?, val starredUrl: String?, val subscriptionsUrl: String?, val organizationsUrl: String?, val reposUrl: String?, val eventsUrl: String?, val receivedEventsUrl: String?, val type: String?, val siteAdmin: Boolean?, val name: String?, val company: @RawValue Any?, val blog: String?, val location: String?, val email: @RawValue Any?, val hireable: Boolean?, val bio: String?, val twitterUsername: @RawValue Any?, val publicRepos: Int?, val publicGists: Int?, val followers: Int?, val following: Int?, val createdAt: String?, val updatedAt: String? ) : BaseUser
0
Kotlin
0
0
845820dd6030199458efbf9ed4116a7a7ca315a1
1,107
GitApp
Apache License 2.0
app/src/main/java/at/marki/daggerino/worker/AndroidWorkerInjectionModule.kt
markini
260,060,195
false
null
package at.marki.daggerino.worker import androidx.work.Worker import dagger.Module import dagger.android.AndroidInjector import dagger.multibindings.Multibinds @Module abstract class AndroidWorkerInjectionModule { @Multibinds abstract fun workerInjectorFactories(): Map<Class<out Worker>, AndroidInjector.Factory<out Worker>> }
0
Kotlin
0
0
b65502a51c88347d60f0a22d0fcfc8409792c318
338
Daggerino
MIT License
backend/src/main/kotlin/com/oz/meow/controller/HomeController.kt
voncho-zero
742,285,196
false
{"Kotlin": 20777}
package com.oz.meow.controller import com.fasterxml.jackson.databind.ObjectMapper import com.oz.meow.domain.PageInfo import com.oz.meow.domain.Tree import com.oz.meow.domain.system.Cmd import com.oz.meow.domain.system.Menu import com.oz.meow.domain.system.User import com.oz.meow.enums.Enable import com.oz.meow.enums.UserStatus import com.oz.meow.mapper.system.UserMapper import com.oz.meow.service.system.UserService import org.beetl.sql.core.page.PageResult import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class HomeController(val userService: UserService, val userMapper: UserMapper) { @GetMapping("sayHi") fun sayHi(): PageResult<User> { val user = User().apply { name = "meow" username = "meow" age = 20 } userMapper.insert(user) println(user) var page = userMapper.page(PageInfo(1, 2), "2") return userService.page(PageInfo(2, 2), User(status = UserStatus.ENABLE)) } }
0
Kotlin
0
0
51840046fdc8e1f3316e41e5e4ee620e4eaff1a2
1,062
meow
Apache License 2.0
feature/blog/src/main/java/jp/mydns/kokoichi0206/blog/components/SkeletonBlogScreen.kt
android-project-46group
408,417,203
false
null
package jp.mydns.kokoichi0206.blog.components import androidx.compose.animation.core.* import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush.Companion.linearGradient import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import jp.mydns.kokoichi0206.common.ui.theme.SpaceSmall import jp.mydns.kokoichi0206.common.ui.theme.SpaceTiny import jp.mydns.kokoichi0206.common.ui.theme.Typography /** * Skeleton Screen * ref: https://mui.com/material-ui/react-skeleton/#variants */ @Composable fun SkeletonBlogScreen() { LazyColumn { items(8) { Row { Box(modifier = Modifier.weight(1f)) SkeletonPart(120.dp) Box(modifier = Modifier.weight(1f)) SkeletonPart(120.dp) Box(modifier = Modifier.weight(1f)) SkeletonPart(120.dp) Box(modifier = Modifier.weight(1f)) } } } } @Composable fun SkeletonPart( size: Dp, ) { val gradient = listOf( Color.LightGray.copy(alpha = 0.9f), Color.LightGray.copy(alpha = 0.3f), Color.LightGray.copy(alpha = 0.9f) ) val transition = rememberInfiniteTransition() val translateAnimation = transition.animateFloat( initialValue = 0f, targetValue = 1000f, animationSpec = infiniteRepeatable( animation = tween( durationMillis = 1000, easing = FastOutLinearInEasing ) ) ) val brush = linearGradient( colors = gradient, start = Offset(200f, 200f), end = Offset( x = translateAnimation.value, y = translateAnimation.value ) ) Column( modifier = Modifier .padding(vertical = SpaceSmall) .width(size), horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer( modifier = Modifier .blogImage() .background(brush), ) Text( modifier = Modifier .padding(top = SpaceSmall) .fillMaxWidth() .clip(RoundedCornerShape(5.dp)) .background(brush), text = "name", style = Typography.body2, color = Color.Transparent, ) Text( modifier = Modifier .padding(top = SpaceSmall) .padding(bottom = SpaceTiny) .fillMaxWidth() .clip(RoundedCornerShape(5.dp)) .background(brush), text = "time", style = Typography.caption, color = Color.Transparent, ) } }
14
Kotlin
0
2
d69f08e815a4780bd93a0e1bf274dc770155b06e
3,179
android
MIT License
app/src/main/java/com/task/noteapp/data/local/AppDatabase.kt
Hichamraf
491,177,404
false
{"Kotlin": 24919}
package com.task.noteapp.data.local import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.task.noteapp.model.Note import com.task.noteapp.utils.Converters @TypeConverters(Converters::class) @Database(entities = [Note::class], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun noteDao(): NoteDao }
0
Kotlin
0
0
11d0afd5f64d8c408d45c754bfe7872c4589f09f
403
Notes
Apache License 2.0
core/src/commonTest/kotlin/maryk/core/aggregations/metric/StatsAggregatorTest.kt
marykdb
290,454,412
false
{"Kotlin": 3039791, "JavaScript": 1004}
package maryk.core.aggregations.metric import maryk.test.models.TestMarykModel import kotlin.test.Test import kotlin.test.expect class StatsAggregatorTest { @Test fun aggregate() { val statsAggregator = StatsAggregator( Stats(TestMarykModel { int::ref }) ) expect( StatsResponse( TestMarykModel { int::ref }, min = null, max = null, sum = null, average = null, valueCount = 0uL ) ) { statsAggregator.toResponse() } statsAggregator.aggregate { 12936 } statsAggregator.aggregate { 452 } statsAggregator.aggregate { 789 } expect( StatsResponse( TestMarykModel { int::ref }, min = 452, max = 12936, sum = 14177, average = 4725, valueCount = 3uL ) ) { statsAggregator.toResponse() } } }
1
Kotlin
1
8
287377518680ab59adeb3bb93d1e37f8329e5eb7
1,062
maryk
Apache License 2.0
src/main/kotlin/com/lean/ciref/entities/RefactLocation.kt
leanresearchlab
646,446,761
false
null
package com.lean.ciref.entities import gr.uom.java.xmi.LocationInfo.CodeElementType class RefactLocation(val filePath:String,val startLine:Int,val endLine:Int,val startColumn:Int,val endColumn:Int,val codeElementType: CodeElementType,val description:String,val codeElement:String ) { }
0
Kotlin
1
1
ce43b078907cd639f846b6130099bb1909e708b2
287
ciref-refactor
MIT License
src/main/kotlin/miragefairy2024/mod/magicplant/TraitCondition.kt
MirageFairy
721,291,232
false
{"Kotlin": 917715, "Java": 14611, "Shell": 751}
package miragefairy2024.mod.magicplant import net.minecraft.text.Text import net.minecraft.util.math.BlockPos import net.minecraft.world.World // api interface TraitCondition { val emoji: Text val name: Text fun getFactor(world: World, blockPos: BlockPos): Double }
0
Kotlin
0
0
1bc8ce33e6ac9db06753be34e7f9d7d0a8790a56
281
MirageFairy2024
Apache License 2.0
ParkingPermitApp/app/src/main/java/com/example/parkingpermitapp/cameraview/RadioButtons.kt
ZeroTolerance225
789,532,216
false
{"Kotlin": 127055, "HTML": 125618, "Python": 62253, "Java": 56037, "CSS": 10518, "Dockerfile": 217}
package com.example.parkingpermitapp.cameraview import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.selection.selectable import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.VerticalAlignmentLine import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.parkingpermitapp.ui.theme.Navy @Composable fun RadioButtons(submitBatch: MutableState<Boolean>, clearBatch: MutableState<Boolean>, plateCount: MutableState<Int>, radioOptions: List<String>, selectedOption: String, onOptionSelected: (String) -> Unit) { val textDisplay = listOf("Plates Scanned: ", plateCount.value.toString() ) Column(horizontalAlignment = Alignment.CenterHorizontally) { var i = 0 radioOptions.forEach { text -> Row( Modifier .fillMaxWidth() .selectable( selected = (text == selectedOption), onClick = { onOptionSelected(text) } ) .padding(horizontal = 0.dp), verticalAlignment = Alignment.CenterVertically ) { RadioButton( selected = (text == selectedOption), onClick = { onOptionSelected(text) } ) Text( modifier = Modifier.padding(start = 0.dp), text = text, style = MaterialTheme.typography.titleMedium, color = Color(red = 17, green = 85, blue = 204, alpha = 255), fontSize = 17.sp, overflow = TextOverflow.Ellipsis ) if(i==0) {Spacer(modifier = Modifier.fillMaxWidth(0.1f))} else{ Spacer(modifier = Modifier.fillMaxWidth(0.27f))} Text( text = textDisplay[i], modifier = Modifier.padding(10.dp), style = MaterialTheme.typography.titleMedium, color = Color(red = 17, green = 85, blue = 204, alpha = 255), fontSize = 17.sp ) } i++ } Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally){ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { Button( onClick = { clearBatch.value = true }, modifier = Modifier .padding(10.dp) ) { Text("Clear Batch") } Button( onClick = { submitBatch.value = true }, modifier = Modifier .padding(10.dp) ) { Text("Batch Search") } } } } }
0
Kotlin
0
0
6895e28195b37cf8b6d6fda47a61c25bdece67aa
3,874
Capstone-License-Plate-Reader
Microsoft Public License
material-web/src/jsMain/kotlin/material/web/component/List.kt
CharLEE-X
762,328,281
false
{"Kotlin": 145688}
package material.web.component import androidx.compose.runtime.Composable import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.toAttrs import material.web.common.MdElement import material.web.common.MdTagElement import material.web.common.jsRequire import org.jetbrains.compose.web.dom.AttrBuilderContext import org.jetbrains.compose.web.dom.ContentBuilder @Suppress("UnsafeCastFromDynamic") @Composable fun List( attrs: AttrBuilderContext<MdElement>? = null, content: ContentBuilder<MdElement>? = null, ) { val tag = "list" MdTagElement( tagName = "md-$tag", applyAttrs = attrs, content = content ).also { jsRequire("@material/web/list/$tag.js") } } @Suppress("UnsafeCastFromDynamic") @Composable fun ListItem( attrs: AttrBuilderContext<MdElement>? = null, headline: String? = null, supportingText: String? = null, content: ContentBuilder<MdElement>? = null, ) { val tag = "list-item" MdTagElement( tagName = "md-$tag", applyAttrs = Modifier.toAttrs { attrs?.invoke(this) headline?.let { attr("headline", it) } supportingText?.let { attr("supportingText", it) } }, content = content ).also { jsRequire("@material/web/list/$tag.js") } }
0
Kotlin
0
0
1c0964e37ad6a75229acfdcb5a79816bdeb8bb6b
1,312
MaterialWeb-ComposeHtml
Apache License 2.0
src/main/kotlin/me/elliott/amethyst/commands/ListenerCommands.kt
the-programmers-hangout
251,071,618
false
{"Kotlin": 37591, "JavaScript": 3190, "Dockerfile": 546, "Shell": 181, "Batchfile": 123}
package me.elliott.amethyst.commands import me.aberrantfox.kjdautils.api.dsl.CommandSet import me.aberrantfox.kjdautils.api.dsl.commands import me.aberrantfox.kjdautils.internal.command.arguments.WordArg import me.elliott.amethyst.arguments.ChannelOrUserArg import me.elliott.amethyst.arguments.ListenerArg import me.elliott.amethyst.services.ListenerService import me.elliott.amethyst.services.ListenerState import net.dv8tion.jda.core.entities.TextChannel @CommandSet fun listenerCommands(listenerService: ListenerService) = commands { command("createListener") { description = "Create a listener." execute { val eventChannel = it.channel as TextChannel listenerService.createListener(it.author, eventChannel.guild, eventChannel) } } command("addSource") { description = "Add a listening source to a listener." expect(ListenerArg, ChannelOrUserArg) execute { val listener = it.args.component1() as ListenerState listenerService.addSource(listener, it.args.component2()) it.respond("Source :: **${it.args.component2()}** added successfully") } } command("addDestination") { description = "Add a destination for message that match the listeners criteria." expect(ListenerArg, ChannelOrUserArg) execute { val listener = it.args.component1() as ListenerState listenerService.addDestination(listener, it.args.component2()) it.respond("Destination :: **${it.args.component2()}** added successfully") } } command("addPattern") { description = "Add a pattern that the specified listener should match against." expect(ListenerArg, WordArg) execute { val listener = it.args.component1() as ListenerState val pattern = it.args.component2() as String listenerService.addPattern(listener, pattern) it.respond("Pattern :: **${it.args.component2()}** added successfully") } } }
0
Kotlin
0
1
830e3b006f8fc5632e797239815931815e39c99f
2,075
Amethyst
MIT License
src/main/kotlin/T64.kt
KilluaSSR
763,466,025
false
{"Kotlin": 106189, "Go": 1048}
class SolutionT64 { lateinit var memo : Array<IntArray> fun minPathSum(grid: Array<IntArray>): Int { memo = Array(grid.size*grid[0].size){ IntArray(grid[0].size){-666} } return dp(grid.size,grid[0].size,grid) } fun dp(m:Int,n:Int,grid: Array<IntArray>):Int{ if(m==0&&n==0)return grid[0][0] if(m<0||n<0)return Int.MAX_VALUE if(memo[m][n]!=-666)return memo[m][n] memo[m][n] = Math.min(dp(m-1,n,grid),dp(m,n-1,grid))+grid[m][n] return memo[m][n] } }
0
Kotlin
0
1
879d82d074d91dd3548aeaa94c5ea54bd8cada2c
522
LeetcodeKotlin
MIT License
kradle-android/src/main/kotlin/io/github/lyxnx/kradle/android/AndroidApplicationPlugin.kt
Lyxnx
688,171,299
false
{"Kotlin": 48071}
package io.github.lyxnx.kradle.android import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.variant.ApplicationAndroidComponentsExtension import io.github.lyxnx.kradle.android.dsl.BuildType import io.github.lyxnx.kradle.android.dsl.android import io.github.lyxnx.kradle.android.dsl.androidComponents import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.kotlin.dsl.hasPlugin import org.jetbrains.kotlin.gradle.plugin.KotlinMultiplatformPluginWrapper public class AndroidApplicationPlugin : BaseAndroidPlugin() { override fun Project.configure() { if (plugins.hasPlugin(KotlinMultiplatformPluginWrapper::class)) { throw GradleException("Kotlin Multiplatform plugin is not supported with the Android Application plugin. Only library projects are supported.") } applyBasePlugin(Constants.APPLICATION_PLUGIN_ID) configureApp() androidComponents<ApplicationAndroidComponentsExtension> { finalizeDsl { it.finalizeApp(configPlugin.androidOptions) } } } private fun Project.configureApp() = android<ApplicationExtension> { defaultConfig { proguardFiles( "proguard-rules.pro", getDefaultProguardFile("proguard-android-optimize.txt") ) } buildTypes { debug { applicationIdSuffix = ".${BuildType.DEBUG}" isDebuggable = true isMinifyEnabled = false isShrinkResources = false } release { applicationIdSuffix = "" isDebuggable = false isMinifyEnabled = true isShrinkResources = true } } } private fun ApplicationExtension.finalizeApp(options: AndroidOptions) { defaultConfig { targetSdk = options.targetSdk.get() } } }
0
Kotlin
0
0
0d91efecbb497213cee169060d052d938f374e43
1,992
kradle
Apache License 2.0
app/src/main/java/com/dicoding/submission/machinelearning/adapter/PredictionAdapter.kt
hanyarui
800,038,667
false
{"Kotlin": 23169}
package com.dicoding.submission.machinelearning.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.dicoding.submission.machinelearning.R import com.dicoding.submission.machinelearning.local.data.Prediction class PredictionAdapter(private val predictionList: List<Prediction>) : RecyclerView.Adapter<PredictionAdapter.ViewHolder>() { private var onDeleteClickListener: OnDeleteClickListener? = null interface OnDeleteClickListener { fun onDeleteClick(position: Int) } fun setOnDeleteClickListener(listener: OnDeleteClickListener) { onDeleteClickListener = listener } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_history, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentItem = predictionList[position] if (currentItem.result.isNotEmpty()) { holder.bind(currentItem) holder.itemView.visibility = View.VISIBLE holder.itemView.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) // Atur kembali parameter tata letak } else { holder.itemView.visibility = View.GONE holder.itemView.layoutParams = RecyclerView.LayoutParams(0, 0) } } override fun getItemCount() = predictionList.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val imageView: ImageView = itemView.findViewById(R.id.savedImg) val resultTextView: TextView = itemView.findViewById(R.id.tvLabel) val deleteImageView: ImageButton = itemView.findViewById(R.id.btnDelete) fun bind(prediction: Prediction) { Glide.with(itemView.context) .load(prediction.imagePath) .placeholder(R.drawable.ic_place_holder) .error(R.drawable.ic_launcher_background) .into(imageView) resultTextView.text = prediction.result deleteImageView.setOnClickListener { onDeleteClickListener?.onDeleteClick(adapterPosition) } } } }
0
Kotlin
0
0
a6a711d026d82ddbb3f64d92a27f262a0580e4d6
2,517
BangkitAcademy_BPMLA_Submission
MIT License
ShadhinMusicLibrary/src/main/java/com/myrobi/shadhinmusiclibrary/fragments/CreatePlaylistFragment.kt
shadhin-music
589,150,241
false
null
package com.myrobi.shadhinmusiclibrary.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.myrobi.shadhinmusiclibrary.R import com.myrobi.shadhinmusiclibrary.fragments.base.BaseFragment internal class CreatePlaylistFragment : BaseFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { return inflater.inflate(R.layout.my_bl_sdk_fragment_create_playlist, container, false) } }
0
Kotlin
0
0
99e11cc3a68fd68607401fca71e32003b638025c
573
MyRobiShadhinSDK
MIT License
src/main/kotlin/io/github/lobodpav/spock/action/NewSpecificationAction.kt
lobodpav
671,811,601
false
{"Kotlin": 69613, "Groovy": 57060, "HTML": 886}
package io.github.lobodpav.spock.action import com.intellij.ide.actions.CreateFileFromTemplateDialog import com.intellij.ide.actions.JavaCreateTemplateInPackageAction import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import io.github.lobodpav.spock.extension.testCreator.spockAvailable import io.github.lobodpav.spock.icon.SpockIcon import io.github.lobodpav.spock.logging.Logger import io.github.lobodpav.spock.template.SpecificationCreator import io.github.lobodpav.spock.template.SpecificationTemplate import io.github.lobodpav.spock.validator.FullyQualifiedNameValidator import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition class NewSpecificationAction : JavaCreateTemplateInPackageAction<GrTypeDefinition>( { ACTION_NAME }, { "Creates a new $ACTION_NAME" }, { SpockIcon.specification }, setOf(JavaSourceRootType.TEST_SOURCE), ), DumbAware { private companion object : Logger() { private const val ACTION_NAME = "Spock Specification" } override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) { builder .setTitle("New $ACTION_NAME") .addKind("Class", SpockIcon.specification, SpecificationTemplate.SIMPLE.fileName) .setValidator(FullyQualifiedNameValidator()) } override fun isAvailable(dataContext: DataContext): Boolean { val module = dataContext.getData(LangDataKeys.MODULE) ?: return false // Skip Spock classpath check when in Dumb mode to allow users to code Specifications during indexing return super.isAvailable(dataContext) && module.spockAvailable } override fun getActionName(directory: PsiDirectory, newName: String, templateName: String): String = ACTION_NAME /** * Place the cursor at the first sample method in the created Specification. * Defaults to the left curly brace of the new Specification class. */ override fun getNavigationElement(createdElement: GrTypeDefinition): PsiElement? = createdElement.body?.methods?.get(0) ?: createdElement.lBrace public override fun doCreate(psiDirectory: PsiDirectory, className: String, templateName: String): GrTypeDefinition { val specificationTemplate = SpecificationTemplate.fromFileName(templateName) return SpecificationCreator.createFromTemplate(psiDirectory, className, specificationTemplate) } }
0
Kotlin
0
2
f8acf0da8ef61c8d70681a16ab97473fcb84261d
2,715
spock-intellij-plugin
Apache License 2.0
app/src/main/java/com/mobdeve/gonzales/lee/ong/artemis/ViewOwnPostActivity.kt
memgonzales
390,384,567
false
null
package com.mobdeve.gonzales.lee.ong.artemis import android.app.Activity import android.content.Context import android.content.Intent import android.content.res.ColorStateList import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.LayoutInflater import android.view.View import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.bumptech.glide.Glide import com.facebook.CallbackManager import com.facebook.FacebookCallback import com.facebook.FacebookException import com.facebook.share.Sharer import com.facebook.share.model.SharePhoto import com.facebook.share.model.SharePhotoContent import com.facebook.share.widget.ShareDialog import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.floatingactionbutton.FloatingActionButton import de.hdodenhof.circleimageview.CircleImageView import java.io.File /** * Class handling the functionalities related to viewing a user's own post. * * @constructor Creates a class that handles the functionalities related to viewing a user's * own post. */ class ViewOwnPostActivity : AppCompatActivity() { /** * Profile picture of the user whose post is being viewed. */ private lateinit var civItemViewOwnPostProfilePic: CircleImageView /** * Username of the user whose post is being viewed. */ private lateinit var tvItemViewOwnPostUsername: TextView /** * Artwork of the post being viewed. */ private lateinit var ivItemViewOwnPostPostImg: ImageView /** * Title of the post being viewed. */ private lateinit var tvItemViewOwnPostTitle: TextView /** * Number of upvotes of the post being viewed. */ private lateinit var tvItemViewOwnPostUpvoteCounter: TextView /** * Number of comments of the post being viewed. */ private lateinit var tvItemViewOwnPostComments: TextView /** * Date posted of the post being viewed. */ private lateinit var tvItemViewOwnPostDatePosted: TextView /** * Medium of the artwork being viewed. */ private lateinit var tvItemViewOwnPostMedium: TextView /** * Dimensions of the artwork being viewed. */ private lateinit var tvItemViewOwnPostDimensions: TextView /** * Description of the post being viewed. */ private lateinit var tvItemViewOwnPostDescription: TextView /** * Tags of the post being viewed. */ private lateinit var tvItemViewOwnPostTags: TextView /** * Image view holding the highlight icon. */ private lateinit var ivItemViewOwnPostHighlight: ImageView /** * Text view holding the "Highlight" label. */ private lateinit var tvItemViewOwnPostHighlight: TextView /** * Constraint layout holding the highlight option. */ private lateinit var clItemViewOwnPostHighlight: ConstraintLayout /** * Constraint layout holding the comment option. */ private lateinit var clItemViewOwnPostComment: ConstraintLayout /** * Constraint layout holding the share option. */ private lateinit var clItemViewOwnPostShare: ConstraintLayout /** * Bottom navigation view containing the menu items for Home, Followed, Bookmarks, and Profile. */ private lateinit var bnvViewOwnPostBottom: BottomNavigationView /** * Image button for opening the own post options bottom dialog */ private lateinit var ibItemViewOwnPostOptions: ImageButton /** * Bottom sheet dialog displayed when the user clicks the image button for viewing the own * post options. */ private lateinit var btmViewOwnPost: BottomSheetDialog /** * Constraint layout holding the edit post option. */ private lateinit var clDialogViewOwnPostEdit: ConstraintLayout /** * Constraint layout holding the delete post option. */ private lateinit var clDialogViewOwnPostDelete: ConstraintLayout /** * Bottom sheet dialog displayed when the user clicks the floating action button * for posting an artwork. */ private lateinit var btmAddPost: BottomSheetDialog /** * Floating action button for posting an artwork. */ private lateinit var fabAddPost: FloatingActionButton /** * Clickable constraint layout (part of the bottom sheet dialog) related to the option * of the user uploading a photo of their artwork from the Gallery. */ private lateinit var clDialogPostArtworkGallery: ConstraintLayout /** * Clickable constraint layout (part of the bottom sheet dialog) related to the option * of the user taking a photo of their artwork using the device camera. */ private lateinit var clDialogPostArtworkPhoto: ConstraintLayout /** * Layout for registering a swipe gesture as a request to refresh this activity. */ private lateinit var srlViewOwnPost: SwipeRefreshLayout /** * Callback manager for handling the share on Facebook feature. */ private lateinit var cmFacebook: CallbackManager /** * Share dialog for sharing the artwork on Facebook. */ private lateinit var sdFacebook: ShareDialog /** * Photo of the artwork for posting. */ private lateinit var photoFile: File /** * Activity result launcher related to taking photos using the device camera. */ private lateinit var cameraLauncher: ActivityResultLauncher<Intent> /** * Activity result launcher related to choosing photos from the Gallery. */ private lateinit var galleryLauncher: ActivityResultLauncher<Intent> /** * Object for accessing the Firebase helper methods. */ private lateinit var firebaseHelper: FirebaseHelper /** * Called when the activity is starting. * * @param savedInstanceState If the activity is being re-initialized after previously being * shut down then this Bundle contains the data it most recently supplied in * <code>onSaveInstanceState(Bundle)</code>. Note: Otherwise it is <code>null</code>. * This value may be <code>null</code>. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_view_own_post) this.civItemViewOwnPostProfilePic = findViewById(R.id.civ_item_view_own_post_profile_pic) this.tvItemViewOwnPostUsername = findViewById(R.id.tv_item_view_own_post_username) this.ivItemViewOwnPostPostImg = findViewById(R.id.iv_item_view_own_post_post) this.tvItemViewOwnPostTitle = findViewById(R.id.tv_item_view_own_post_title) this.tvItemViewOwnPostUpvoteCounter = findViewById(R.id.tv_item_view_own_post_upvote_counter) this.tvItemViewOwnPostComments = findViewById(R.id.tv_item_view_own_post_comments) this.tvItemViewOwnPostDatePosted = findViewById(R.id.tv_item_view_own_post_date) this.tvItemViewOwnPostMedium = findViewById(R.id.tv_item_view_own_post_medium) this.tvItemViewOwnPostDimensions = findViewById(R.id.tv_item_view_own_post_dimen) this.tvItemViewOwnPostDescription = findViewById(R.id.tv_item_view_own_post_desc) this.tvItemViewOwnPostTags = findViewById(R.id.tv_item_view_own_post_tags) this.ivItemViewOwnPostHighlight = findViewById(R.id.iv_item_view_own_post_highlight) this.tvItemViewOwnPostHighlight = findViewById(R.id.tv_item_view_own_post_highlight) this.clItemViewOwnPostHighlight = findViewById(R.id.cl_item_view_own_post_highlight) this.clItemViewOwnPostComment = findViewById(R.id.cl_item_view_own_post_comment) this.clItemViewOwnPostShare = findViewById(R.id.cl_item_view_own_post_share) this.ibItemViewOwnPostOptions = findViewById(R.id.ib_item_view_own_post_options) this.btmViewOwnPost = BottomSheetDialog(this@ViewOwnPostActivity) initIntent() initComponents() initBottom() addPost() initGalleryLauncher(this@ViewOwnPostActivity) initCameraLauncher(this@ViewOwnPostActivity) } /** * Initializes the activity result launcher related to choosing photos from the Gallery. * * @param packageContext Context tied to this activity. */ private fun initGalleryLauncher(packageContext: Context) { galleryLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { val intent = Intent(packageContext, PostArtworkActivity::class.java) intent.putExtra( Keys.KEY_POST_ARTWORK.name, result.data?.data.toString() ) intent.putExtra( Keys.KEY_POST_FROM.name, PostArtworkUtil.FROM_GALLERY ) startActivity(intent) } } } /** * Initializes the activity result launcher related to taking photos using the device camera. * * @param packageContext Context tied to this activity. */ private fun initCameraLauncher(packageContext: Context) { cameraLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { val intent = Intent(packageContext, PostArtworkActivity::class.java) intent.putExtra( Keys.KEY_POST_ARTWORK.name, photoFile.absolutePath ) intent.putExtra( Keys.KEY_POST_FROM.name, PostArtworkUtil.FROM_CAMERA ) startActivity(intent) } } } /** * Initializes the components of the activity. */ private fun initComponents() { setSupportActionBar(findViewById(R.id.toolbar_view_own_post)) initActionBar() initSwipeRefresh() } /** * Initializes the swipe refresh layout and defines the behavior when the screen is swiped * to refresh. */ private fun initSwipeRefresh() { this.srlViewOwnPost = findViewById(R.id.srl_view_own_post) srlViewOwnPost.setOnRefreshListener { onRefresh() } srlViewOwnPost.setColorSchemeResources(R.color.purple_main, R.color.pinkish_purple, R.color.purple_pics_lighter, R.color.pinkish_purple_lighter) } /** * Refetches data from the database and reshuffles the display of existing data when the screen * is swiped to refresh. */ private fun onRefresh() { Handler(Looper.getMainLooper()).postDelayed({ initIntent() srlViewOwnPost.isRefreshing = false }, AnimationDuration.REFRESH_TIMEOUT.toLong()) } /** * Initializes the intent passed to the activity. */ private fun initIntent() { val intent: Intent = intent val postId = intent.getStringExtra(Keys.KEY_POSTID.name) val userIdPost = intent.getStringExtra(Keys.KEY_USERID.name) this.firebaseHelper = FirebaseHelper(this@ViewOwnPostActivity, postId, userIdPost) val profilePicture = intent.getStringExtra(Keys.KEY_PROFILE_PICTURE.name) val username = intent.getStringExtra(Keys.KEY_USERNAME.name) val postImg = intent.getStringExtra(Keys.KEY_POST.name) val title = intent.getStringExtra(Keys.KEY_TITLE.name) val upvoteCounter = intent.getIntExtra(Keys.KEY_NUM_UPVOTES.name, 0) val comments = intent.getIntExtra(Keys.KEY_NUM_COMMENTS.name, 0) val datePosted = intent.getStringExtra(Keys.KEY_DATE_POSTED.name) val medium = intent.getStringExtra(Keys.KEY_MEDIUM.name) val dimensions = intent.getStringExtra(Keys.KEY_DIMENSIONS.name) val description = intent.getStringExtra(Keys.KEY_DESCRIPTION.name) val tags = intent.getStringArrayListExtra(Keys.KEY_TAGS.name) var highlight = intent.getBooleanExtra(Keys.KEY_HIGHLIGHT.name, false) var bookmark = intent.getBooleanExtra(Keys.KEY_BOOKMARK.name, false) var upvote = intent.getBooleanExtra(Keys.KEY_UPVOTE.name, false) var upvoteString = "" var commentString = "" if (upvoteCounter == 1) { upvoteString = "$upvoteCounter upvote" } else { upvoteString = "$upvoteCounter upvotes" } if (comments == 1) { commentString = "$comments comment" } else { commentString = "$comments comments" } val tagsString = tags?.joinToString(", ") if (!(this@ViewOwnPostActivity as Activity).isFinishing) { Glide.with(this@ViewOwnPostActivity) .load(profilePicture) .placeholder(R.drawable.chibi_artemis_hd) .error(R.drawable.chibi_artemis_hd) .into(this.civItemViewOwnPostProfilePic) } this.tvItemViewOwnPostUsername.text = username if (!(this@ViewOwnPostActivity as Activity).isFinishing) { Glide.with(this@ViewOwnPostActivity) .load(postImg) .placeholder(R.drawable.placeholder) .error(R.drawable.placeholder) .into(this.ivItemViewOwnPostPostImg) } if (!title.isNullOrEmpty()){ this.tvItemViewOwnPostTitle.visibility = View.VISIBLE this.tvItemViewOwnPostTitle.text = title } else{ this.tvItemViewOwnPostTitle.visibility = View.INVISIBLE } this.tvItemViewOwnPostUpvoteCounter.text = upvoteString this.tvItemViewOwnPostComments.text = commentString this.tvItemViewOwnPostDatePosted.text = datePosted if(!medium.isNullOrEmpty()){ this.tvItemViewOwnPostMedium.visibility = View.VISIBLE this.tvItemViewOwnPostMedium.text = medium } else{ this.tvItemViewOwnPostMedium.visibility = View.GONE } if(!dimensions.isNullOrEmpty()){ this.tvItemViewOwnPostDimensions.visibility = View.VISIBLE this.tvItemViewOwnPostDimensions.text = dimensions } else{ this.tvItemViewOwnPostDimensions.visibility = View.GONE } if(!description.isNullOrEmpty()){ this.tvItemViewOwnPostDescription.visibility = View.VISIBLE this.tvItemViewOwnPostDescription.text = description } else{ this.tvItemViewOwnPostDescription.visibility = View.GONE } this.tvItemViewOwnPostTags.text = tagsString updateHighlight(highlight) clItemViewOwnPostHighlight.setOnClickListener { if (highlight) { highlight = false updateHighlight(highlight) this.firebaseHelper.updateHighlightDB(postId!!, null) } else { highlight = true updateHighlight(highlight) Toast.makeText(this@ViewOwnPostActivity, "Added to your Highlights", Toast.LENGTH_SHORT).show() this.firebaseHelper.updateHighlightDB(postId!!, postId) } } clItemViewOwnPostComment.setOnClickListener { val intent = Intent(this, ViewOwnPostCommentsActivity::class.java) intent.putExtra( Keys.KEY_USERID.name, userIdPost ) intent.putExtra( Keys.KEY_PROFILE_PICTURE.name, profilePicture ) intent.putExtra( Keys.KEY_USERNAME.name, username ) intent.putExtra( Keys.KEY_POST.name, postImg ) intent.putExtra( Keys.KEY_TITLE.name, title ) intent.putExtra( Keys.KEY_POSTID.name, postId ) intent.putExtra( Keys.KEY_NUM_UPVOTES.name, upvoteCounter ) intent.putExtra( Keys.KEY_NUM_COMMENTS.name, comments ) intent.putExtra( Keys.KEY_DATE_POSTED.name, datePosted ) intent.putExtra( Keys.KEY_MEDIUM.name, medium ) intent.putExtra( Keys.KEY_DIMENSIONS.name, dimensions ) intent.putExtra( Keys.KEY_DESCRIPTION.name, description ) intent.putExtra( Keys.KEY_TAGS.name, tags ) intent.putExtra( Keys.KEY_BOOKMARK.name, bookmark ) intent.putExtra( Keys.KEY_HIGHLIGHT.name, highlight ) startActivity(intent) finish() } clItemViewOwnPostShare.setOnClickListener { shareOnFacebook() } civItemViewOwnPostProfilePic.setOnClickListener { val intent = Intent(this, ViewProfileActivity::class.java) startActivity(intent) } tvItemViewOwnPostUsername.setOnClickListener { val intent = Intent(this, ViewProfileActivity::class.java) startActivity(intent) } val editTitle: String = title.toString() val editMedium: String = medium.toString() val editDimensions: String = dimensions.toString() val editDescription: String = description.toString() val editPostImg: String = postImg.toString() val editTags: String = tagsString.toString() launchDialog(userIdPost.toString(), postId.toString(), editTitle, editMedium, editDimensions, editDescription, editPostImg, editTags) } /** * Launches the bottom sheet dialog for choosing the own post options. * * @param userIdPost Unique identifier of the user who posted the post. * @param postId Unique identifier of the post. * @param title Title of the post. * @param medium Medium of the artwork. * @param dimensions Dimensions of the artwork. * @param description Description of the post. * @param postImg The posted artwork. * @param tags Tags of the post. */ private fun launchDialog(userIdPost: String, postId: String, title: String, medium: String, dimensions: String, description: String, postImg: String, tags: String) { val view = LayoutInflater.from(this@ViewOwnPostActivity).inflate(R.layout.dialog_own_post, null) this.ibItemViewOwnPostOptions.setOnClickListener { btmViewOwnPost.setContentView(view) this.clDialogViewOwnPostEdit = btmViewOwnPost.findViewById(R.id.cl_dialog_own_post_edit)!! this.clDialogViewOwnPostDelete = btmViewOwnPost.findViewById(R.id.cl_dialog_own_post_delete)!! clDialogViewOwnPostEdit.setOnClickListener { btmViewOwnPost.dismiss() val intent = Intent(this@ViewOwnPostActivity, EditPostActivity::class.java) intent.putExtra( Keys.KEY_USERID.name, userIdPost ) intent.putExtra( Keys.KEY_POSTID.name, postId ) intent.putExtra( Keys.KEY_TITLE.name, title ) intent.putExtra( Keys.KEY_MEDIUM.name, medium ) intent.putExtra( Keys.KEY_DIMENSIONS.name, dimensions ) intent.putExtra( Keys.KEY_DESCRIPTION.name, description ) intent.putExtra( Keys.KEY_TAGS.name, tags ) intent.putExtra( Keys.KEY_POST.name, postImg ) startActivity(intent) finish() } clDialogViewOwnPostDelete.setOnClickListener { firebaseHelper.deletePostDB(postId, false) val intent = Intent(this@ViewOwnPostActivity, BrowseOwnPostsActivity::class.java) startActivity(intent) finish() btmViewOwnPost.dismiss() } btmViewOwnPost.show() } } /** * Adds a back button to the action bar. */ private fun initActionBar() { supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) } /** * Sets the listeners for the menu selection found in the bottom navigation view. */ private fun initBottom() { this.bnvViewOwnPostBottom = findViewById(R.id.nv_view_own_post_bottom) BottomMenuUtil.setFinishBottomMenuListeners(bnvViewOwnPostBottom, this, this@ViewOwnPostActivity) } /** * Updates the highlight status of a post. * * @param highlight <code>true</code> if the user chooses to highlight the post; <code>false</code> * if the user chooses to remove the highlight status of the post */ private fun updateHighlight(highlight: Boolean) { if(highlight) { this.ivItemViewOwnPostHighlight.setImageResource(R.drawable.baseline_star_24) this.ivItemViewOwnPostHighlight.imageTintList = ColorStateList.valueOf( ContextCompat.getColor(this.ivItemViewOwnPostHighlight.context, R.color.pinkish_purple) ) this.tvItemViewOwnPostHighlight.setTextColor(ColorStateList.valueOf( ContextCompat.getColor(this.tvItemViewOwnPostHighlight.context, R.color.pinkish_purple)) ) } else { this.ivItemViewOwnPostHighlight.setImageResource(R.drawable.outline_star_border_24) this.ivItemViewOwnPostHighlight.imageTintList = ColorStateList.valueOf( ContextCompat.getColor(this.ivItemViewOwnPostHighlight.context, R.color.default_gray) ) this.tvItemViewOwnPostHighlight.setTextColor(ColorStateList.valueOf( ContextCompat.getColor(this.tvItemViewOwnPostHighlight.context, R.color.default_gray)) ) } } /** * Sets the listeners in relation to adding an artwork (that is, by either choosing an image * from the gallery or taking a photo using the device camera) to be posted on Artemis. */ private fun addPost() { this.btmAddPost = BottomSheetDialog(this@ViewOwnPostActivity) this.fabAddPost = findViewById(R.id.fab_view_own_post_add) val view = LayoutInflater.from(this@ViewOwnPostActivity).inflate(R.layout.dialog_post_artwork, null) this.fabAddPost.setOnClickListener { btmAddPost.setContentView(view) this.clDialogPostArtworkGallery = btmAddPost.findViewById(R.id.cl_dialog_post_artwork_gallery)!! this.clDialogPostArtworkPhoto = btmAddPost.findViewById(R.id.cl_dialog_post_artwork_photo)!! clDialogPostArtworkGallery.setOnClickListener { PostArtworkUtil.chooseFromGallery(this, galleryLauncher) } clDialogPostArtworkPhoto.setOnClickListener { photoFile = PostArtworkUtil.takeFromCamera(this, this@ViewOwnPostActivity, cameraLauncher) } btmAddPost.show() } } /** * Shares the posted artwork on the user's Facebook account. */ private fun shareOnFacebook() { cmFacebook = CallbackManager.Factory.create() sdFacebook = ShareDialog(this@ViewOwnPostActivity) sdFacebook.registerCallback(cmFacebook, object : FacebookCallback<Sharer.Result?> { override fun onSuccess(result: Sharer.Result?) { Toast.makeText(this@ViewOwnPostActivity, "Shared on Facebook", Toast.LENGTH_SHORT).show() } override fun onCancel() { Toast.makeText(this@ViewOwnPostActivity, "Sharing cancelled", Toast.LENGTH_SHORT).show() } override fun onError(error: FacebookException) { Toast.makeText(this@ViewOwnPostActivity, "Sharing error occurred", Toast.LENGTH_SHORT).show() } }) if (ShareDialog.canShow(SharePhotoContent::class.java)) { val bitmapDrawable = ivItemViewOwnPostPostImg.drawable as BitmapDrawable val bitmap = bitmapDrawable.bitmap val username = "@" + tvItemViewOwnPostUsername.text.toString() val captionedImage = CaptionPlacer.placeCaption(bitmap, username, "Posted on Artemis") val sharePhoto = SharePhoto.Builder() .setBitmap(captionedImage) .build() val sharePhotoContent = SharePhotoContent.Builder() .addPhoto(sharePhoto) .build() sdFacebook.show(sharePhotoContent) Toast.makeText(this@ViewOwnPostActivity, "Opening Facebook", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@ViewOwnPostActivity, "Unable to share post", Toast.LENGTH_SHORT).show() } } /** * Callback for the result from requesting permissions. * * @param requestCode The request code passed in <code> * ActivityCompat.requestPermissions(android.app.Activity, String[], int)</code>. * @param permissions The requested permissions. Never null. * @param grantResults The grant results for the corresponding permissions which is either <code> * PackageManager.PERMISSION_GRANTED</code> or <code>PackageManager.PERMISSION_DENIED</code>. * Never null. */ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) permissionsResult(requestCode, grantResults, this@ViewOwnPostActivity, this) } /** * Defines the behavior related to choosing a photo from the Gallery or taking a photo using * the device camera based on the permissions granted by the user. * * @param requestCode The request code passed in <code> * ActivityCompat.requestPermissions(android.app.Activity, String[], int)</code>. * @param grantResults The grant results for the corresponding permissions which is either <code> * PackageManager.PERMISSION_GRANTED</code> or <code>PackageManager.PERMISSION_DENIED</code>. * Never null. * @param context Context tied to this activity. * @param activity This activity. */ private fun permissionsResult(requestCode: Int, grantResults: IntArray, context: Context, activity: Activity ) { when (requestCode) { RequestCodes.REQUEST_CODE_POST_CAMERA.ordinal -> { val temp: File? = PostArtworkUtil.permissionsResultCamera( grantResults, activity, context, cameraLauncher ) if (temp != null) { photoFile = temp } } RequestCodes.REQUEST_CODE_POST_GALLERY.ordinal -> { PostArtworkUtil.permissionsResultGallery(grantResults, context, galleryLauncher) } } } }
0
Kotlin
0
0
9d92a5a2905afd1e9869854f2c5238bb860ba8cd
28,599
artemis-art-app
Apache License 1.1
tegro-bot/src/main/kotlin/money/tegro/bot/exceptions/AccountMinAmountException.kt
TegroTON
607,921,195
false
{"Kotlin": 492434, "Java": 37393, "Dockerfile": 341}
package money.tegro.bot.exceptions import money.tegro.bot.objects.Account class AccountMinAmountException( val account: Account ) : RuntimeException()
21
Kotlin
4
7
6e3419f3f4d870a6e7e5703a87d44a009b99e477
156
Telegram-Cryptocurrency-Wallet-TON-Kotlin
MIT License
data/src/main/java/com/mshaw/data/util/extensions/Response+Extensions.kt
michaeltheshah
697,087,832
false
{"Kotlin": 37602}
package com.mshaw.data.util.extensions import com.mshaw.data.model.ErrorResponse import com.mshaw.data.util.state.AwaitResult import kotlinx.serialization.json.Json import retrofit2.HttpException import retrofit2.Response fun <T> Response<T>.awaitResult(): AwaitResult<T> { return try { if (isSuccessful) { val body = body() if (body != null) { AwaitResult.Ok(body, raw()) } else { AwaitResult.Error(NullPointerException("Response body is null"), raw(), errorBody()?.string()) } } else { AwaitResult.Error(HttpException(this), raw(), errorBody()?.string()) } } catch (e: Exception) { val json = errorBody()?.string() val errorResponse = tryOrNull { Json.decodeFromString<ErrorResponse>(json!!) } AwaitResult.Error(e, raw(), errorBody()?.string(), errorResponse) } } val <T> Response<T>.value: T get() = try { body() as T } catch (e: Exception) { throw HttpException(this) }
0
Kotlin
0
0
094807e606fbac5f4b99ff0b69e2e6ff20b48afa
1,056
WeatherAppChase
Apache License 2.0
app/src/main/java/com/dartharrmi/weathery/base/BaseApp.kt
jArrMi
303,480,302
false
{"Kotlin": 88851}
package com.dartharrmi.weathery.base import android.app.Application import androidx.appcompat.app.AppCompatDelegate import androidx.multidex.MultiDexApplication import com.dartharrmi.weathery.di.DependencyContainer /** * Base [Application] for the current app, initializes the dependency injection. */ class BaseApp : MultiDexApplication() { override fun onCreate() { super.onCreate() DependencyContainer.initDependencies(this) AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } }
0
Kotlin
0
0
cb7baa67ba30e7d76731df77a9eaf93be29e3396
529
weathery
MIT License
kzmq-tests/src/commonTest/kotlin/org/zeromq/tests/sockets/DealerRouterTests.kt
ptitjes
386,722,015
false
{"Kotlin": 332545}
/* * Copyright (c) 2021-2024 <NAME> and Kzmq contributors. * Use of this source code is governed by the Apache 2.0 license. */ package org.zeromq.tests.sockets import io.kotest.core.spec.style.* import io.kotest.matchers.* import io.kotest.matchers.equals.* import kotlinx.atomicfu.* import kotlinx.coroutines.* import kotlinx.io.* import kotlinx.io.bytestring.* import org.zeromq.* import org.zeromq.tests.utils.* private const val REQUEST_MARKER = "REQ" private const val REPLY_MARKER = "REP" @Suppress("unused") class DealerRouterTests : FunSpec({ withContexts("base").config( // TODO fix when testing more Dealer and Router logic // skip = setOf("jeromq"), ) { ctx1, ctx2, protocol -> val dealerCount = 2 val routerCount = 3 val addresses = Array(routerCount) { randomEndpoint(protocol) } val routers = addresses.map { ctx2.createRouter().apply { bind(it) } } val dealers = Array(dealerCount) { index -> ctx1.createDealer().apply { routingId = index.encodeAsRoutingId() addresses.forEach { connect(it) } waitForConnections(addresses.size) } } class Trace { val receivedReplyIds = atomic(setOf<Int>()) } val trace = Trace() coroutineScope { launch { repeat(dealerCount * routerCount) { requestId -> val dealerId = requestId % dealers.size val dealer = dealers[dealerId] dealer.send { writeFrame(REQUEST_MARKER) writeFrame { writeByte(requestId.toByte()) } } } } routers.forEach { router -> launch { repeat(dealerCount) { val (dealerId, requestId) = router.receive { val dealerId = readFrame { readByteString() } readFrame { readString() shouldBe REQUEST_MARKER } val requestId = readFrame { readByte() } dealerId to requestId } router.send { writeFrame(dealerId) writeFrame(REPLY_MARKER) writeFrame { writeByte(requestId) } writeFrame(dealerId) } } } } dealers.forEach { dealer -> launch { repeat(routerCount) { val (dealerId, requestId) = dealer.receive { readFrame { readString() shouldBe REPLY_MARKER } val requestId = readFrame { readByte() } val dealerId = readFrame { readByteString() } dealerId to requestId } val realDealerId = dealerId.decodeFromRoutingId() realDealerId shouldBe dealer.routingId?.decodeFromRoutingId() realDealerId shouldBe requestId % dealerCount trace.receivedReplyIds.getAndUpdate { it + requestId.toInt() } } } } } trace.receivedReplyIds.value shouldBeEqual (0 until 6).toSet() } }) /* * TODO Remove when https://github.com/zeromq/zeromq.js/issues/506 is fixed. */ private fun Int.encodeAsRoutingId(): ByteString = buildByteString { append(1.toByte()) append((this@encodeAsRoutingId + 1).toByte()) } private fun ByteString.decodeFromRoutingId(): Int { require(size == 2) { "Size should be 2, but is $size" } require(this[0] == 1.toByte()) return this[1].toInt() - 1 }
21
Kotlin
1
16
6ed177d7e3859fda0c17ffdcd1e43b2d51a4cf1c
3,922
kzmq
Apache License 2.0
app/src/main/java/com/example/nordicnews/ui/shared/ErrorScreen.kt
avanisoam
803,286,041
false
{"Kotlin": 164967}
package com.example.nordicnews.ui.shared import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.nordicnews.R @Composable fun ErrorScreen(modifier: Modifier = Modifier) { Column( modifier = modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = R.drawable.ic_connection_error), contentDescription = "" ) Text(text = stringResource(R.string.loading_failed), modifier = Modifier.padding(16.dp)) } }
0
Kotlin
0
0
d73886238657919c1a7887e06eea8abbab1b3c82
1,047
NordicNews
MIT License
geary-commons/src/main/kotlin/com/mineinabyss/geary/commons/events/configurable/EventTriggerListener.kt
MineInAbyss
388,677,224
false
null
package com.mineinabyss.geary.commons.events.configurable import com.mineinabyss.geary.annotations.AutoScan import com.mineinabyss.geary.annotations.Handler import com.mineinabyss.geary.commons.events.configurable.components.EventRun import com.mineinabyss.geary.commons.events.configurable.components.EventRunBuilder import com.mineinabyss.geary.serialization.parseEntity import com.mineinabyss.geary.systems.GearyListener import com.mineinabyss.geary.systems.accessors.EventScope import com.mineinabyss.geary.systems.accessors.SourceScope import com.mineinabyss.geary.systems.accessors.TargetScope import com.mineinabyss.geary.systems.accessors.relation @AutoScan class EventRunListener : GearyListener() { val EventScope.run by relation<Any?, EventRun>() @Handler fun handle(source: SourceScope, target: TargetScope, event: EventScope) { target.entity.callEvent(event.run.keyId, source = source.entity) } } @AutoScan class EventRunBuilderToRelation : GearyListener() { val TargetScope.run by added<EventRunBuilder>() @Handler fun TargetScope.handle() { entity.setRelation(entity.parseEntity(run.expression).id, EventRun) entity.remove<EventRunBuilder>() } }
5
Kotlin
3
1
179d10613b13dd1df83fe169d1333d8b994d9ec8
1,222
Geary-addons
MIT License
ui_utils/src/main/java/com/artkachenko/ui_utils/views/ClippedLayout.kt
ArtemiyTkachenko
471,678,076
false
{"Kotlin": 267809}
package com.artkachenko.ui_utils.views import android.content.Context import android.util.AttributeSet import android.view.ViewOutlineProvider import android.widget.LinearLayout import androidx.constraintlayout.widget.ConstraintLayout class ClippedLinearLayout @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0) : LinearLayout(context, attributeSet, defStyle) { init { outlineProvider = ViewOutlineProvider.BACKGROUND clipToOutline = true } } class ClippedConstraintLayout @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0) : ConstraintLayout(context, attributeSet, defStyle) { init { outlineProvider = ViewOutlineProvider.BACKGROUND clipChildren = true clipToOutline = true } }
0
Kotlin
0
0
d9042abe218533bbcdbf28f3c87438f2c24b679b
835
CalorieTrackerRefactored
Apache License 2.0
trustagent/src/com/google/android/libraries/car/trustagent/AssociatedCarEntity.kt
google
415,118,653
false
{"Kotlin": 865761, "Java": 244253}
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.trustagent import androidx.room.Entity import androidx.room.PrimaryKey /** * Table entity representing an associated car. * * @property id The unique identifier of the car. * @property encryptionKey The key for encrypting and decrypting data to and from the car. * @property identificationKey The key for identifying an advertisement from an associated device. * @property name A human-readable name of the car. * @property macAddress MAC address of the car. * @property isUserRenamed `true` if the user manually renamed this car. */ @Entity(tableName = "associated_cars") internal data class AssociatedCarEntity( @PrimaryKey val id: String, val encryptionKey: String, val identificationKey: String, val name: String?, val macAddress: String, val isUserRenamed: Boolean ) /** Entity for a car's name in the database. */ internal data class AssociatedCarName(val id: String, val name: String, val isUserRenamed: Boolean) /** Entity for a car's encryption key in the database. */ internal data class AssociatedCarKey(val id: String, val encryptionKey: String) /** Entity for a car's identification key in the database. */ internal data class AssociatedCarIdentificationKey(val id: String, val identificationKey: String)
1
Kotlin
5
18
912fd5cff1f08577d679bfaff9fc0666b8093367
1,874
android-auto-companion-android
Apache License 2.0
src/iii_conventions/MyDate.kt
longlyPaul
114,056,772
true
{"Kotlin": 73652, "Java": 4952}
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int):Comparable<MyDate> { override fun compareTo(other: MyDate): Int { return when{ year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this,other) enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(override val start: MyDate, override val endInclusive: MyDate):ClosedRange<MyDate> ,Iterable<MyDate>{ override fun iterator(): Iterator<MyDate> = object : Iterator<MyDate> { var current: MyDate = start override fun next(): MyDate { val result = current current = current.addTimeIntervals(TimeInterval.DAY, 1) return result } override fun hasNext(): Boolean = current <= endInclusive } override fun contains(d: MyDate):Boolean = start <= d && endInclusive >= d } class DateIterator(val dateRange: DateRange) : Iterator<MyDate> { var current: MyDate = dateRange.start override fun next(): MyDate { val result = current current = current.addTimeIntervals(TimeInterval.DAY, 1) return result } override fun hasNext(): Boolean = current <= dateRange.endInclusive } fun DateRange.step(step:Int):IntProgression{ if (step <= 0) throw IllegalArgumentException("Step must be positive, was: $step") return IntProgression.fromClosedRange(start.dayOfMonth, endInclusive.dayOfMonth, if (step > 0) step else -step) } class RepeatedTimeInterval(val ti: TimeInterval, val n: Int) operator fun MyDate.plus(timeInterval: TimeInterval) = addTimeIntervals(timeInterval,1); operator fun TimeInterval.times(fold:Int) = RepeatedTimeInterval(this,fold) operator fun MyDate.plus(repeatedTimeInterval: RepeatedTimeInterval) = addTimeIntervals(repeatedTimeInterval.ti,repeatedTimeInterval.n)
0
Kotlin
0
0
9f1362a4a3d3875547ddc9579295608110c5c774
2,028
kotlin-koans
MIT License
app/src/main/java/com/example/animconer/data/local/entity/Favorite.kt
brandy-kay
503,192,266
false
{"Kotlin": 115710}
package com.example.animconer.data.local.entity import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "table_favorite") data class Favorite( @PrimaryKey val malId: Int, val title: String?, val image: String?, val rating: String?, val isFavorite: Boolean, )
2
Kotlin
6
16
92ebeb50edb46b5168eadc715e75c1b770c3ccc2
309
AnimCorner
Apache License 2.0
next/kmp/pureCrypto/src/commonMain/kotlin/org/dweb_browser/pure/crypto/hash/SHA256.kt
BioforestChain
594,577,896
false
{"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818}
package org.dweb_browser.pure.crypto.hash expect suspend fun sha256(data: ByteArray): ByteArray expect suspend fun sha256(data: String): ByteArray expect fun sha256Sync(data: ByteArray): ByteArray
66
Kotlin
5
20
6db1137257e38400c87279f4ccf46511752cd45a
198
dweb_browser
MIT License
app/src/main/java/com/ludovic/vimont/mangareader/helper/ViewHelper.kt
1ud0v1c
320,667,207
false
null
package com.ludovic.vimont.mangareader.helper import android.app.Activity import android.graphics.Color import android.view.View import android.view.WindowManager import androidx.core.content.ContextCompat import com.ludovic.vimont.mangareader.R object ViewHelper { fun transparentStatusBar(activity: Activity, isTransparent: Boolean) { if (isTransparent) { activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) activity.window.statusBarColor = Color.TRANSPARENT activity.actionBar?.hide() } else { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { activity.window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_VISIBLE) } else { activity.window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_VISIBLE) } activity.window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) activity.window.statusBarColor = ContextCompat.getColor(activity, R.color.purple_500) activity.actionBar?.show() } } }
0
Kotlin
0
0
e3c0753cbcd34eaf0e64e9bdfe9b620fe293f501
1,352
manga-reader
Apache License 2.0
final_project/app/src/main/java/juliano/correa/final_project/model/Character.kt
Juliano-OC
523,030,629
false
{"Kotlin": 128152, "Java": 2968}
package juliano.correa.final_project.model import java.io.Serializable data class Character( val id: Int, var name: String, var race: String, var age: Int, var gender: String, var primaryWeapon: String, var HP: Double, var MP: Double, var height: Double, var secondaryWeapon: String ): Serializable { override fun toString(): String { return "Character(id=$id, name='$name', race='$race', age=$age, gender='$gender', primaryWeapon='$primaryWeapon', HP=$HP, MP=$MP, Height=$height, secondaryWeapon='$secondaryWeapon')" } }
0
Kotlin
0
0
6e4b95c03998edb825b7fd117dd51a52b6b2b9ec
579
AulasAndroid
MIT License
app/src/main/kotlin/com/hyphenate/chatdemo/common/extensions/internal/ChatOptions.kt
easemob
785,517,709
false
{"Kotlin": 413106, "HTML": 35978, "Makefile": 917}
package com.hyphenate.chatdemo.common.extensions.internal import android.content.Context import android.content.pm.PackageManager import com.hyphenate.easeui.common.ChatOptions /** * Check if set the app key. */ internal fun ChatOptions.checkAppKey(context: Context): Boolean { if (appKey.isNullOrEmpty().not()) { return true } val appPackageName = context.packageName try { context.packageManager.getApplicationInfo(appPackageName, PackageManager.GET_META_DATA)?.let { info -> info.metaData?.getString("EASEMOB_APPKEY")?.let { key -> if (key.isNullOrEmpty().not()) { return true } } } } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return false }
1
Kotlin
4
2
dd157240fa4bf84a0fbcb24c1f133042206210eb
814
easemob-demo-android
Apache License 2.0
src/main/kotlin/net/fabricmc/bot/enums/Channels.kt
FabricMC
272,279,496
false
null
package net.fabricmc.bot.enums /** * An enum representing each type of channel that may be configured, for easier reference. * * @param value A human-readable representation of the given channel. */ enum class Channels(val value: String) { /** The channel used for staff alerts (eg by filters). **/ ALERTS("alerts"), /** The channel intended for running bot commands within. **/ BOT_COMMANDS("bot-commands"), /** The category used for action logging. **/ ACTION_LOG_CATEGORY("action-log"), /** The channel used for staff action logging.. **/ MODERATOR_LOG("moderator-log"), }
20
Kotlin
10
7
16622cffbc0622c6ca461bfb887f39849fa2b935
616
kotlin-fabric-discord-bot
MIT License
src/main/kotlin/org/agoranomic/assessor/lib/proposal/proposal_set/AbstractProposalSet.kt
AgoraNomic
98,589,628
false
{"Kotlin": 1667765, "HTML": 3937}
package org.agoranomic.assessor.lib.proposal.proposal_set import org.agoranomic.assessor.lib.proposal.Proposal import org.agoranomic.assessor.lib.proposal.ProposalDataMismatchException import org.agoranomic.assessor.lib.proposal.ProposalNumbers import org.randomcat.util.requireDistinct abstract class AbstractProposalSet : ProposalSet { companion object { /** * @throws ProposalDataMismatchException if there are two [Proposals][Proposal] in `this` that have the same * [number][Proposal.number] but otherwise different data. */ @JvmStatic protected fun checkInitialList(list: List<Proposal>) { val distinctList = list.distinct() val distinctNumberList = distinctList.distinctBy { it.number } if (distinctList != distinctNumberList) { val differingList = distinctList - distinctNumberList check(differingList.isNotEmpty()) val firstDiffering = differingList.first() val otherWithSameNumber = list.first { it.number == firstDiffering.number && it != firstDiffering } throw ProposalDataMismatchException( next = firstDiffering, original = otherWithSameNumber ) } } } override fun numbers(): ProposalNumbers { val numbersSet = map { it.number }.requireDistinct() return ProposalNumbers(numbersSet) } final override fun equals(other: Any?): Boolean { if (other !is ProposalSet) return false return this.toSet() == other.toSet() } final override fun hashCode(): Int { return this.toSet().hashCode() } override fun toString(): String { return this.toSet().joinToString(separator = ", ", prefix = "[", postfix = "]") } } abstract class AbstractMutableProposalSet : AbstractProposalSet(), MutableProposalSet { /** * Add a proposal, assuming that all necessary checking has already been performed. Will not be called if this * [ProposalSet] already contains the [Proposal]. */ protected abstract fun addUnchecked(toAdd: Proposal) final override fun add(toAdd: Proposal) { if (contains(toAdd.number)) { checkMismatch(toAdd) } else { addUnchecked(toAdd) } } }
0
Kotlin
1
1
85942ee111ea96b938d36079e736eb3d6cee2ceb
2,372
assessor
MIT License
app/src/main/java/app/android/issue5101/LoginFragment.kt
dconeybe
809,895,500
false
{"Kotlin": 39529, "TypeScript": 4030, "JavaScript": 888}
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.android.issue5101 import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.MainThread import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModel import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewModelScope import app.android.issue5101.databinding.FragmentLoginBinding import com.google.firebase.Firebase import com.google.firebase.auth.auth import java.lang.ref.WeakReference import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await class LoginFragment : Fragment(), LoggerNameAndIdProvider { private val logger = Logger("LoginFragment") override val loggerName get() = logger.name override val loggerId get() = logger.id override val loggerNameWithId get() = logger.nameWithId private val weakThis = WeakReference(this) private val viewModel: MyViewModel by viewModels() private var viewBinding: FragmentLoginBinding? = null override fun onAttach(context: Context) { logger.onAttach(context) super.onAttach(context) } override fun onDetach() { logger.onDetach() super.onDetach() } override fun onCreate(savedInstanceState: Bundle?) { logger.onCreate(savedInstanceState) super.onCreate(savedInstanceState) } override fun onDestroy() { logger.onDestroy() weakThis.clear() super.onDestroy() } override fun onViewStateRestored(savedInstanceState: Bundle?) { logger.onViewStateRestored() super.onViewStateRestored(savedInstanceState) } override fun onSaveInstanceState(outState: Bundle) { logger.onSaveInstanceState() super.onSaveInstanceState(outState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { logger.onCreateView() val binding = FragmentLoginBinding.inflate(inflater, container, false).also { viewBinding = it } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { logger.onViewCreated() super.onViewCreated(view, savedInstanceState) viewBinding!!.login.setOnClickListener { handleLoginButtonClick() } if (savedInstanceState === null) { updateUi(viewModel.isLoginInProgress.value) } viewLifecycleOwner.lifecycleScope.launch { viewModel.isLoginInProgress .flowWithLifecycle(viewLifecycleOwner.lifecycle, Lifecycle.State.STARTED) .collect { updateUi(it) } } } override fun onDestroyView() { logger.onDestroyView() viewBinding = null super.onDestroyView() } override fun onStart() { logger.onStart() super.onStart() } override fun onStop() { logger.onStop() super.onStop() } override fun onResume() { logger.onResume() super.onResume() } override fun onPause() { logger.onPause() super.onPause() } @MainThread private fun updateUi(isLoginInProgress: Boolean) { logger.log { "updateUi()" } val loginButton = viewBinding!!.login val spinner = viewBinding!!.spinner if (isLoginInProgress) { loginButton.isEnabled = false spinner.visibility = View.VISIBLE } else { loginButton.isEnabled = true spinner.visibility = View.GONE } } @MainThread private fun handleLoginButtonClick() { logger.log { "handleLoginButtonClick()" } viewModel.login() } class MyViewModel : ViewModel() { private val firebaseAuth = Firebase.auth private val loginJob = MutableStateFlow<Job?>(null) val isLoginInProgress = loginJob .map { it?.isActive ?: false } .stateIn(viewModelScope, SharingStarted.Eagerly, false) @MainThread fun login() { val oldJob = loginJob.value if (oldJob === null || !oldJob.isActive) { viewModelScope .launch { firebaseAuth.signInAnonymously().await() } .also { job -> loginJob.value = job job.invokeOnCompletion { loginJob.compareAndSet(job, null) } } } } } }
0
Kotlin
0
0
e947c92480de2475c6edc204afad2cf5c197eac8
5,067
android-issue-5101
Apache License 2.0
src/main/kotlin/cz/opendatalab/captcha/task/templates/TemplateUtils.kt
opendatalabcz
481,095,558
false
null
package cz.opendatalab.captcha.task.templates import java.util.* object TemplateUtils { fun toBase64Image(dataInBase64: String, imageFormat: String): String { val prefix = "data:image/$imageFormat;base64," return prefix + dataInBase64 } fun toBase64String(bytes: ByteArray): String { return String(Base64.getEncoder().encode(bytes)) } }
0
Kotlin
0
0
ad09e9cef2401a6afa04d073f3cb9ad17fbf77f0
380
czech-captcha
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/CommentOff.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.CommentOff: ImageVector get() { if (_commentOff != null) { return _commentOff!! } _commentOff = fluentIcon(name = "Regular.CommentOff") { fluentPath { moveTo(3.28f, 2.22f) arcToRelative(0.75f, 0.75f, 0.0f, true, false, -1.06f, 1.06f) lineToRelative(0.7f, 0.7f) arcTo(3.24f, 3.24f, 0.0f, false, false, 2.0f, 6.25f) verticalLineToRelative(8.5f) curveTo(2.0f, 16.55f, 3.46f, 18.0f, 5.25f, 18.0f) lineTo(6.0f, 18.0f) verticalLineToRelative(2.75f) arcToRelative(1.25f, 1.25f, 0.0f, false, false, 2.0f, 1.0f) lineTo(13.0f, 18.0f) horizontalLineToRelative(3.93f) lineToRelative(3.78f, 3.78f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.06f, -1.06f) lineTo(3.28f, 2.22f) close() moveTo(15.44f, 16.5f) lineTo(12.5f, 16.5f) lineTo(7.5f, 20.25f) lineTo(7.5f, 16.5f) lineTo(5.25f, 16.5f) curveToRelative(-0.97f, 0.0f, -1.75f, -0.78f, -1.75f, -1.75f) verticalLineToRelative(-8.5f) curveToRelative(0.0f, -0.47f, 0.18f, -0.9f, 0.48f, -1.2f) lineTo(15.44f, 16.5f) close() moveTo(20.5f, 14.75f) curveToRelative(0.0f, 0.7f, -0.4f, 1.3f, -1.0f, 1.58f) lineToRelative(1.1f, 1.1f) arcToRelative(3.25f, 3.25f, 0.0f, false, false, 1.4f, -2.68f) verticalLineToRelative(-8.5f) curveTo(22.0f, 4.45f, 20.54f, 3.0f, 18.75f, 3.0f) lineTo(6.18f, 3.0f) lineToRelative(1.5f, 1.5f) horizontalLineToRelative(11.07f) curveToRelative(0.97f, 0.0f, 1.75f, 0.78f, 1.75f, 1.75f) verticalLineToRelative(8.5f) close() } } return _commentOff!! } private var _commentOff: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,380
compose-fluent-ui
Apache License 2.0
shared/src/commonMain/kotlin/com/drahovac/weatherstationdisplay/viewmodel/SetupState.kt
drahovac
667,016,953
false
null
package com.drahovac.weatherstationdisplay.viewmodel import dev.icerock.moko.resources.StringResource data class SetupState( val value: String? = null, val error: StringResource? = null, )
0
Kotlin
0
0
ac4298318439c6c6cff7ad5630842b86f214d4cb
199
WeatherStationDataDisplay
MIT License
CryptoCrazyComposeApp/app/src/main/java/com/example/cryptocrazycomposeapp/model/CryptoList.kt
dogukandmrl
619,548,857
false
null
package com.example.cryptocrazycomposeapp.model class CryptoList : ArrayList<CryptoListItem>()
0
Kotlin
0
0
5083a861210122adb7072785f6c0a67eaed4b977
95
JetpackComposeSampleApps
MIT License
examples/basics/src/test/kotlin/example/micronaut/basics/events/InMemoryBookEventPublisherTest.kt
test-automation-in-practice
516,747,931
false
{"Kotlin": 178}
package example.micronaut.basics.events import example.micronaut.basics.Examples.record_cleanCode import example.micronaut.basics.Examples.id_cleanCode import example.micronaut.basics.books.core.BookEvent import example.micronaut.basics.books.core.BookRecordCreatedEvent import example.micronaut.basics.books.core.BookRecordDeletedEvent import io.micronaut.context.event.ApplicationEventPublisher import io.mockk.clearMocks import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DynamicTest.dynamicTest import org.junit.jupiter.api.TestFactory internal class InMemoryEventPublisherTest { private val delegate: ApplicationEventPublisher<BookEvent> = mockk(relaxed = true) private val cut = InMemoryEventPublisher(delegate) @BeforeEach fun resetMocks() { clearMocks(delegate) } @TestFactory fun `all book events are simply published as application events`() = listOf( BookRecordCreatedEvent(record_cleanCode), BookRecordDeletedEvent(id_cleanCode) ).map { event -> dynamicTest(event::class.simpleName) { cut.publish(event) verify { delegate.publishEvent(event) } } } }
3
Kotlin
1
2
700e9b171200a71b7880e43b937b21bc05eb33f7
1,222
cnt-micronaut
Apache License 2.0
common/ui/src/main/java/com/him/sama/spotifycompose/common/musicplayer/TabletMusicPlayer.kt
arohim
762,735,266
false
{"Kotlin": 251979}
package com.him.sama.spotifycompose.common.musicplayer import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.LocalMinimumInteractiveComponentEnforcement import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider import androidx.compose.material3.SliderDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil.compose.AsyncImage import com.him.sama.spotifycompose.common.ui.R import com.him.sama.spotifycompose.common.ui.theme.nautral_50 import com.him.sama.spotifycompose.common.ui.theme.unselected_color @OptIn(ExperimentalMaterial3Api::class) @Composable fun TabletPlayer( modifier: Modifier = Modifier, viewModel: MusicPlayerViewModel = hiltViewModel() ) { val viewState by viewModel.viewState.collectAsStateWithLifecycle() Column( modifier = modifier .fillMaxWidth() .padding(horizontal = 16.dp) .padding(bottom = 16.dp), verticalArrangement = Arrangement.Bottom, ) { AsyncImage( modifier = Modifier .height(220.dp) .background( color = Color.LightGray, shape = RoundedCornerShape(8.dp) ) .clip(RoundedCornerShape(8.dp)), model = viewState.selectedItem?.image, contentScale = ContentScale.Crop, contentDescription = null ) Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Column( modifier = Modifier, ) { Text( text = viewState.selectedItem?.title ?: "", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onPrimary ) Text( text = viewState.selectedItem?.description ?: "", style = MaterialTheme.typography.labelLarge, color = unselected_color ) } Icon( modifier = Modifier.size(32.dp), painter = painterResource(id = R.drawable.baseline_favorite_border_24), contentDescription = null, tint = Color.White ) } Spacer(modifier = Modifier.height(24.dp)) CompositionLocalProvider(LocalMinimumInteractiveComponentEnforcement provides false) { Slider( modifier = Modifier.fillMaxWidth(), colors = SliderDefaults.colors( thumbColor = Color.White, inactiveTrackColor = nautral_50, activeTrackColor = Color.White ), valueRange = 0f..100f, value = 50f, onValueChange = {} ) } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "2:47", style = MaterialTheme.typography.labelSmall, color = unselected_color ) Text( text = "-4:07", style = MaterialTheme.typography.labelSmall, color = unselected_color ) } Spacer(modifier = Modifier.height(24.dp)) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Icon( modifier = Modifier.size(48.dp), painter = painterResource(id = R.drawable.baseline_skip_previous_24), contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary ) Icon( modifier = Modifier.size(48.dp), painter = painterResource(id = R.drawable.baseline_play_circle_24), contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary ) Icon( modifier = Modifier.size(48.dp), painter = painterResource(id = R.drawable.baseline_skip_next_24), contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary ) } Spacer(modifier = Modifier.height(24.dp)) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Icon( painter = painterResource(id = R.drawable.baseline_speaker_group_24), contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary ) Spacer(modifier = Modifier.width(8.dp)) Text( text = "Devices available", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onPrimary ) } } }
0
Kotlin
0
0
826694a8a38dc6f53b48e3a337c8bd15a0f8549c
6,487
SpotifyJetpackCompose
Apache License 2.0
app/src/main/java/com/asadmshah/rplace/android/schedulers/SchedulersImpl.kt
asadmshah
94,214,566
false
null
package com.asadmshah.rplace.android.schedulers import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers internal class SchedulersImpl: Schedulers { override fun ui(): Scheduler = AndroidSchedulers.mainThread() override fun io(): Scheduler = io.reactivex.schedulers.Schedulers.io() }
0
Kotlin
0
0
4165eee5e045510ffda80b919838484abe67346e
326
rplace-android
The Unlicense
app/src/main/java/com/example/leetcode/string/reversestring.kt
vaibhavtripathi-bit
781,967,732
false
{"Kotlin": 65079}
package com.example.leetcode.string class reversestring { fun reverseString(s: CharArray): Unit { var left = 0 var right = s.size - 1 while (left < right) { val temp = s[left] s[left] = s[right] s[right] = temp left++ right-- } } fun reverseStringUsingRecursion(s: CharArray): Unit { reverse(s, 0, s.size - 1) } fun reverse(s: CharArray, left: Int, right: Int) { if (left >= right) return val temp = s[left] s[left] = s[right] s[right] = temp reverse(s, left + 1, right - 1) } }
0
Kotlin
0
0
f6ae6d195a794989bf04a6bf47b858f2a5123c8f
646
algorithm
MIT License
app/src/main/java/com/example/bonusapp/database/ReminderDatabase.kt
akinbojo
732,840,757
false
{"Kotlin": 30943}
package com.example.bonusapp.database import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.example.bonusapp.Reminder @Database(entities = [Reminder::class], version=1) @TypeConverters(ReminderTypeConverters::class) abstract class ReminderDatabase : RoomDatabase() { abstract fun reminderDao(): ReminderDao }
0
Kotlin
0
0
05eee081f72325428cb10f5df5c4f0016bcb9f48
371
BonusApp1
Apache License 2.0
src/main/kotlin/com/esop/constant/Constants.kt
AkankshaChaudhari24
619,495,405
false
null
package com.esop.constant val errors = mapOf( "PHONENUMBER_EXISTS" to "User with given phone number already exists.", "USERNAME_EXISTS" to "User with given username already exists", "EMAIL_EXISTS" to "User with given email already exists", "INVALID_EMAIL" to "Email id is not valid", "INVALID_PHONENUMBER" to "Phone number is not valid", "USER_DOES_NOT_EXISTS" to "User not found", "POSITIVE_QUANTITY" to "Quantity must be positive.", "POSITIVE_PRICE" to "Price must be positive.", "INVALID_TYPE" to "Given type doesn't exist.", "NO_ORDERS" to "User does not have any orders", "INVALID_TYPE" to "Type of Esop doesn't exist", "QUANTITY_NOT_ACCEPTED" to "Quantity of ESOPs must be between 0 to 10000", "INVALID_USERNAME" to "Invalid User Name: username can consist only of alphabets, numbers or hyphen(s) and should start with an alphabet.", "WALLET_LIMIT_EXCEEDED" to "Wallet Limit exceeded", "INVENTORY_LIMIT_EXCEEDED" to "Inventory Limit exceeded", "POSITIVE_PLATFORM_FEE" to "Platform fee cannot be less than zero", "INSUFFICIENT_FUNDS" to "Insufficient Funds" ) const val MAX_WALLET_CAPACITY = 10_000_000L const val MAX_INVENTORY_CAPACITY = 10_000_000L const val FEE_PERCENTAGE = 0.02
0
Kotlin
0
0
a0640610e9aca383905b02769ca0a71dd8af101d
1,262
esop-infra-cicd
Apache License 2.0
core/src/main/java/com/rcosteira/core/ui/BaseViewModel.kt
rcosteira79
105,062,893
false
null
package com.rcosteira.core.ui import androidx.lifecycle.ViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelChildren open class BaseViewModel : ViewModel() { private val viewModelJob = SupervisorJob() protected val viewModelScope = CoroutineScope(Dispatchers.Main + viewModelJob) override fun onCleared() { super.onCleared() viewModelScope.coroutineContext.cancelChildren() } }
0
Kotlin
5
34
fbc34905496044a950862aee4dea16abfdad98a0
523
AndroidMultiModuleCleanArchTemplate
Apache License 2.0
suspending/src/commonMain/kotlin/matt/collect/suspending/list/fake/fake.kt
mgroth0
532,378,323
false
{"Kotlin": 201664}
package matt.collect.suspending.list.fake import matt.collect.fake.toFakeMutableList import matt.collect.suspending.SuspendCollection import matt.collect.suspending.SuspendMutableIterator import matt.collect.suspending.fake.SuspendFakeMutableIterator import matt.collect.suspending.fake.SuspendFakeMutableListIterator import matt.collect.suspending.list.SuspendList import matt.collect.suspending.list.SuspendMutableList import matt.collect.suspending.list.SuspendMutableListIterator import matt.collect.suspending.list.toNonSuspendList import matt.lang.common.err fun <E> SuspendList<E>.toSuspendingFakeMutableList() = FakeMutableSuspendList(this) class FakeMutableSuspendList<E>(val list: SuspendList<E>) : SuspendMutableList<E> { override suspend fun add(element: E): Boolean { err("tried to add in ${FakeMutableSuspendList::class.simpleName}") } override suspend fun addAll(elements: SuspendCollection<E>): Boolean { err("tried to addAll in ${FakeMutableSuspendList::class.simpleName}") } override suspend fun clear() { err("tried to clear in ${FakeMutableSuspendList::class.simpleName}") } override suspend fun addAll( index: Int, elements: SuspendCollection<E> ): Boolean { err("tried to modify ${FakeMutableSuspendList::class.simpleName}") } override suspend fun add( index: Int, element: E ) { err("tried to modify ${FakeMutableSuspendList::class.simpleName}") } override suspend fun setAll(c: Collection<E>) { err("tried to modify ${FakeMutableSuspendList::class.simpleName}") } override suspend fun iterator(): SuspendMutableIterator<E> = SuspendFakeMutableIterator(list.iterator()) override suspend fun listIterator(): SuspendMutableListIterator<E> = listIterator(0) override suspend fun listIterator(index: Int): SuspendMutableListIterator<E> = SuspendFakeMutableListIterator(list.listIterator(index)) override suspend fun removeAt(index: Int): E { err("tried to modify ${FakeMutableSuspendList::class.simpleName}") } override suspend fun subList( fromIndexInclusive: Int, toIndexExclusive: Int ): SuspendMutableList<E> = list.subList(fromIndexInclusive, toIndexExclusive).toSuspendingFakeMutableList() override suspend fun get(index: Int): E = list.get(index) override suspend fun lastIndexOf(element: E): Int = list.lastIndexOf(element) override suspend fun indexOf(element: E): Int = list.indexOf(element) override suspend fun size(): Int = list.size() override suspend fun isEmpty(): Boolean = list.isEmpty() override suspend fun toNonSuspendCollection(): MutableList<E> = list.toNonSuspendList().toFakeMutableList() override suspend fun containsAll(elements: SuspendCollection<E>): Boolean = list.containsAll(elements) override suspend fun contains(element: E): Boolean = list.contains(element) override suspend fun set( index: Int, element: E ): E { err("tried to modify ${FakeMutableSuspendList::class.simpleName}") } override suspend fun remove(element: E): Boolean { err("tried to remove in ${FakeMutableSuspendList::class.simpleName}") } override suspend fun removeAll(elements: SuspendCollection<E>): Boolean { err("tried to removeAll in ${FakeMutableSuspendList::class.simpleName}") } override suspend fun retainAll(elements: SuspendCollection<E>): Boolean { err("tried to retainAll in ${FakeMutableSuspendList::class.simpleName}") } }
0
Kotlin
0
0
fa34fe96b8ecd7cd731fd8e40d8ff6ad4951b36a
3,589
collect
MIT License
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/ComponentProperties.kt
ivso0001
314,132,961
true
{"Kotlin": 1610663, "Java": 113787, "Shell": 51}
package org.hexworks.zircon.api.component import org.hexworks.zircon.api.behavior.* /** * This interface contains all the common *properties* that a UI [Component] * can have. */ interface ComponentProperties : CanBeDisabled, CanBeHidden, ThemeOverride, TilesetOverride
0
null
0
0
3c189da12de9da58c5555b2db9dd73af7562b5bf
275
zircon
Apache License 2.0
16.InheritanceOver/main.kt
StevenJokess
383,575,169
true
{"Kotlin": 6110}
import java.util.Arrays open class Master { open fun think () { print("Kotlin Master Class ") } } class Children: Master() { override fun think() { print("Kotlin Children Class") } } fun main(args: Array<String>) { var a = Children() a.think() }
0
null
0
0
bff4f948656b4f814d461b6151b1b787d6b9009c
282
Introduction-to-Kotlin-Programming
MIT License
composeApp/src/androidMain/kotlin/com/br/kmpdemo/compose/widget/forecast/WeatherWidget.kt
BottleRocketStudios
663,198,654
false
{"Kotlin": 238268, "Swift": 168}
package com.br.kmpdemo.compose.widget.forecast import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.glance.GlanceId import androidx.glance.GlanceModifier import androidx.glance.GlanceTheme import androidx.glance.Image import androidx.glance.ImageProvider import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.provideContent import androidx.glance.background import androidx.glance.layout.Alignment import androidx.glance.layout.Column import androidx.glance.layout.Row import androidx.glance.layout.Spacer import androidx.glance.layout.fillMaxSize import androidx.glance.layout.fillMaxWidth import androidx.glance.layout.height import androidx.glance.layout.padding import androidx.glance.layout.size import androidx.glance.preview.ExperimentalGlancePreviewApi import androidx.glance.preview.Preview import androidx.glance.text.FontWeight import androidx.glance.text.Text import androidx.glance.text.TextStyle import com.br.kmpdemo.compose.R import com.br.kmpdemo.compose.previews.previewdata.forecastWidgetPreviewData import com.br.kmpdemo.compose.resources.theme.Dimens import com.br.kmpdemo.compose.resources.theme.KmpDemoGlanceColors import com.br.kmpdemo.repositories.WeatherRepository import org.koin.core.component.KoinComponent import org.koin.core.component.inject /** * A widget that displays the daily weather forecast. */ object WeatherWidget : GlanceAppWidget(), KoinComponent { private val weatherRepo: WeatherRepository by inject() override suspend fun provideGlance(context: Context, id: GlanceId) { provideContent { val widgetState = remember { mutableStateOf<ForecastWidgetState?>(null) } LaunchedEffect(true) { weatherRepo.getDailyForecast(location = "New York City", units = "imperial") .onSuccess { forecast -> widgetState.value = forecast.toWidgetState() } .onFailure { // Show the preview data when the request fails. widgetState.value = forecastWidgetPreviewData } } GlanceTheme(colors = KmpDemoGlanceColors.colors) { Column( modifier = GlanceModifier.fillMaxSize() ) { widgetState.value?.let { ForecastWidget(it) } } } } } } /** * Composable function that creates a Forecast Widget. * * @param state The [ForecastWidgetState] object containing the data for the widget. */ @Composable fun ForecastWidget(state: ForecastWidgetState) { Column( modifier = GlanceModifier .padding(Dimens.grid_1) .fillMaxWidth() .background(GlanceTheme.colors.background), horizontalAlignment = Alignment.CenterHorizontally ) { ForecastWidgetHeader( state.location, state.dailyPrecipitationProbabilityAvg, state.dailyCloudCoverAvg ) Spacer(modifier = GlanceModifier.padding(vertical = Dimens.grid_1)) Row { ForecastWidgetCurrentTemperature(state.currentTemperature, state.dailyTemperatureApparentMin, state.dailyTemperatureApparentMax) Spacer(modifier = GlanceModifier.padding(horizontal = Dimens.grid_1_5)) FutureHourTemperatures(state) } Spacer(modifier = GlanceModifier.height(Dimens.grid_2)) } } @OptIn(ExperimentalGlancePreviewApi::class) @Preview(widthDp = 225, heightDp = 165) @Composable fun ForecastWidgetPreview() { GlanceTheme(colors = KmpDemoGlanceColors.colors) { ForecastWidget( forecastWidgetPreviewData ) } } /** * Composable function to display the header of the Forecast widget. * * @param location The location for which the forecast is displayed. * @param dailyPrecipitationProbabilityAvg The average daily precipitation probability. * @param dailyCloudCoverAvg The average daily cloud cover. */ @Composable private fun ForecastWidgetHeader( location: String, dailyPrecipitationProbabilityAvg: Double, dailyCloudCoverAvg: Double ) { Row( horizontalAlignment = Alignment.CenterHorizontally ) { WeatherIcon( precipitationProbabilityAvg = dailyPrecipitationProbabilityAvg, cloudCoverAvg = dailyCloudCoverAvg, isTitleImage = true ) Spacer(modifier = GlanceModifier.padding(horizontal = Dimens.grid_0_5)) Row { Column( horizontalAlignment = Alignment.End ) { Text( text = location, style = TextStyle( color = GlanceTheme.colors.inverseOnSurface, fontSize = TextUnit(22f, TextUnitType.Sp), fontWeight = FontWeight.Bold ) ) Text( text = when { (dailyPrecipitationProbabilityAvg) >= 50.0 -> "Rainy" (dailyCloudCoverAvg) >= 25.0 -> "Cloudy" else -> "Sunny" }, style = TextStyle( color = GlanceTheme.colors.onBackground, fontSize = TextUnit(10f, TextUnitType.Sp), ) ) } } } } @OptIn(ExperimentalGlancePreviewApi::class) @Preview @Composable private fun ForecastWidgetHeaderPreview() { GlanceTheme(colors = KmpDemoGlanceColors.colors) { ForecastWidgetHeader( forecastWidgetPreviewData.location, forecastWidgetPreviewData.dailyPrecipitationProbabilityAvg, forecastWidgetPreviewData.dailyCloudCoverAvg ) } } /** * Composable function for displaying the current temperature, minimum and maximum apparent temperatures in a column. * * @param currentTemperature The current temperature value. * @param dailyTemperatureApparentMin The minimum apparent temperature value. * @param dailyTemperatureApparentMax The maximum apparent temperature value. */ @Composable private fun ForecastWidgetCurrentTemperature( currentTemperature: Double, dailyTemperatureApparentMin: Double, dailyTemperatureApparentMax: Double, ) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = (currentTemperature).toFahrenheit(), style = TextStyle( color = GlanceTheme.colors.secondary, fontSize = TextUnit(32f, TextUnitType.Sp), fontWeight = FontWeight.Bold ) ) Row { Text( text = (dailyTemperatureApparentMin).toFahrenheit(), style = TextStyle( fontSize = TextUnit(11f, TextUnitType.Sp), color = GlanceTheme.colors.inverseOnSurface ) ) Spacer(modifier = GlanceModifier.padding(horizontal = Dimens.grid_0_5)) Text( text = (dailyTemperatureApparentMax).toFahrenheit(), style = TextStyle( fontSize = TextUnit(11f, TextUnitType.Sp), color = GlanceTheme.colors.inverseOnSurface ) ) } } } @OptIn(ExperimentalGlancePreviewApi::class) @Preview @Composable private fun ForecastWidgetCurrentTemperaturePreview() { GlanceTheme(colors = KmpDemoGlanceColors.colors) { ForecastWidgetCurrentTemperature( forecastWidgetPreviewData.currentTemperature, forecastWidgetPreviewData.dailyTemperatureApparentMin, forecastWidgetPreviewData.dailyTemperatureApparentMax ) } } /** * Composable function to display future hour temperatures. * * @param state The state object containing the forecast data. */ @Composable private fun FutureHourTemperatures(state: ForecastWidgetState) { Row { FutureHourTemperature(1, state.futureTemperature1, state.futurePrecipitationProbability1, state.futureCloudCover1) Spacer(modifier = GlanceModifier.padding(horizontal = Dimens.grid_0_5)) FutureHourTemperature(2, state.futureTemperature2, state.futurePrecipitationProbability2, state.futureCloudCover2) Spacer(modifier = GlanceModifier.padding(horizontal = Dimens.grid_0_5)) FutureHourTemperature(3, state.futureTemperature3, state.futurePrecipitationProbability3, state.futureCloudCover3) } } @OptIn(ExperimentalGlancePreviewApi::class) @Preview @Composable private fun FutureHourTemperaturesPreview() { GlanceTheme(colors = KmpDemoGlanceColors.colors) { FutureHourTemperatures( forecastWidgetPreviewData ) } } /** * Composable to display the temperature, precipitation probability, cloud cover, and hour of day for a future time. * * @param hoursAhead The number of hours in the future for which to display the weather data. * @param futureTemperature The temperature in degrees Fahrenheit. * @param futurePrecipitationProbability The probability of precipitation as a percentage. * @param futureCloudCover The cloud cover as a percentage. */ @Composable private fun FutureHourTemperature( hoursAhead: Long, futureTemperature: Double?, futurePrecipitationProbability: Double, futureCloudCover: Double ) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = futureTemperature.toFahrenheit(), style = TextStyle( color = GlanceTheme.colors.onBackground, fontSize = TextUnit(14f, TextUnitType.Sp), ), ) Spacer(modifier = GlanceModifier.padding(vertical = Dimens.grid_0_25)) WeatherIcon(futurePrecipitationProbability, futureCloudCover) Spacer(modifier = GlanceModifier.padding(vertical = Dimens.grid_0_25)) Text( text = getHourOfDayInAmPmFormat(hoursAhead), style = TextStyle( color = GlanceTheme.colors.onBackground, fontSize = TextUnit(12f, TextUnitType.Sp), ) ) } } @OptIn(ExperimentalGlancePreviewApi::class) @Preview() @Composable fun FutureHourTemperaturePreview() { GlanceTheme(colors = KmpDemoGlanceColors.colors) { FutureHourTemperature( 2, forecastWidgetPreviewData.futureTemperature1, forecastWidgetPreviewData.futurePrecipitationProbability1, forecastWidgetPreviewData.futureCloudCover1 ) } } /** * Composable function to display a weather icon based on precipitation probability and cloud cover. * * @param precipitationProbabilityAvg The average precipitation probability. * @param cloudCoverAvg The average cloud cover. * @param isTitleImage Whether the icon is used as a title image. */ @Composable fun WeatherIcon( precipitationProbabilityAvg: Double, cloudCoverAvg: Double, isTitleImage: Boolean = false ) { Image( provider = when { (precipitationProbabilityAvg) >= 50.0 -> ImageProvider(R.drawable.rain_light) (cloudCoverAvg) >= 25.0 -> ImageProvider(R.drawable.overcast_cloudy) else -> ImageProvider(R.drawable.sunny) }, contentDescription = "", modifier = GlanceModifier.size(if (isTitleImage) Dimens.grid_6 else Dimens.grid_3) ) } /** * The `WeatherWidgetReceiver` class is a subclass of `GlanceAppWidgetReceiver`. * It is responsible for providing the `GlanceAppWidget` instance that will be used to render the weather widget. * */ class WeatherWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget get() = WeatherWidget }
0
Kotlin
1
0
a874592cab80eaa0f1534547250c38cdbf9f69dd
12,196
Kmp-demo
Apache License 2.0
build-logic/src/main/kotlin/extension/Project.kt
NeoUtils
438,508,907
false
{"Kotlin": 9027}
package extension import model.Config import org.gradle.accessors.dm.LibrariesForLibs import org.gradle.api.Project import org.gradle.kotlin.dsl.the val config = Config( app = Config.App( major = 2, minor = 0, patch = 0, phase = Config.Phase.ALPHA ), android = Config.Android( compileSdk = 34, minSdk = 24, targetSdk = 34 ), basePackage = "com.neo.regex" ) val Project.catalog get() = the<LibrariesForLibs>()
1
Kotlin
0
4
3fe6b1fd85b7fd6fa2372dcdcee1a3eacf658166
492
NeoRegex
MIT License
app/src/main/java/com/ahmedtikiwa/fxapp/network/models/NetworkCurrenciesResponse.kt
akitikkx
371,123,034
false
null
package com.ahmedtikiwa.fxapp.network.models import com.google.gson.internal.LinkedTreeMap data class NetworkCurrenciesResponse( val currencies: LinkedTreeMap<String,String> )
0
Kotlin
0
0
a782a5a5f6960b3926e670faa37d8f9b5f4355e1
181
fx-app
MIT License
src/main/kotlin/net/casualuhc/uhc/commands/UHCCommand.kt
CasualUHC
334,382,250
false
null
package net.casualuhc.uhc.commands import com.mojang.brigadier.CommandDispatcher import com.mojang.brigadier.arguments.BoolArgumentType import com.mojang.brigadier.arguments.IntegerArgumentType import com.mojang.brigadier.context.CommandContext import net.casualuhc.arcade.commands.EnumArgument import net.casualuhc.arcade.commands.TimeArgument import net.casualuhc.arcade.commands.TimeZoneArgument import net.casualuhc.arcade.utils.CommandSourceUtils.fail import net.casualuhc.arcade.utils.CommandSourceUtils.success import net.casualuhc.arcade.utils.PlayerUtils import net.casualuhc.arcade.utils.PlayerUtils.isSurvival import net.casualuhc.arcade.utils.PlayerUtils.location import net.casualuhc.arcade.utils.PlayerUtils.teleportTo import net.casualuhc.arcade.utils.TimeUtils import net.casualuhc.uhc.UHCMod import net.casualuhc.uhc.extensions.PlayerFlag import net.casualuhc.uhc.extensions.PlayerFlagsExtension.Companion.flags import net.casualuhc.uhc.extensions.TeamFlag import net.casualuhc.uhc.extensions.TeamFlagsExtension.Companion.flags import net.casualuhc.uhc.util.UHCPlayerUtils.sendUHCResourcePack import net.casualuhc.uhc.managers.TeamManager import net.casualuhc.uhc.resources.UHCResourcePack import net.casualuhc.uhc.resources.UHCResourcePackHost import net.casualuhc.uhc.screen.ItemsScreen import net.casualuhc.uhc.screen.RuleScreen import net.casualuhc.uhc.util.Config import net.casualuhc.uhc.util.Texts import net.casualuhc.uhc.util.UHCPlayerUtils.setForUHC import net.minecraft.commands.CommandSourceStack import net.minecraft.commands.Commands import net.minecraft.commands.arguments.EntityArgument import net.minecraft.commands.arguments.TeamArgument import net.minecraft.network.chat.Component import java.util.concurrent.TimeUnit object UHCCommand: Command { override fun register(dispatcher: CommandDispatcher<CommandSourceStack>) { dispatcher.register( Commands.literal("uhc").requires { it.hasPermission(4) }.then( Commands.literal("team").then( Commands.literal("reload").executes { this.reloadTeams() } ).then( Commands.literal("fakes").then( Commands.literal("spawn").executes { this.spawnFakes() } ).then( Commands.literal("kill").executes { this.killFakes() } ) ).then( Commands.literal("modify").then( Commands.argument("team", TeamArgument.team()).then( Commands.literal("flags").then( Commands.argument("flag", EnumArgument.enumeration<TeamFlag>()).then( Commands.argument("value", BoolArgumentType.bool()).executes(this::setTeamFlag) ) ) ) ) ).then( Commands.literal("get").then( Commands.argument("team", TeamArgument.team()).then( Commands.literal("flags").executes(this::getTeamFlags) ) ) ) ).then( Commands.literal("player").then( Commands.literal("modify").then( Commands.argument("player", EntityArgument.player()).then( Commands.literal("team").then( Commands.argument("team", TeamArgument.team()).then( Commands.argument("teleport", BoolArgumentType.bool()).executes { this.setPlayerTeam(it, false) } ).executes { this.setPlayerTeam(it, true) } ) ).then( Commands.literal("flags").then( Commands.argument("flag", EnumArgument.enumeration<PlayerFlag>()).then( Commands.argument("value", BoolArgumentType.bool()).executes(this::setPlayerFlag) ) ) ) ) ).then( Commands.literal("get").then( Commands.argument("player", EntityArgument.player()).then( Commands.literal("flags").executes(this::getPlayerFlags) ) ) ) ).then( Commands.literal("phase").then( Commands.literal("pause").executes(this::pausePhase) ).then( Commands.literal("unpause").executes(this::unpausePhase) ).executes(this::getPhase) ).then( Commands.literal("setup").executes { UHCMod.minigame.onSetup().run { 1 } } ).then( Commands.literal("lobby").then( Commands.literal("reload") ).then( Commands.literal("delete").executes(this::deleteLobby) ).then( Commands.literal("tp").executes(this::teleportToLobby) ).executes { UHCMod.minigame.onLobby().run { 1 } } ).then( Commands.literal("start").then( Commands.literal("force").executes { UHCMod.minigame.onStart().run { 1 } } ).then( Commands.literal("at").then( Commands.argument("time", TimeArgument.time()).then( Commands.argument("zone", TimeZoneArgument.timeZone()).executes(this::atTime) ) ) ).then( Commands.literal("in").then( Commands.argument("time", IntegerArgumentType.integer(1)).then( Commands.argument("unit", EnumArgument.enumeration(TimeUnit::class.java)).executes(this::inTime) ) ) ).executes { UHCMod.minigame.onReady().run { 1 } } ).then( Commands.literal("finish").executes { UHCMod.minigame.onEnd().run { 1 } } ).then( Commands.literal("settings").executes(this::openSettingsMenu) ).then( Commands.literal("config").then( Commands.literal("reload").executes(this::reloadConfig) ) ).then( Commands.literal("resources").then( Commands.literal("regenerate").executes(this::regenerateResources) ).then( Commands.literal("reload").executes(this::reloadResources) ) ).then( Commands.literal("items").executes(this::openItemsMenu) ) ) } private fun reloadTeams(): Int { TeamManager.createTeams() return 1 } private fun spawnFakes(): Int { return 1 } private fun killFakes(): Int { return 1 } private fun setTeamFlag(context: CommandContext<CommandSourceStack>): Int { val team = TeamArgument.getTeam(context, "team") val flag = EnumArgument.getEnumeration<TeamFlag>(context, "flag") val value = BoolArgumentType.getBool(context, "value") team.flags.set(flag, value) val message = Component.literal("${flag.name} has been set to $value for ").append(team.formattedDisplayName) context.source.success(message, true) return 1 } private fun getTeamFlags(context: CommandContext<CommandSourceStack>): Int { val team = TeamArgument.getTeam(context, "team") val message = team.formattedDisplayName.append(" has the following flags enabled: ${team.flags.get().joinToString()}") context.source.success(message, false) return 1 } private fun setPlayerTeam(context: CommandContext<CommandSourceStack>, bool: Boolean): Int { val target = EntityArgument.getPlayer(context, "player") val team = TeamArgument.getTeam(context, "team") val teleport = bool || BoolArgumentType.getBool(context, "teleport") val server = context.source.server server.scoreboard.addPlayerToTeam(target.scoreboardName, team) target.sendSystemMessage(Texts.UHC_ADDED_TO_TEAM.generate(team.formattedDisplayName)) target.setForUHC(!target.flags.has(PlayerFlag.Participating)) if (teleport) { for (player in PlayerUtils.players()) { if (team.players.contains(player.scoreboardName) && player.isSurvival && target != player) { target.teleportTo(player.location) break } } } val message = Component.literal("${target.scoreboardName} has joined team ") .append(team.formattedDisplayName) .append(" and has ${if (teleport) "been teleported to a random teammate" else "not been teleported"}") context.source.success(message, true) return 1 } private fun setPlayerFlag(context: CommandContext<CommandSourceStack>): Int { val player = EntityArgument.getPlayer(context, "player") val flag = EnumArgument.getEnumeration<PlayerFlag>(context, "flag") val value = BoolArgumentType.getBool(context, "value") player.flags.set(flag, value) val message = Component.literal("${flag.name} has been set to $value for ").append(player.displayName) context.source.success(message, true) return 1 } private fun getPlayerFlags(context: CommandContext<CommandSourceStack>): Int { val player = EntityArgument.getPlayer(context, "player") val message = player.displayName.copy().append(" has the following flags enabled: ${player.flags.get().joinToString()}") context.source.success(message, false) return 1 } private fun pausePhase(context: CommandContext<CommandSourceStack>): Int { if (UHCMod.minigame.paused) { context.source.sendFailure(Component.literal("Current phase was already paused!")) return 0 } UHCMod.minigame.pause() context.source.success(Component.literal("Successfully paused the current phase ${UHCMod.minigame.phase}"), true) return 1 } private fun unpausePhase(context: CommandContext<CommandSourceStack>): Int { if (!UHCMod.minigame.paused) { context.source.sendFailure(Component.literal("Current phase was not paused!")) return 0 } UHCMod.minigame.unpause() context.source.success(Component.literal("Successfully unpaused the current phase ${UHCMod.minigame.phase}"), true) return 1 } private fun getPhase(context: CommandContext<CommandSourceStack>): Int { val paused = "the scheduler is ${if (UHCMod.minigame.paused) "paused" else "running"}" context.source.success(Component.literal("The current phase is ${UHCMod.minigame.phase.id}, $paused"), false) return 1 } private fun atTime(context: CommandContext<CommandSourceStack>): Int { val time = TimeArgument.getTime(context, "time") val zone = TimeZoneArgument.getTimeZone(context, "zone") UHCMod.minigame.setStartTime(TimeUtils.toEpoch(time, zone) * 1_000) context.source.success(Component.literal("Set UHC start time to $time in zone $zone"), true) return 1 } private fun inTime(context: CommandContext<CommandSourceStack>): Int { val time = IntegerArgumentType.getInteger(context, "time") val unit = EnumArgument.getEnumeration<TimeUnit>(context, "unit") UHCMod.minigame.setStartTime(System.currentTimeMillis() + unit.toMillis(time.toLong())) context.source.success(Component.literal("UHC will start in $time ${unit.toChronoUnit()}"), true) return 1 } private fun deleteLobby(context: CommandContext<CommandSourceStack>): Int { UHCMod.minigame.event.getLobbyHandler().getMap().remove() context.source.success(Component.literal("Successfully removed the lobby"), false) return 1 } private fun teleportToLobby(context: CommandContext<CommandSourceStack>): Int { val player = context.source.playerOrException UHCMod.minigame.event.getLobbyHandler().forceTeleport(player) return 1 } private fun openSettingsMenu(context: CommandContext<CommandSourceStack>): Int { val player = context.source.playerOrException player.openMenu(RuleScreen.createScreenFactory(0)) return 1 } private fun reloadConfig(context: CommandContext<CommandSourceStack>): Int { Config.reload() context.source.success(Component.literal("Successfully reloaded config"), true) return 1 } private fun regenerateResources(context: CommandContext<CommandSourceStack>): Int { val success = UHCResourcePack.generate() if (success) { context.source.success(Component.literal("Successfully regenerated resources, reload resources to refresh clients")) return 1 } context.source.fail(Component.literal("Failed to regenerate resources...")) return 0 } private fun reloadResources(context: CommandContext<CommandSourceStack>): Int { val server = context.source.server context.source.success(Component.literal("Reloading resources...")) UHCResourcePackHost.reload().thenRunAsync({ context.source.success(Component.literal("Successfully reloaded resources, resending pack...")) PlayerUtils.forEveryPlayer { it.sendUHCResourcePack() } }, server) return 1 } private fun openItemsMenu(context: CommandContext<CommandSourceStack>): Int { context.source.playerOrException.openMenu(ItemsScreen.createScreenFactory(0)) return 1 } }
0
Kotlin
0
3
3e4645fa33ea24584b0e9cf9c77008fa694f80d5
14,602
UHC-Mod
MIT License
Android/ghvzApp/app/src/androidTest/java/com/app/playhvz/testutils/TestUtil.kt
google
95,704,578
false
null
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.testutils import android.app.Activity import android.app.Instrumentation import androidx.test.espresso.intent.Intents import androidx.test.espresso.intent.matcher.IntentMatchers.isInternal import org.hamcrest.CoreMatchers.not class TestUtil { companion object { /** Sleeps for 1 second. */ fun pauseForDebugging() { Thread.sleep(1000) } /** Sleeps for a very short amount of time. */ fun tacticalWait() { Thread.sleep(50) } fun stubAllExternalIntents() { // Call in @Before // By default Espresso Intents does not stub any Intents. Stubbing needs to be setup before // every test run. In this case all external Intents will be blocked. Intents.intending(not(isInternal())).respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null)) } } }
37
Kotlin
30
24
9e02fb706af61a336bda852f467a35f49bdcfec7
1,512
playhvz
Apache License 2.0
presentation/src/main/java/com/cheise_proj/presentation/viewmodel/message/MessageViewModel.kt
marshall219
249,870,132
true
{"Kotlin": 788935}
package com.cheise_proj.presentation.viewmodel.message import androidx.lifecycle.LiveData import androidx.lifecycle.toLiveData import com.cheise_proj.domain.entity.message.MessageEntity import com.cheise_proj.domain.usecase.message.GetMessageTask import com.cheise_proj.domain.usecase.message.GetSentMessageTask import com.cheise_proj.domain.usecase.message.SendMessageTask import com.cheise_proj.presentation.mapper.message.MessageEntityMapper import com.cheise_proj.presentation.model.message.Message import com.cheise_proj.presentation.model.vo.Resource import com.cheise_proj.presentation.viewmodel.BaseViewModel import io.reactivex.BackpressureStrategy import io.reactivex.Observable import io.reactivex.functions.Function import javax.inject.Inject class MessageViewModel @Inject constructor( private val getMessageTask: GetMessageTask, private val messageEntityMapper: MessageEntityMapper, private val sendMessageTask: SendMessageTask, private val getSentMessageTask: GetSentMessageTask ) : BaseViewModel() { fun getSentMessages(): LiveData<Resource<List<Message>>> { return getSentMessageTask.buildUseCase() .map { t: List<MessageEntity> -> messageEntityMapper.entityToPresentationList(t) } .map { t: List<Message> -> Resource.onSuccess(t) } .startWith(Resource.onLoading()) .onErrorResumeNext( Function { Observable.just(Resource.onError(it.localizedMessage)) } ) .toFlowable(BackpressureStrategy.LATEST) .toLiveData() } fun sendMessage( content: String, receiverName: String?, identifier: String? ): LiveData<Resource<Boolean>> { return sendMessageTask.buildUseCase( sendMessageTask.Params( content, receiverName, identifier ) ) .map { t: Boolean -> Resource.onSuccess(t) } .startWith(Resource.onLoading()) .onErrorResumeNext(Function { Observable.just(Resource.onError(it.localizedMessage)) }) .toFlowable(BackpressureStrategy.LATEST) .toLiveData() } fun getMessages(): LiveData<Resource<List<Message>>> { return getMessageTask.buildUseCase() .map { t: List<MessageEntity> -> messageEntityMapper.entityToPresentationList(t) } .map { t: List<Message> -> Resource.onSuccess(t) } .startWith(Resource.onLoading()) .onErrorResumeNext( Function { Observable.just(Resource.onError(it.localizedMessage)) } ) .toFlowable(BackpressureStrategy.LATEST) .toLiveData() } fun getMessage(identifier: Int): LiveData<Resource<Message>> { return getMessageTask.buildUseCase(identifier).map { t: List<MessageEntity> -> messageEntityMapper.entityToPresentationList(t)[0] }.map { t: Message -> Resource.onSuccess(t) } .startWith(Resource.onLoading()) .onErrorResumeNext( Function { Observable.just(Resource.onError(it.localizedMessage)) } ) .toFlowable(BackpressureStrategy.LATEST) .toLiveData() } }
0
null
0
0
0183ab6165a42be83691dd7281efc6d738ebe88c
3,386
Nagies-Edu-Center
Apache License 2.0
composeApp/src/commonMain/kotlin/App.kt
joshuaschori
833,395,858
false
{"Kotlin": 169079, "Swift": 594, "HTML": 336, "CSS": 102}
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Dehaze import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import classes.Guitar import com.russhwolf.settings.ExperimentalSettingsApi import com.russhwolf.settings.Settings import kotlinx.coroutines.launch import kotlinx.serialization.ExperimentalSerializationApi import ui.theme.AppTheme const val insetHorizontal = 24f const val insetVertical = 24f val settings: Settings = Settings() @OptIn(ExperimentalMaterial3Api::class, ExperimentalSerializationApi::class, ExperimentalSettingsApi::class ) @Composable fun App() { var navigationState: String by remember { mutableStateOf(settings.getString("startScreen", "Home")) } var currentGuitar: Guitar by remember { mutableStateOf(Guitar(isDefaultGuitar = true)) } AppTheme { val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) val coroutineScope = rememberCoroutineScope() ModalNavigationDrawer( drawerState = drawerState, drawerContent = { ModalDrawerSheet { Text("Magnum Opus", modifier = Modifier.padding(16.dp)) HorizontalDivider() NavigationDrawerItem( label = { Text(text = "Home") }, selected = false, onClick = { navigationState = "Home" coroutineScope.launch { drawerState.apply { if (isOpen) close() } } } ) NavigationDrawerItem( label = { Text(text = "Chord Identification") }, selected = false, onClick = { navigationState = "Chord Identification" coroutineScope.launch { drawerState.apply { if (isOpen) close() } } } ) NavigationDrawerItem( label = { Text(text = "Interval Display") }, selected = false, onClick = { navigationState = "Interval Display" coroutineScope.launch { drawerState.apply { if (isOpen) close() } } } ) NavigationDrawerItem( label = { Text(text = "Settings") }, selected = false, onClick = { navigationState = "Settings" coroutineScope.launch { drawerState.apply { if (isOpen) close() } } } ) } }, gesturesEnabled = drawerState.isOpen ) { Scaffold( topBar = { // TODO finish top app bar TopAppBar( actions = { Column { Text( "Tuning:", fontSize = 16.sp, modifier = Modifier .padding(top = (insetVertical / 2).dp, end = insetHorizontal.dp) ) Text( currentGuitar.currentTuningNoteNames.joinToString(" "), fontSize = 14.sp, modifier = Modifier .widthIn(150.dp) .heightIn(40.dp) ) } /* IconButton(onClick = { /* do something */ }) { Icon(Icons.Filled.MusicNote, contentDescription = "Localized description") } */ }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), navigationIcon = { IconButton( onClick = { coroutineScope.launch { drawerState.apply { if (isClosed) open() else close() } } } ) { Icon(Icons.Filled.Dehaze, contentDescription = "Menu") } }, title = { Text(navigationState) }, ) }, /* // TODO finish bottom bar bottomBar = { BottomAppBar( actions = { IconButton(onClick = { /* do something */ }) { Icon( Icons.Filled.Star, contentDescription = "Localized description", ) } }, floatingActionButton = { FloatingActionButton( onClick = { /* do something */ }, containerColor = BottomAppBarDefaults.bottomAppBarFabColor, elevation = FloatingActionButtonDefaults.bottomAppBarFabElevation() ) { Icon(Icons.Filled.Refresh, "Localized description") } } ) } */ ) { innerPadding -> // content on screen Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally, ) { when (navigationState) { "Interval Display" -> IntervalDisplay( navigationState = navigationState, innerPadding = innerPadding, currentGuitar = currentGuitar, onGuitarChange = { currentGuitar = it } ) "Chord Identification" -> ChordIdentification( navigationState = navigationState, innerPadding = innerPadding, currentGuitar = currentGuitar, onGuitarChange = { currentGuitar = it } ) "Home" -> Home( navigationState = navigationState, innerPadding = innerPadding ) "Settings" -> Settings( innerPadding = innerPadding, currentGuitar = currentGuitar, onGuitarChange = { currentGuitar = it } ) } } } } } }
0
Kotlin
0
2
c2298b4c4f638edb2ee582fa17af2242c268c55a
9,927
MagnumOpus
MIT License
complete/src/test/kotlin/example/micronaut/HelloControllerSpec.kt
croudet
271,086,122
true
{"Kotlin": 2204, "Shell": 699, "Dockerfile": 128}
package example.micronaut import io.micronaut.context.ApplicationContext import io.micronaut.http.client.HttpClient import io.micronaut.runtime.server.EmbeddedServer import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals object HelloControllerSpec : Spek({ describe("HelloController Suite") { val embeddedServer: EmbeddedServer = ApplicationContext.run(EmbeddedServer::class.java) // <1> val client: HttpClient = HttpClient.create(embeddedServer.url) // <2> it("test /hello responds Hello World") { val rsp: String = client.toBlocking().retrieve("/hello/you") assertEquals("""{"firstName":"you","lastName":"LastName"}""", rsp) } afterGroup { client.close() embeddedServer.close() } } })
0
null
0
0
31ee2e5de4f89c2993d925f48fd1d6a85d51e887
868
creating-your-first-micronaut-app-kotlin
Apache License 2.0
src/main/kotlin/it/scoppelletti/spaceship/ApplicationException.kt
dscoppelletti
263,568,278
false
null
/* * Copyright (C) 2008-2018 Dario Scoppelletti, <http://www.scoppelletti.it/>. * * 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("unused") package it.scoppelletti.spaceship import it.scoppelletti.spaceship.i18n.MessageSpec import it.scoppelletti.spaceship.types.StringExt /** * Application exception. * * @since 1.0.0 * * @property messageSpec Message specification. */ public class ApplicationException constructor( @Suppress("WeakerAccess") public val messageSpec: MessageSpec, override val cause: Throwable? = null ) : RuntimeException() { @Suppress("RedundantNullableReturnType") override val message: String? get() = toString() override fun toString(): String = "ApplicationException($messageSpec)" } /** * Returns the message of an exception. * * The message is obtained by the following fallbacks: * * 1. The `localizedMessage` property of the exception object. * 1. The `message` property of the exception object. * 1. The fully qualified name of the exception class. * * @receiver An exception. * @return The message. * @since 1.0.0 */ public fun Throwable?.toMessage(): String { if (this == null) { return "null" } var msg: String? = this.localizedMessage if (!msg.isNullOrBlank()) { return msg } msg = this.message if (!msg.isNullOrBlank()) { return msg } msg = this.toString() if (!msg.isNullOrBlank()) { return msg } return StringExt.EMPTY }
0
Kotlin
0
0
be5079769d9846871b9fcfade047a0f808a233c9
2,044
spaceship-stdlib
Apache License 2.0
sample/src/main/java/com/juul/pommel/sample/EnglishNameProvider.kt
JuulLabs
281,788,612
false
null
package com.juul.pommel.sample import com.juul.pommel.annotations.SoloModule import dagger.hilt.components.SingletonComponent import javax.inject.Inject import javax.inject.Named @SoloModule(installIn = SingletonComponent::class, bindingClass = NameProvider::class) @Named("NameProvider") class EnglishNameProvider @Inject constructor() : NameProvider { override fun name(): String { return "Pommel" } }
1
Kotlin
2
21
73d94b064a3322aa31dc48e57c6d20114be671bf
423
pommel
Apache License 2.0
src/main/kotlin/org/tty/dailyset/dailyset_cloud/bean/UserState.kt
h1542462994
482,193,075
false
null
/** * create at 2022/4/16 * @author h1542462994 */ @file:Suppress("OPT_IN_IS_NOT_ENABLED") package org.tty.dailyset.dailyset_cloud.bean import org.tty.dailyset.dailyset_cloud.bean.entity.User import org.tty.dailyset.dailyset_cloud.bean.entity.UserActivity import org.tty.dailyset.dailyset_cloud.bean.resp.UserStateResp import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract data class UserState( val user: User?, val userActivity: UserActivity?, val token: String?, ) @OptIn(ExperimentalContracts::class) fun UserState?.isActive(): Boolean { contract { returns(true) implies (this@isActive != null ) } return this != null && user != null && userActivity != null } fun UserState?.castToUserStateResp(): UserStateResp { val user = this!!.user!! val userActivity = this.userActivity!! return UserStateResp( uid = user.uid, nickname = user.nickname, email = user.email, portraitId = user.portraitId, deviceCode = userActivity.deviceCode, deviceName = userActivity.deviceName, platformCode = userActivity.platformCode, state = userActivity.state, lastActive = userActivity.lastActive, token = this.token!! ) }
0
Kotlin
0
0
e3fe192c227da0c0a7c18c8bf3a2cd42a0de4e14
1,268
dailyset_cloud
MIT License
server/src/main/kotlin/io/liftgate/server/autoscale/AutoScaleTemplate.kt
liftgate
525,014,392
false
{"Kotlin": 63446}
package io.liftgate.server.autoscale import kotlinx.serialization.Serializable /** * @author GrowlyX * @since 8/16/2022 */ @Serializable data class AutoScaleTemplate( val group: String, val template: String, val scaleUpMax: Int, val minimumReplicas: Int, val autoStart: Boolean, val availabilityStrategy: String, val propertyChoiceScheme: String, val desiredMetricRatio: Double = 50.0, val metricRatioThreshold: Double = 10.0, ) { var startedAutoScale = false }
0
Kotlin
0
5
c0f8c00008d2cb35c0da9b940ed299f6548588f6
507
liftgate
MIT License
app/src/main/java/io/aethibo/pxlart/data/remote/api/ApiService.kt
primepixel
320,511,148
false
null
package io.aethibo.pxlart.data.remote.api import io.aethibo.pxlart.domain.MainResponse import io.aethibo.pxlart.framework.utils.AppConst import retrofit2.http.GET import retrofit2.http.Query import retrofit2.http.QueryMap /** * Service to fetch Pexels posts using end point [AppConst.baseUrl]. */ interface ApiService { /** * @param [page] by API is defaulted to 1, so it can be omitted * @param [per_page] by API is defaulted to 15, so it can be omitted * * We kept them here for clarity. * * As you can see we have two different query handlings for our API calls. * Which you use is totally up to you since either does the job. * @param Query is only taking single parameter, this is in case you want to clearly * see within your calls what is each of the parameters passed in * * @param QueryMap as the name says will take a map of items which is defined elsewhere. * QueryMaps are quite good if you have a lot of calls that take several query * parameters, so the code is bit more concise. * * In our example app, we'll use both so you can see their usage. */ @GET(AppConst.searchPhotos) suspend fun searchPhotos( @Query("page") page: Int, @Query("per_page") perPage: Int, @Query("query") query: String ): MainResponse @GET(AppConst.curatedPhotos) suspend fun getCuratedPhotos(@QueryMap params: Map<String, Int>): MainResponse }
0
Kotlin
0
1
a36917702368d1cb83ce576fa02d007eb60085de
1,479
PxlArt
Apache License 2.0
src/geometry/Vector2D.kt
Pantonshire
132,039,170
false
null
package geometry class Vector2D(var x: Double = 0.0, var y: Double = 0.0) { constructor(angle: Angle, magnitude: Double = 1.0): this(magnitude * angle.cos(), magnitude * angle.sin()) fun set(newX: Double = 0.0, newY: Double = 0.0): Vector2D { x = newX y = newX return this } fun set(angle: Angle, magnitude: Double = 1.0): Vector2D { x = magnitude * angle.cos() y = magnitude * angle.sin() return this } fun magnitude(): Double = Math.sqrt(x * x + y * y) fun angle(): Angle = Angle(Math.atan2(y, x)) fun floored(): Vector2D = Vector2D(Math.floor(x), Math.floor(y)) fun floor(): Vector2D { x = Math.floor(x) y = Math.floor(y) return this } fun rounded(): Vector2D = Vector2D(Math.round(x).toDouble(), Math.round(y).toDouble()) fun round(): Vector2D { x = Math.round(x).toDouble() y = Math.round(y).toDouble() return this } infix fun dotP(other: Vector2D): Double = x * other.x + y * other.y fun angleBetween(other: Vector2D): Angle = Angle(Math.acos((this dotP other) / (magnitude() * other.magnitude()))) operator fun plus(other: Vector2D): Vector2D = Vector2D(x + other.x, y + other.y) operator fun minus(other: Vector2D): Vector2D = Vector2D(x - other.x, y - other.y) operator fun times(scale: Double): Vector2D = Vector2D(x * scale, y * scale) operator fun div(denominator: Double): Vector2D = Vector2D(x / denominator, y / denominator) operator fun plusAssign(other: Vector2D) { x += other.x y += other.y } operator fun minusAssign(other: Vector2D) { x -= other.x y -= other.y } operator fun timesAssign(scale: Double) { x *= scale y *= scale } operator fun divAssign(denominator: Double) { x /= denominator y /= denominator } }
0
Kotlin
0
0
36c3f3ad956d7bb58ac5e368cd80c42d3f8f40d4
2,071
TomsLib
MIT License
HelloworldGwk/app/src/main/java/com/gwk/helloworldgwk/todpapp/data/source/local/ToDoDatabase.kt
cn-ansonkai
159,456,863
false
null
package com.gwk.helloworldgwk.todpapp.data.source.local import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.content.Context abstract class ToDoDatabase: RoomDatabase() { abstract fun taskDao(): TasksDao companion object { private var INSTANCE: ToDoDatabase? = null private val lock = Any() fun getInstance(context: Context): ToDoDatabase { synchronized(lock) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.applicationContext, ToDoDatabase::class.java, "Tasks.db") .build() } return INSTANCE!! } } } }
0
Kotlin
0
0
a4edbf715df58b829a7e7d178593dcb569c511f5
766
mobileomcapp_repo
Apache License 2.0
navigation/src/main/java/com/vkondrav/ram/navigation/KoinModule.kt
vkondrav
481,052,423
false
null
package com.vkondrav.ram.navigation import com.vkondrav.ram.common.util.FlowWrapper import com.vkondrav.ram.navigation.usecase.fetchAppBarStateUseCase import com.vkondrav.ram.navigation.usecase.handleNavigationCommandsUseCase import com.vkondrav.ram.navigation.usecase.navigateToRouteUseCase import com.vkondrav.ram.navigation.usecase.navigateUpUseCase import org.koin.dsl.module val navigationModule = module { factory { fetchAppBarStateUseCase( navigator = get(), ) } factory { navigateToRouteUseCase( navigator = get(), ) } factory { navigateUpUseCase( navigator = get(), ) } factory { handleNavigationCommandsUseCase( navigator = get(), ) } single { Navigator( flowWrapper = FlowWrapper(), ) } }
0
Kotlin
1
0
78c466563652800d8001a58504a533b764507461
882
rick_and_morty_compose
MIT License
day8/src/main/kotlin/com/nohex/aoc/day8/Solution.kt
mnohe
433,396,563
false
{"Kotlin": 105740}
package com.nohex.aoc.day8 import com.nohex.aoc.PuzzleInput fun main() { val uniqueDigitCount = getUniqueDigitCount(getInput("input.txt")) println("day8, part 1: $uniqueDigitCount") val allDigitSum = getDigitSum(getInput("input.txt")) println("day8, part 2: $allDigitSum") } fun getInput(path: String) = // Read the input. PuzzleInput(path) // Get each line. .asSequence() fun getUniqueDigitCount(entries: Sequence<String>) = entries // Parse as digit information. .map { DigitData(it) } .flatMap { it.digits } // Count if the segments match those for: // 1 -> 2 segments // 4 -> 4 segments // 7 -> 3 segments // 8 -> 7 segments .count { it.segmentCount in arrayOf(2, 3, 4, 7) } fun getDigitSum(entries: Sequence<String>) = entries .map { DigitData(it) } .sumOf { it.decodedNumber }
0
Kotlin
0
0
4d7363c00252b5668c7e3002bb5d75145af91c23
924
advent_of_code_2021
MIT License
app/src/main/java/pe/fernan/animals/breeds/MainActivity.kt
FernanApps
703,755,259
false
{"Kotlin": 116913}
package pe.fernan.animals.breeds import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import pe.fernan.ui.AppNavigator import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppNavigator() } } }
0
Kotlin
0
0
4a65d349ee9d2c5ef2bc815a28c843cbd2b632d0
453
AnimalBreeds
MIT License
PuzzleGames/app/src/main/java/com/malkinfo/puzzlegames/TouchListener.kt
shnartho
472,117,984
false
{"Java": 83802, "Kotlin": 30097, "HTML": 6552, "JavaScript": 5252, "CSS": 3780}
package com.malkinfo.puzzlegames import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import android.view.ViewGroup import android.widget.RelativeLayout class TouchListener(private val activity: PuzzleActivity) : OnTouchListener { private var xDelta = 0f private var yDelta = 0f override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { val x = motionEvent.rawX val y = motionEvent.rawY val tolerance = Math.sqrt( Math.pow(view.width.toDouble(), 2.0) + Math.pow( view.height.toDouble(), 2.0 ) ) / 10 val piece = view as PuzzlePiece if (!piece.canMove) { return true } val lParams = view.getLayoutParams() as RelativeLayout.LayoutParams when (motionEvent.action and MotionEvent.ACTION_MASK) { MotionEvent.ACTION_DOWN -> { xDelta = x - lParams.leftMargin yDelta = y - lParams.topMargin piece.bringToFront() } MotionEvent.ACTION_MOVE -> { lParams.leftMargin = (x - xDelta).toInt() lParams.topMargin = (y - yDelta).toInt() view.setLayoutParams(lParams) } MotionEvent.ACTION_UP -> { val xDiff = StrictMath.abs(piece.xCoord - lParams.leftMargin) val yDiff = StrictMath.abs(piece.yCoord - lParams.topMargin) if (xDiff <= tolerance && yDiff <= tolerance) { lParams.leftMargin = piece.xCoord lParams.topMargin = piece.yCoord piece.layoutParams = lParams piece.canMove = false sendViewToBack(piece) activity.checkGameOver() } } } return true } fun sendViewToBack(child: View) { val parent = child.parent as ViewGroup if (null != parent) { parent.removeView(child) parent.addView(child, 0) } } }
1
null
1
1
8d986cd2aa40e0dbe51e824e7a75d1c4138fd82f
2,125
Programming-Multimedia-Applications
MIT License
railway-oriented-validation-kt/src/test/kotlin/ga/overfullstack/app/imperative/ImperativeValidation2Test.kt
overfullstack
762,260,590
false
{"Gradle Kotlin DSL": 11, "JSON": 1, "INI": 3, "TOML": 1, "Ignore List": 1, "EditorConfig": 1, "Markdown": 5, "XML": 23, "Kotlin": 27, "YAML": 1, "Java": 34}
/* gakshintala created on 4/13/20 */ package app.imperative import app.common.eggCarton import app.common.expectedImperativeValidationResults import io.github.oshai.kotlinlogging.KotlinLogging import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class ImperativeValidation2Test { @Test fun `Octopus Orchestrator`() { val badEggFailureBucketMap = validateEggCartonImperatively2( eggCarton.toMutableList() ) // sending a copy, a the iterator is common logger.info { badEggFailureBucketMap } Assertions.assertEquals(expectedImperativeValidationResults, badEggFailureBucketMap) } private val logger = KotlinLogging.logger {} }
1
Java
0
1
95ab9896f1f5f1122555ff94310111e7e7fe64e7
687
fcwfp-root
MIT License
plugin-common/src/test/kotlin/ru/itbasis/jvmwrapper/core/vendor/JvmVendorTest.kt
itbasis
143,887,823
false
null
package ru.itbasis.jvmwrapper.core.vendor import io.kotlintest.data.forall import io.kotlintest.shouldBe import io.kotlintest.shouldThrow import io.kotlintest.specs.FunSpec import io.kotlintest.tables.row import ru.itbasis.jvmwrapper.core.jvm.JvmVendor.ORACLE import ru.itbasis.jvmwrapper.core.jvm.toJvmVendor import samples.JvmVersionSamples import samples.asKotlinTestRows internal class JvmVendorTest : FunSpec({ test("Successful parsing of vendors") { forall( row("oracle", ORACLE), row("Oracle", ORACLE), row("Oracle Corporation", ORACLE) ) { value, expected -> value.toJvmVendor() shouldBe expected } } test("Successful parsing of vendors - 2") { forall( rows = *JvmVersionSamples.asKotlinTestRows() ) { (vendor) -> vendor.toJvmVendor().code shouldBe vendor } } test("Unsuccessful parsing of vendors") { forall( row("oracle "), row("o") ) { value -> shouldThrow<IllegalArgumentException> { value.toJvmVendor() } } } })
8
Kotlin
0
2
c9066a0147d979b66175ae8decf82307dea7f69d
978
jvm-wrapper-ide-plugins
MIT License
app/src/main/java/com/koleff/kare_android/ui/compose/dialogs/BaseDialogs.kt
MartinKoleff
741,013,199
false
{"Kotlin": 1413112}
package com.koleff.kare_android.ui.compose.dialogs import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme 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.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.window.DialogProperties @Composable fun WarningDialog( title: String, description: String, onDismiss: () -> Unit, onClick: () -> Unit, positiveButtonTitle: String, negativeButtonTitle: String = "Cancel", callDismissOnConfirm: Boolean = true ) { val buttonColor = MaterialTheme.colorScheme.tertiary val onButtonColor = MaterialTheme.colorScheme.onTertiary val titleTextColor = MaterialTheme.colorScheme.onSurface val titleTextStyle = MaterialTheme.typography.headlineMedium.copy( color = titleTextColor ) val textColor = MaterialTheme.colorScheme.onSurface val textStyle = MaterialTheme.typography.titleMedium.copy( color = textColor ) val buttonTextStyle = MaterialTheme.typography.titleSmall.copy( color = textColor ) AlertDialog( title = { Box( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp), contentAlignment = Alignment.Center ) { Text( text = title, style = titleTextStyle, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis ) } }, text = { Text( text = description, style = textStyle, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis ) }, confirmButton = { Button( onClick = { onClick() if (callDismissOnConfirm) onDismiss() }, colors = ButtonDefaults.buttonColors( containerColor = buttonColor, contentColor = onButtonColor ) ) { Text( text = positiveButtonTitle, style = buttonTextStyle, textAlign = TextAlign.Start, maxLines = 1, overflow = TextOverflow.Ellipsis ) } }, dismissButton = { Button( onClick = onDismiss, colors = ButtonDefaults.buttonColors( containerColor = buttonColor, contentColor = onButtonColor ) ) { Text( text = negativeButtonTitle, style = buttonTextStyle, textAlign = TextAlign.End, maxLines = 1, overflow = TextOverflow.Ellipsis ) } }, onDismissRequest = { onDismiss() }, properties = DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true) ) }
23
Kotlin
0
4
4ad6b9f320ff60e05b453375b9b855bd3e4a3483
3,667
KareFitnessApp
MIT License
src/typingAnimation/Typing.kt
jdvalenzuelah
219,055,480
false
null
@file:JsModule("react-typing-animation") @file:JsNonModule package typingAnimation import react.* @JsName("default") external val Typing: RClass<TypingProps> external interface TypingProps: RProps { var className: String var children: ReactElement var onFinishedTyping: () -> Unit var onBeforeType: () -> Unit var startDelay: Int var cursor: ReactElement }
0
Kotlin
0
0
9203a306f7748f51794e1818dd93c4b8bc692f54
385
portafolio
MIT License
app/src/main/java/com/hypertrack/android/models/MeasurementUnits.kt
hypertrack
241,723,736
false
null
package com.hypertrack.android.models sealed class MeasurementUnits object Unspecified : MeasurementUnits() object Imperial : MeasurementUnits() object Metric : MeasurementUnits()
1
Kotlin
17
31
c5dd23621aed11ff188cf98ac037b67f435e9f5b
181
visits-android
MIT License
src/main/kotlin/org/ocpp/server/entities/image/ImageRepository.kt
NLCProject
497,246,900
false
null
package org.ocpp.server.entities.image import org.isc.utils.genericCrudl.services.RepositoryService import org.isc.utils.models.CurrentUser import org.ocpp.server.entities.image.interfaces.IImageRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class ImageRepository @Autowired constructor( private val repository: IImageRepository ) : RepositoryService<ImageEntity>(repository = repository) { /** * Find thumbnail by its ID. * * @param id . * @return Byte array of thumbnail. May be null. */ fun findThumbnail(id: String, currentUser: CurrentUser): String? { val optional = repository.findThumbnailById(id = id) if (optional.isPresent) return String(optional.get()) return null } }
0
Kotlin
0
0
8014bacd913760ea2d58e9a29006ad248c449728
842
OcppServer
ISC License
app/src/main/java/com/patel/programmingzone/pythontheory/ExercisePy.kt
lalit-patel
456,964,451
false
{"Kotlin": 44875}
package com.patel.programmingzone.pythontheory import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import com.patel.programmingzone.adapter.CustomAdapter import android.os.Bundle import android.view.View import android.widget.Toast import com.patel.programmingzone.R import androidx.recyclerview.widget.LinearLayoutManager class ExercisePy : AppCompatActivity() { var recyclerView: RecyclerView? = null var customAdapter: CustomAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.exerciselist) recyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView recyclerView!!.setHasFixedSize(true) val title = arrayOf( "Guessing Game","Rock, Paper Scissor Game" ) val htmlfiles = arrayOf( "Python/PythonExercise/ex01", "Python/PythonExercise/ex02" ) customAdapter = CustomAdapter(this, title, htmlfiles) recyclerView!!.layoutManager = LinearLayoutManager(this) recyclerView!!.adapter = customAdapter } }
0
Kotlin
0
0
4d249af0d39b55487817068c01dda57415635606
1,173
Programming-Zone
MIT License
app/src/main/java/com/exorabeveragefsm/features/document/api/DocumentRepoProvider.kt
DebashisINT
614,840,078
false
null
package com.exorabeveragefsm.features.document.api import com.exorabeveragefsm.features.dymanicSection.api.DynamicApi import com.exorabeveragefsm.features.dymanicSection.api.DynamicRepo object DocumentRepoProvider { fun documentRepoProvider(): DocumentRepo { return DocumentRepo(DocumentApi.create()) } fun documentRepoProviderMultipart(): DocumentRepo { return DocumentRepo(DocumentApi.createImage()) } }
0
Kotlin
0
0
11801c2d74a940c23e66b51cf53fec14b1a8560b
440
ExoraBeverage
Apache License 2.0
3.3/LR_3_8+/app/src/main/java/ru/samsung/itschool/myapplication/Main2Activity.kt
Purpurum
580,288,282
false
null
package ru.samsung.itschool.myapplication import android.os.Bundle import android.view.Menu import android.widget.Toast import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import com.google.android.material.navigation.NavigationView import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.navigation.Navigation class Main2Activity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val fab: FloatingActionButton = findViewById(R.id.fab) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) val navView: NavigationView = findViewById(R.id.nav_view) val navController = findNavController(R.id.nav_host_fragment2) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow ), drawerLayout ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) // получаем переданное из предыдущих UI значение arg1 val str=intent.getStringExtra("arg1") Toast.makeText(this,str, Toast.LENGTH_LONG).show() // отправка данных обратно вызывающему navController.previousBackStackEntry?.savedStateHandle?.set("result_from_activity", "ответ на:"+str) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main2, menu) return true } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
0
Kotlin
0
0
cbb31dfec9eaf0169a12fa7368632138661ae034
2,755
MD-NARFU
MIT License
desktop/views/src/test/kotlin/prose/proseEditor/Prose Editor Text Area Unit Test.kt
Soyle-Productions
239,407,827
false
null
package com.soyle.stories.prose.proseEditor import javafx.scene.Scene import javafx.scene.input.KeyCode import javafx.scene.layout.VBox import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.testfx.api.FxRobot import org.testfx.api.FxToolkit class `Prose Editor Text Area Unit Test` : FxRobot() { private val textArea = ProseEditorTextArea() init { FxToolkit.registerPrimaryStage().apply { interact { scene = Scene(VBox(textArea)) width = 300.0 height = 300.0 show() } } } @Test fun `contiguous basic text should collapse`() { interact { repeat(5) { textArea.append(BasicText("text $it "), listOf()) } } assertEquals(1, textArea.paragraphs.size) assertEquals("text 0 text 1 text 2 text 3 text 4 ", textArea.text) assertEquals(1, textArea.paragraphs.flatMap { it.segments }.size) } @Test fun `basic text with newline should be split into paragraphs`() { interact { repeat(5) { textArea.appendText("text\n $it ") } } assertEquals("text\n 0 text\n 1 text\n 2 text\n 3 text\n 4 ", textArea.text) assertEquals(6, textArea.paragraphs.size) assertEquals(listOf( BasicText("text\n"), BasicText(" 0 text\n"), BasicText(" 1 text\n"), BasicText(" 2 text\n"), BasicText(" 3 text\n"), BasicText(" 4 ") ), textArea.paragraphs.flatMap { it.segments }) } @Test fun `typed newline characters create new paragraphs`() { interact { textArea.requestFocus() type(KeyCode.A, KeyCode.B, KeyCode.ENTER, KeyCode.C, KeyCode.D, KeyCode.ENTER, KeyCode.E) } assertEquals(3, textArea.paragraphs.size) assertEquals("ab\ncd\ne", textArea.text) assertEquals(listOf( BasicText("ab\n"), BasicText("cd\n"), BasicText("e") ), textArea.paragraphs.flatMap { it.segments }) } }
45
Kotlin
0
9
1a110536865250dcd8d29270d003315062f2b032
2,188
soyle-stories
Apache License 2.0
plugin/src/main/kotlin/com/sanyavertolet/kotlinjspreview/config/PluginConfig.kt
sanyavertolet
668,488,437
false
{"Kotlin": 40557, "HTML": 369}
package com.sanyavertolet.kotlinjspreview.config import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.Service import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.util.xmlb.XmlSerializerUtil /** * Plugin configuration data class * * @property tempProjectDirName name of a dir inside of `build` directory, where a copy of project is located * @property copyIgnoreFileNames file/dir names that should not be copied to temp dir */ @Service(Service.Level.PROJECT) @State( name = "KotlinJsPreviewPluginConfig", storages = [Storage("kotlinJsPreview.xml")], ) data class PluginConfig( var tempProjectDirName: String = DEFAULT_TEMP_PROJECT_DIR_NAME, var copyIgnoreFileNames: List<String> = defaultCopyIgnoreFileNames, ) : PersistentStateComponent<PluginConfig> { override fun getState(): PluginConfig { return this } override fun loadState(state: PluginConfig) { XmlSerializerUtil.copyBean(state, this) } companion object { fun getInstance(): PluginConfig = service<PluginConfig>() /** * Default value of [tempProjectDirName] */ const val DEFAULT_TEMP_PROJECT_DIR_NAME = "jsPreviewTemp" /** * Default value of [copyIgnoreFileNames] */ val defaultCopyIgnoreFileNames = listOf( ".idea", ".gradle", ".run", "build", ".gitignore", ) } }
0
Kotlin
0
6
a186d0d4a58f8ff4b395759425bb8c181c449fea
1,592
kotlin-js-preview-idea-plugin
MIT License
freya/src/main/kotlin/io/violabs/freya/controller/LibraryController.kt
violabs
640,711,709
false
null
package io.violabs.freya.controller import io.violabs.freya.domain.Library import io.violabs.freya.service.LibraryService import kotlinx.coroutines.flow.Flow import mu.KLogging import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("api/libraries") class LibraryController(private val libraryService: LibraryService) { @GetMapping("{userId}") suspend fun getLibraryDetailsByUserId(@PathVariable userId: Long): Library = log("getLibraryDetailsByUserId($userId)") { libraryService.getLibraryDetailsByUserId(userId) } @PostMapping("{userId}/book/{bookId}") suspend fun addBookToLibrary(@PathVariable userId: Long, @PathVariable bookId: Long): Flow<Long> = log("addBookToLibrary($userId, $bookId)") { libraryService.addBookToLibrary(userId, bookId) } private suspend fun <T> log(message: String, fn: suspend () -> T): T { logger.info { "STARTING: $message" } return fn().also { logger.info { "FINISHING: $message" } } } companion object : KLogging() }
8
Kotlin
0
1
a0d58453016e2794f31b4ca7fca85f2d814c8b1a
1,290
vanir
Apache License 2.0
src/main/kotlin/com/github/imflog/schema/registry/config/ConfigTaskAction.kt
bspeakmon
190,799,790
true
{"Kotlin": 73111}
package com.github.imflog.schema.registry.config import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient import io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException import org.gradle.api.logging.Logging class ConfigTaskAction( private val client: SchemaRegistryClient, private val subjectPairs: List<Pair<String, String>> ) { private val logger = Logging.getLogger(ConfigTaskAction::class.java) fun run() : Int { var errorCount = 0 for ((subject, config) in subjectPairs) { logger.debug("$subject: setting config $config") try { client.updateCompatibility(subject, config) } catch (ex: RestClientException) { logger.error("Error during compatibility update for $subject", ex) errorCount++ } } return errorCount } }
0
Kotlin
0
0
3313c9aa146a7deda83818c53fa16e92088e939d
903
schema-registry-plugin
Apache License 2.0
katarina-core/src/main/kotlin/com/hubtwork/riot/dto/cdn/championdetail/ChampionPassiveDTO.kt
adsad100
339,934,054
false
null
package com.hubtwork.riot.dto.cdn.championdetail import com.hubtwork.riot.dto.cdn.Image /** * DTO for Champion's Passive Skill * */ data class ChampionPassiveDTO ( var name: String, var description: String, var image: Image )
0
Kotlin
0
0
0db5e7d5c1b681a562392ded6182bffc72b91f7b
249
Katarina
MIT License
src/jvmTest/java/com/codeborne/selenide/MatchTextConditionTest.kt
TarCV
358,762,107
true
{"Kotlin": 998044, "Java": 322706, "HTML": 46587, "XSLT": 7418}
package com.codeborne.selenide import com.codeborne.selenide.Condition.Companion.matchText import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.assertj.core.api.WithAssertions import org.junit.jupiter.api.Test import org.mockito.Mockito import org.openqa.selenium.WebElement @ExperimentalCoroutinesApi internal class MatchTextConditionTest : WithAssertions { private val driver = Mockito.mock(Driver::class.java) @Test fun displaysHumanReadableName() { assertThat(matchText("abc")) .hasToString("match text 'abc'") } @Test fun matchesWholeString() = runBlockingTest { assertThat( matchText("Chuck Norris' gmail account is [email protected]") .apply(driver, element("Chuck Norris' gmail account is [email protected]")) ) .isTrue() assertThat( matchText("Chuck Norris.* gmail\\s+account is [email protected]") .apply(driver, element("Chuck Norris' gmail account is [email protected]")) ) .isTrue() } private fun element(text: String): WebElement { val element = Mockito.mock(WebElement::class.java) Mockito.`when`(element.text).thenReturn(text) return element } @Test fun matchesSubstring() = runBlockingTest { assertThat( matchText("Chuck") .apply(driver, element("Chuck Norris' gmail account is [email protected]")) ) .isTrue() assertThat( matchText("Chuck\\s*Norris") .apply(driver, element("Chuck Norris' gmail account is [email protected]")) ) .isTrue() assertThat( matchText("gmail account") .apply(driver, element("Chuck Norris' gmail account is [email protected]")) ) .isTrue() } }
0
Kotlin
0
0
c86103748bdf214adb8a027492d21765059d3629
1,932
selenide.kt-js
MIT License
src/main/kotlin/io/github/darefox/bot/Main.kt
DareFox
573,069,850
false
null
package io.github.darefox.bot import io.github.darefox.bot.extensions.PingPongExtension import io.github.darefox.bot.extensions.TempRoomCreatorExtension import com.kotlindiscord.kord.extensions.ExtensibleBot import dev.kord.gateway.Intents import dev.kord.gateway.PrivilegedIntent import org.litote.kmongo.KMongo @OptIn(PrivilegedIntent::class) suspend fun main(args: Array<String>) { val bot = ExtensibleBot(Config.botToken) { // To add extensions, you need to pass reference to extension class via :: symbol extensions { add(::TempRoomCreatorExtension) } intents { +Intents.all } } bot.start() }
0
Kotlin
0
0
7e29f03f3a45e672ea66b1b61366fbc5873e987e
675
TempRoomBot
MIT License
src/main/kotlin/no/nav/toi/kandidatvarsel/altinnsms/AltinnVarsel.kt
navikt
768,528,587
false
{"Kotlin": 92600, "Dockerfile": 255}
package no.nav.toi.kandidatvarsel.altinnsms import no.nav.toi.kandidatvarsel.* import org.springframework.jdbc.core.simple.JdbcClient import java.sql.ResultSet import java.time.LocalDateTime import javax.sql.DataSource enum class AltinnStatus { SENDT, UNDER_UTSENDING, IKKE_SENDT, FEIL } /** Gammel løsning sendte SMS via altinn. Det blir ikke * opprettet nye, men vi har historikk på stillinger og * kandidater. */ data class AltinnVarsel( private val avsenderNavident: String, private val mottakerFnr: String, private val frontendId: String, private val opprettet: LocalDateTime, private val stillingId: String, private val status: AltinnStatus, ) { fun toResponse() = VarselResponseDto( id = frontendId, opprettet = opprettet, stillingId = stillingId, mottakerFnr = mottakerFnr, avsenderNavident = avsenderNavident, minsideStatus = MinsideStatusDto.IKKE_BESTILT, eksternStatus = when (status) { AltinnStatus.IKKE_SENDT -> EksternStatusDto.UNDER_UTSENDING AltinnStatus.UNDER_UTSENDING -> EksternStatusDto.UNDER_UTSENDING AltinnStatus.SENDT -> EksternStatusDto.VELLYKKET_SMS AltinnStatus.FEIL -> EksternStatusDto.FEIL }, eksternFeilmelding = null, ) companion object { object RowMapper : org.springframework.jdbc.core.RowMapper<AltinnVarsel> { override fun mapRow(rs: ResultSet, rowNum: Int) = AltinnVarsel( avsenderNavident = rs.getString("avsender_navident"), frontendId = rs.getString("frontend_id"), opprettet = rs.getTimestamp("opprettet").toLocalDateTime(), stillingId = rs.getString("stilling_id"), mottakerFnr = rs.getString("mottaker_fnr"), status = AltinnStatus.valueOf(rs.getString("status")), ) } fun hentVarslerForStilling(jdbcClient: JdbcClient, stillingId: String): List<AltinnVarsel> = jdbcClient.sql("""select * from altinn_varsel where stilling_id = :stilling_id""") .param("stilling_id", stillingId) .query(RowMapper) .list() fun hentVarslerForQuery(jdbcClient: JdbcClient, queryRequestDto: QueryRequestDto): List<AltinnVarsel> = jdbcClient.sql("""select * from altinn_varsel where mottaker_fnr = :mottaker_fnr""") .param("mottaker_fnr", queryRequestDto.fnr) .query(RowMapper) .list() } }
0
Kotlin
0
0
5745dfd8430ee775675708eb089048340cf6d68a
2,554
rekrutteringsbistand-kandidatvarsel-api
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Hiking.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline 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 me.localx.icons.straight.Icons public val Icons.Outline.Hiking: ImageVector get() { if (_hiking != null) { return _hiking!! } _hiking = Builder(name = "Hiking", defaultWidth = 512.0.dp, defaultHeight = 512.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(10.48f, 2.5f) arcTo(2.5f, 2.5f, 0.0f, true, true, 12.98f, 5.0f) arcTo(2.5f, 2.5f, 0.0f, false, true, 10.48f, 2.5f) close() moveTo(20.98f, 7.0f) lineTo(20.98f, 24.0f) horizontalLineToRelative(-2.0f) lineTo(18.98f, 12.0f) lineTo(15.362f, 12.0f) lineToRelative(-0.906f, -1.813f) lineToRelative(-0.785f, 4.033f) lineToRelative(-1.808f, -1.177f) lineToRelative(0.979f, -5.029f) curveToRelative(-0.033f, 0.0f, -1.96f, -0.014f, -1.96f, -0.014f) lineTo(9.836f, 13.372f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.437f, 1.03f) lineToRelative(4.707f, 3.055f) lineTo(14.98f, 24.0f) horizontalLineToRelative(-2.0f) lineTo(12.98f, 18.543f) lineTo(9.185f, 16.08f) arcToRelative(3.009f, 3.009f, 0.0f, false, true, -0.744f, -0.694f) arcTo(3.3f, 3.3f, 0.0f, false, true, 6.469f, 16.0f) curveTo(4.8f, 16.0f, 3.0f, 14.748f, 3.0f, 12.0f) curveTo(3.0f, 8.636f, 6.036f, 6.0f, 9.913f, 6.0f) horizontalLineToRelative(2.831f) arcToRelative(2.984f, 2.984f, 0.0f, false, true, 2.684f, 1.658f) lineTo(16.6f, 10.0f) lineTo(18.98f, 10.0f) lineTo(18.98f, 7.0f) close() moveTo(7.912f, 12.781f) horizontalLineToRelative(0.0f) lineTo(8.824f, 8.1f) curveTo(6.8f, 8.478f, 5.0f, 9.874f, 5.0f, 12.0f) curveToRelative(0.0f, 1.9f, 1.224f, 2.0f, 1.469f, 2.0f) arcTo(1.5f, 1.5f, 0.0f, false, false, 7.912f, 12.781f) close() moveTo(7.941f, 17.64f) lineTo(6.854f, 24.0f) lineTo(8.9f, 24.0f) lineToRelative(0.847f, -5.174f) lineTo(8.1f, 17.757f) curveTo(8.04f, 17.722f, 7.994f, 17.677f, 7.941f, 17.64f) close() } } .build() return _hiking!! } private var _hiking: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,396
icons
MIT License
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_PersonalityTypeTest.kt
boris920308
618,428,844
false
{"Kotlin": 57019, "Swift": 40496, "Java": 2698, "Rich Text Format": 407}
/** * 프로그래머스 Lv.1 * https://school.programmers.co.kr/learn/courses/30/lessons/118666 */ fun main() { val mSurvey = arrayOf("RT", "TR", "FC", "CF", "MJ", "JM", "AN", "NA") // solution(mSurvey, intArrayOf(1,2,3,4,1,2,3,6)) solution(arrayOf("AN", "CF", "MJ", "RT", "NA"), intArrayOf(5, 3, 2, 7, 5)) solution(arrayOf("TR", "RT", "TR"), intArrayOf(7, 1, 3)) } fun solution(survey: Array<String>, choices: IntArray): String { println() println("* * * * * * * * solution * * * * * * * * ") var answer: String = "" var resultArray = charArrayOf() survey.forEachIndexed { index, s -> println("---------------index = $index-------------") println(s.toCharArray()[0]) println(s.toCharArray()[1]) println("get choices = ${choices[index]}") when(choices[index]) { 1 -> { resultArray = resultArray.plus(s.toCharArray()[0]) resultArray = resultArray.plus(s.toCharArray()[0]) resultArray = resultArray.plus(s.toCharArray()[0]) } 2 -> { resultArray = resultArray.plus(s.toCharArray()[0]) resultArray = resultArray.plus(s.toCharArray()[0]) } 3 -> { resultArray = resultArray.plus(s.toCharArray()[0]) } 4 -> {} 5 -> { resultArray = resultArray.plus(s.toCharArray()[1]) } 6 -> { resultArray = resultArray.plus(s.toCharArray()[1]) resultArray = resultArray.plus(s.toCharArray()[1]) } 7 -> { resultArray = resultArray.plus(s.toCharArray()[1]) resultArray = resultArray.plus(s.toCharArray()[1]) resultArray = resultArray.plus(s.toCharArray()[1]) } } } println("resultArray = ${resultArray.toList()}") var countR = 0 var countT = 0 var countC = 0 var countF = 0 var countJ = 0 var countM = 0 var countA = 0 var countN = 0 var resultSolution = charArrayOf() resultArray.forEach { when (it) { 'R' -> { countR++ } 'T' -> { countT++ } 'C' -> { countC++ } 'F' -> { countF++ } 'J' -> { countJ++ } 'M' -> { countM++ } 'A' -> { countA++ } 'N' -> { countN++ } } } resultSolution = if (countR >= countT) { resultSolution.plus('R') } else { resultSolution.plus('T') } resultSolution = if (countC >= countF) { resultSolution.plus('C') } else { resultSolution.plus('F') } resultSolution = if (countJ >= countM) { resultSolution.plus('J') } else { resultSolution.plus('M') } resultSolution = if (countA >= countN) { resultSolution.plus('A') } else { resultSolution.plus('N') } println("resultSolution = ${resultSolution.toList()}") answer = String(resultSolution) println("answer = $answer") return answer }
1
Kotlin
1
2
0e495912539ae3ba49e03880cb406bcb99f6457b
3,085
HoOne
Apache License 2.0
android-theme/src/main/kotlin/dev/jonpoulton/alakazam/theme/Constants.kt
jonapoul
375,762,483
false
null
package dev.jonpoulton.alakazam.theme import dev.jonpoulton.alakazam.prefs.PrefPair internal object Constants { const val PREF_KEY = "app_theme" val PREF_PAIR = PrefPair(PREF_KEY, AppTheme.SYSTEM.string) }
0
Kotlin
0
0
14f111c8f1ea50be893a0af6f6eb21034cb574ee
212
alakazam
Apache License 2.0
app/src/main/java/com/example/marsphotos/model/MarsPhoto.kt
akbarbin
737,496,550
false
{"Kotlin": 31703}
/* * Copyright (C) 2023 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.marsphotos.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * This data class defines a Mars photo which includes an ID, and the image URL. */ @Serializable data class MarsPhoto( val name: String, val city: String, val p01: String, val p02: String, val p03: String, val p04: String, val p05: String, val p06: String, val p07: String, val p08: String, val p09: String, val p10: String, val p11: String, val p12: String, val p13: String, val p14: String, val p15: String, val p16: String, val p17: String, val p18: String, val p19: String, val p20: String, val p21: String, val p22: String, val p23: String, val p24: String, val p25: String, val p26: String, val p27: String, val p28: String, val p29: String, val p30: String, val p31: String, val p32: String, val p33: Double, val p34: Int, val p35: String, val p36: String, val p37: String, val p38: String, val p39: String, val p40: String, val p41: String, val p42: String, val p43: String, val p44: String, val p45: String, val p46: String, val p47: String, val p48: String, val p49: String, val p50: String, @SerialName("p51_1") val p511: Double, @SerialName("p51_2") val p512: Double, @SerialName("p51_3") val p513: Double, @SerialName("p51_4") val p514: Double, @SerialName("p51_5") val p515: Double, @SerialName("p51_6") val p516: Double, val p52: String, val p53: String, val p54: String, val p55: String, val p56: String, val p57: String, val p58: String, val p59: String, val p60: String, @SerialName("p61_1") val p611: Double, @SerialName("p61_2") val p612: Double, @SerialName("p61_3") val p613: Double, @SerialName("p61_4") val p614: Double, @SerialName("p61_5") val p615: Double, @SerialName("p61_6") val p616: Double, val p62: String, val p63: Double, val p64: String, val p65: String, val p66: String, @SerialName("p67_1") val p671: Double, @SerialName("p67_2") val p672: Double, @SerialName("p68_1") val p681: Double, @SerialName("p68_2") val p682: Double, @SerialName("p68_3") val p683: Double, @SerialName("p68_4") val p684: Double, @SerialName("p68_5") val p685: Double, @SerialName("p68_6") val p686: Double, val p69: Double, val p70: String, val p71: String, val p72: Double, val p73: Double, val p74: String, val p75: String, val p76: String, val p77: String, val p78: String, @SerialName("p79_1") val p791: Double, @SerialName("p79_2") val p792: Double, @SerialName("p79_3") val p793: Double, @SerialName("p79_4") val p794: Double, @SerialName("p79_5") val p795: Double, @SerialName("p79_6") val p796: Double, val p80: String, val p81: String, val p82: String, val p83: String, val id: Int?, val ax: Float?, val bx: Float?, val cx: Float?, val dx: Float?, val performance: Float?, val level: String?, val policy: Float?, val retrofit: Float?, val construction: Float?, val utilization: Float? )
0
Kotlin
0
0
1c6085060cbb9dfdaa827bcbb8c96f3da8af7f09
4,029
green-building-android
Apache License 2.0