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/com/studio1r/simpleblockexplorer/BlockListViewModelFactory.kt
takn
186,167,067
false
null
package com.studio1r.simpleblockexplorer import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import io.reactivex.Scheduler class BlockListViewModelFactory(private val repository: BlockRepository, private val executionScheduler: Scheduler, private val observationScheduler: Scheduler) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return BlockListViewModel(repository, executionScheduler, observationScheduler) as T } }
1
null
1
1
031dbc33e4b430a0fa27bd38ef1deb8eca2ad8ae
589
SimpleBlockExplorer
Apache License 2.0
android/src/main/kotlin/io/sourcya/playx_3d_scene/factory/Playx3dSceneFactory.kt
playx-flutter
607,852,578
false
null
package io.sourcya.playx_3d_scene.factory import android.content.Context import com.google.android.filament.Engine import com.google.android.filament.gltfio.AssetLoader import com.google.android.filament.gltfio.ResourceLoader import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.StandardMessageCodec import io.flutter.plugin.platform.PlatformView import io.flutter.plugin.platform.PlatformViewFactory import io.sourcya.playx_3d_scene.core.utils.IBLProfiler import io.sourcya.playx_3d_scene.utils.LifecycleProvider import io.sourcya.playx_3d_scene.view.Playx3dScene class Playx3dSceneFactory(private val binding: FlutterPlugin.FlutterPluginBinding, private val engine:Engine, private val iblProfiler: IBLProfiler, private val assetLoader: AssetLoader, private val resourceLoader: ResourceLoader, private val lifecycleProvider: LifecycleProvider ):PlatformViewFactory (StandardMessageCodec.INSTANCE){ override fun create(context: Context, viewId: Int, args: Any?): PlatformView { val creationParams = try { args as Map<String?, Any?>? }catch (_:Throwable){ null } return Playx3dScene( context, viewId, creationParams , binding, engine, iblProfiler, assetLoader, resourceLoader, lifecycleProvider ) } }
1
null
0
3
46cd40546b4b06aea4fae0889926d24e441ad825
1,549
playx-3d-scene
MIT License
idea/idea-completion/testData/basic/common/override/Simple.kt
JakeWharton
99,388,807
false
null
interface I { infix fun foo(p: Int) val someVal: Int var someVar: Int } class Base1 { protected open suspend fun bar(){} } open class Base2 : Base1() { } class A : Base2(), I { o<caret> } // EXIST: { lookupString: "override", itemText: "override"} // EXIST: { itemText: "override suspend fun bar() {...}", lookupString: "override", allLookupStrings: "bar, override", tailText: null, typeText: "Base1", attributes: "", icon: "nodes/method.svg" } // EXIST: { itemText: "override fun equals(other: Any?): Boolean {...}", lookupString: "override", allLookupStrings: "equals, override", tailText: null, typeText: "Any", attributes: "", icon: "nodes/method.svg" } // EXIST: { itemText: "override fun foo(p: Int) {...}", lookupString: "override", allLookupStrings: "foo, override", tailText: null, typeText: "I", attributes: "bold", icon: "nodes/abstractMethod.svg" } // EXIST: { itemText: "override fun hashCode(): Int {...}", lookupString: "override", allLookupStrings: "hashCode, override", tailText: null, typeText: "Any", attributes: "", icon: "nodes/method.svg" } // EXIST: { itemText: "override val someVal: Int", lookupString: "override", allLookupStrings: "override, someVal", tailText: null, typeText: "I", attributes: "bold", icon: "org/jetbrains/kotlin/idea/icons/field_value.svg" } // EXIST: { itemText: "override var someVar: Int", lookupString: "override", allLookupStrings: "override, someVar", tailText: null, typeText: "I", attributes: "bold", icon: "org/jetbrains/kotlin/idea/icons/field_variable.svg" }
191
null
4372
83
4383335168338df9bbbe2a63cb213a68d0858104
1,540
kotlin
Apache License 2.0
cobalt.core/src/commonMain/kotlin/org/hexworks/cobalt/databinding/internal/extensions/PropertyExtensions.kt
cobalt
155,008,361
false
{"Kotlin": 179455, "Shell": 65}
package org.hexworks.cobalt.databinding.internal.extensions import org.hexworks.cobalt.databinding.api.property.Property import org.hexworks.cobalt.databinding.internal.property.InternalProperty internal fun <T : Any> Property<T>.asInternalProperty(): InternalProperty<T> { return this as InternalProperty<T> }
0
Kotlin
5
6
4b75558da4c72190706d7e30929eb0cfa110653a
317
cobalt
Apache License 2.0
app/src/main/java/fr/thegostsniperfr/todoapp/utils/Constants.kt
mamad2050
796,186,908
false
{"Kotlin": 13260}
package fr.thegostsniperfr.todoapp.utils object Constants { const val DATABASE_TABLE = "todo_table" const val DATABASE_NAME = "todo_database" const val LIST_SCREEN = "list/{action}" const val TASK_SCREEN = "task/{taskId}" const val LIST_ARGUMENT_KEY = "action" const val TASK_ARGUMENT_KEY = "taskId" }
0
Kotlin
0
0
8ea54276a30c874a17dfc8ea46d803883d7a33dd
328
ToDoApp
MIT License
app/src/main/java/com/example/quitter/MainActivity.kt
Johnricharde
799,963,883
false
{"Kotlin": 17410}
package com.example.quitter import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.ui.Modifier import com.example.quitter.ui.theme.QuitterTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { QuitterTheme { Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> MainPage( modifier = Modifier.padding(innerPadding) ) } } } } }
0
Kotlin
0
0
ea73347be65c818fb0741fe27c14cf30f52a04f8
880
Quitter
The Unlicense
product/appkit/src/main/kotlin/com/reown/appkit/ui/components/button/Web3Button.kt
reown-com
851,466,242
false
{"Kotlin": 2055654, "Java": 4294, "Shell": 1676}
package com.reown.appkit.ui.components.button import androidx.compose.animation.AnimatedContent import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @Composable fun Web3Button( state: AppKitState, accountButtonType: AccountButtonType = AccountButtonType.NORMAL, connectButtonSize: ConnectButtonSize = ConnectButtonSize.NORMAL ) { val isConnected by state.isConnected.collectAsState(initial = false) AnimatedContent( targetState = isConnected, label = "Web3ButtonState" ) { isConnected -> if (isConnected) { AccountButton(state = state, accountButtonType = accountButtonType) } else { ConnectButton(state = state, buttonSize = connectButtonSize) } } }
78
Kotlin
70
8
893084b3df91b47daa77f8f964e37f84a02843b1
824
reown-kotlin
Apache License 2.0
app/src/main/java/com/example/makeupmate/ui/PreviewActivity.kt
Nugraha-akt
646,423,292
false
null
package com.example.makeupmate.ui import android.content.Intent import android.graphics.BitmapFactory import android.os.Build import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.makeupmate.databinding.ActivityPreviewBinding import com.example.makeupmate.utils.rotateFile import java.io.File class PreviewActivity : AppCompatActivity() { private lateinit var binding: ActivityPreviewBinding private var getFile: File? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPreviewBinding.inflate(layoutInflater) setContentView(binding.root) val myFile = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getSerializableExtra("picture", File::class.java) } else { @Suppress("DEPRECATION") intent.getSerializableExtra("picture") } as? File val isBackCamera = intent.getBooleanExtra("isBackCamera", true) as Boolean myFile?.let { rotateFile(it, isBackCamera) getFile = it binding.previewPhoto.setImageBitmap(BitmapFactory.decodeFile(it.path)) } binding.btnBack.setOnClickListener { startActivity(Intent(this@PreviewActivity, CameraActivity::class.java)) } binding.delete.setOnClickListener { val intent = Intent(this@PreviewActivity, CameraActivity::class.java) startActivity(intent) } binding.confirm.setOnClickListener { val intent = Intent(this@PreviewActivity, RekomActivity::class.java) intent.putExtra("picture", myFile) intent.putExtra( "isBackCamera", isBackCamera ) setResult(RekomActivity.CAMERA_X_RESULT, intent) startActivity(intent) } } companion object { const val CAMERA_X_RESULT = 200 } }
0
Kotlin
0
0
a6b4df517f7fd436ab0162f5dd994625c4d9a611
1,993
makeupmate
MIT License
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/gradle/newTests/KotlinBeforeAfterTestRuleWithTarget.kt
rpaquay
136,651,574
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.gradle.newTests import org.junit.rules.MethodRule import org.junit.runners.model.FrameworkMethod import org.junit.runners.model.Statement interface KotlinBeforeAfterTestRuleWithTarget : MethodRule { override fun apply(base: Statement, method: FrameworkMethod, target: Any): Statement { return object : Statement() { override fun evaluate() { try { before(target) base.evaluate() } finally { after(target) } } } } fun before(target: Any) { } /** * [after] is guaranteed to be called even if the test or [before] finished with an exception */ fun after(target: Any) { } }
1
null
1
1
1f52648bb045575c53c3b22ccbab8bf8ad93094b
919
intellij-community
Apache License 2.0
api/src/main/java/org/runestar/client/api/SidePanel.kt
widget-
179,150,566
true
{"Kotlin": 1038885, "Java": 4010}
package org.runestar.client.api import com.alee.managers.style.StyleId import org.kxtra.slf4j.info import org.kxtra.slf4j.getLogger import org.kxtra.swing.component.window import java.awt.BorderLayout import java.awt.Component import java.awt.Dimension import java.util.* import javax.swing.* class SidePanel internal constructor() : JPanel() { companion object { const val PANEL_WIDTH = 225 const val BAR_WIDTH = 24 const val WIDTH = PANEL_WIDTH + BAR_WIDTH } private val tabs: SortedSet<TabButton> = TreeSet() private val buttons: SortedSet<BarButton> = TreeSet() private var firstTabs: SortedSet<TabButton> = TreeSet() internal val panel: JPanel private val buttonsBox: Box private val logger = getLogger() private var selectedTab: TabButton? = null init { layout = BoxLayout(this, BoxLayout.X_AXIS) panel = JPanel(BorderLayout()).apply { alignmentX = JComponent.RIGHT_ALIGNMENT alignmentY = JComponent.CENTER_ALIGNMENT preferredSize = Dimension(PANEL_WIDTH, 0) minimumSize = Dimension(PANEL_WIDTH, 0) maximumSize = Dimension(PANEL_WIDTH, Int.MAX_VALUE) isVisible = false } buttonsBox = Box.createVerticalBox().apply { alignmentX = JComponent.LEFT_ALIGNMENT alignmentY = JComponent.CENTER_ALIGNMENT preferredSize = Dimension(BAR_WIDTH, 0) minimumSize = Dimension(BAR_WIDTH, 0) maximumSize = Dimension(BAR_WIDTH, Int.MAX_VALUE) } alignmentX = JComponent.CENTER_ALIGNMENT alignmentY = JComponent.CENTER_ALIGNMENT add(buttonsBox) add(panel) } fun add(tab: TabButton) { if (!tabs.add(tab)) { logger.info { "Cannot add $tab, it is already present" } return } rebuild() } internal fun addFirst(tab: TabButton) { if (!firstTabs.add(tab)) { logger.info { "Cannot add $tab, it is already present" } return } rebuild() } internal fun add(button: BarButton) { if (!buttons.add(button)) { logger.info { "Cannot add $button, it is already present" } return } rebuild() } internal fun clear() { firstTabs.clear() tabs.clear() buttons.clear() rebuild() } fun remove(tab: TabButton) { if (!tabs.remove(tab)) { logger.info { "Cannot remove $tab, it is not present" } return } rebuild() } internal fun removeFirst(tab: TabButton) { if (!firstTabs.remove(tab)) { logger.info { "Cannot remove $tab, it is not present" } return } rebuild() } internal fun remove(button: BarButton) { if (!buttons.remove(button)) { logger.info { "Cannot remove $button, it is not present" } return } rebuild() } private fun rebuild() { buttonsBox.removeAll() panel.removeAll() firstTabs.forEach { buttonsBox.add(it.makeButton()) } tabs.forEach { buttonsBox.add(it.makeButton()) } buttonsBox.add(Box.createGlue()) buttons.forEach { buttonsBox.add(it.makeButton()) } if (selectedTab == null) { selectedTab = firstTabs.firstOrNull() ?: tabs.firstOrNull() } selectedTab?.component?.let { panel.add(it, BorderLayout.CENTER) } revalidate() repaint() } private fun TabButton.makeButton(): Component { return JButton(icon).apply { alignmentY = JComponent.TOP_ALIGNMENT alignmentX = JComponent.CENTER_ALIGNMENT putClientProperty(StyleId.STYLE_PROPERTY, StyleId.buttonIconHover) // TooltipManager.addTooltip(this, this@makeButton.name) // todo addActionListener { if (selectedTab != this@makeButton || !panel.isVisible) { selectedTab = this@makeButton panel.removeAll() panel.add(component, BorderLayout.CENTER) if (!panel.isVisible) { panel.isVisible = true (window as GameFrame).refit() // todo } else { panel.revalidate() panel.repaint() } } else { panel.isVisible = false (window as GameFrame).refit() } } } } private fun BarButton.makeButton(): Component { return JButton(icon).apply { alignmentY = JComponent.BOTTOM_ALIGNMENT alignmentX = JComponent.CENTER_ALIGNMENT putClientProperty(StyleId.STYLE_PROPERTY, StyleId.buttonIconHover) // TooltipManager.addTooltip(this, this@makeButton.name) // todo addActionListener(this@makeButton) } } }
0
Kotlin
0
0
5ff4db62d216fcc316d7171501ec5c1a45460bd2
5,138
client
MIT License
app/src/main/java/com/example/fitness_app/welcome/FragmentWelcome.kt
HauntedMilkshake
698,074,119
false
{"Kotlin": 18759}
package com.example.fitness_app.welcome import android.annotation.SuppressLint import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.ScaleAnimation import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.fitness_app.R import com.example.fitness_app.databinding.FragmentWelcomeBinding import com.example.fitness_app.hideBottomNav import com.google.android.material.bottomnavigation.BottomNavigationView class FragmentWelcome: Fragment() { private var _binding: FragmentWelcomeBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentWelcomeBinding.inflate(inflater, container, false) return binding.root } override fun onStart() { super.onStart() requireActivity().hideBottomNav() } @SuppressLint("ResourceAsColor") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { entry.setOnClickListener { it.startAnimation(ScaleAnimation(0f, 20f, 0f, 20f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f).apply { duration = 1500 }) it.postDelayed({ welcomeText.visibility = View.VISIBLE underWelcomeText.visibility = View.VISIBLE registerButton.visibility = View.VISIBLE logInButton.visibility = View.VISIBLE root.setBackgroundColor(R.color.background) }, 1500) it.visibility = View.GONE } logInButton.setOnClickListener{ findNavController().navigate(R.id.welcome_to_login) } registerButton.setOnClickListener{ findNavController().navigate(R.id.welcome_to_signup) } } } }
0
Kotlin
0
1
d6b4b437f082996fccf971ad4d9992ea67739a07
2,207
fitness_app
MIT License
androidApp/src/main/java/com/mutualmobile/harvestKmp/android/HKMPApp.kt
mutualmobile
495,292,087
false
null
package com.mutualmobile.harvestKmp.android import android.app.Application import com.mutualmobile.harvestKmp.android.di.viewModelModule import com.mutualmobile.harvestKmp.db.DriverFactory import com.mutualmobile.harvestKmp.di.SharedComponent import com.mutualmobile.harvestKmp.di.initSharedDependencies import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.koin.android.ext.koin.androidContext val sharedComponent = SharedComponent() class HKMPApp : Application() { override fun onCreate() { super.onCreate() initSharedDependencies().apply { androidContext(this@HKMPApp) modules(viewModelModule) } GlobalScope.launch { precheckSqlite() } } private suspend fun precheckSqlite() { if (sharedComponent.provideHarvestUserLocal().driver == null) { val driver = DriverFactory(context = this).createDriverBlocking() sharedComponent.provideHarvestUserLocal().driver = driver } } }
0
Kotlin
4
41
763dd7f45f8271cebe9107c63f3532e1b14c666f
1,037
HarvestTimeKMP
Apache License 2.0
app/src/main/java/com/kaelesty/shoppinglist/di/DatasourceModule.kt
Kaelesty
669,493,927
false
null
package com.kaelesty.shoppinglist.di import android.app.Application import com.kaelesty.shoppinglist.data.ShopItemDatabase import dagger.BindsInstance import dagger.Module import dagger.Provides @Module class DatasourceModule { @Provides fun provideDatabase(@AppContextQualifier application: Application) = ShopItemDatabase.getInstance(application) @Provides fun provideDao(db: ShopItemDatabase) = db.shopListDao() }
0
Kotlin
0
0
da6f5104647f1373c12799470ffe2fa478324f82
426
study-android-shopping_list
The Unlicense
05-data-layer-caching/projects/starter/app/src/androidTest/java/com/raywenderlich/android/petsave/common/data/PetFinderAnimalRepositoryTest.kt
GoddayOkos
410,719,187
false
null
package com.raywenderlich.android.petsave.common.data import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import com.raywenderlich.android.petsave.common.data.api.PetFinderApi import com.raywenderlich.android.petsave.common.data.api.model.mappers.ApiAnimalMapper import com.raywenderlich.android.petsave.common.data.api.model.mappers.ApiPaginationMapper import com.raywenderlich.android.petsave.common.data.api.utils.FakeServer import com.raywenderlich.android.petsave.common.data.cache.Cache import com.raywenderlich.android.petsave.common.data.cache.PetSaveDatabase import com.raywenderlich.android.petsave.common.data.cache.RoomCache import com.raywenderlich.android.petsave.common.data.di.CacheModule import com.raywenderlich.android.petsave.common.data.di.PreferencesModule import com.raywenderlich.android.petsave.common.data.preferences.FakePreferences import com.raywenderlich.android.petsave.common.data.preferences.Preferences import com.raywenderlich.android.petsave.common.domain.repositories.AnimalRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.testing.BindValue import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import dagger.hilt.android.testing.UninstallModules import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.threeten.bp.Instant import retrofit2.Retrofit import javax.inject.Inject @HiltAndroidTest @UninstallModules(PreferencesModule::class, CacheModule::class) class PetFinderAnimalRepositoryTest { private val fakeServer = FakeServer() private lateinit var repository: AnimalRepository private lateinit var api: PetFinderApi private lateinit var cache: Cache @get:Rule var hiltRule = HiltAndroidRule(this) @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @Inject lateinit var database: PetSaveDatabase @Inject lateinit var retrofitBuilder: Retrofit.Builder @Inject lateinit var apiAnimalMapper: ApiAnimalMapper @Inject lateinit var apiPaginationMapper: ApiPaginationMapper @BindValue @JvmField val preferences: Preferences = FakePreferences() @Module @InstallIn(SingletonComponent::class) object TestCacheModule { @Provides fun provideRoomDatabase(): PetSaveDatabase { return Room.inMemoryDatabaseBuilder( InstrumentationRegistry.getInstrumentation().context, PetSaveDatabase::class.java ) .allowMainThreadQueries() .build() } } @Before fun setup() { fakeServer.start() // Start the fake server // Setup preferences preferences.deleteTokenInfo() preferences.putToken("validToken") preferences.putTokenExpirationTime( Instant.now().plusSeconds(3600).epochSecond ) preferences.putTokenType("Bearer") hiltRule.inject() // Tell hilt to inject the dependencies api = retrofitBuilder .baseUrl(fakeServer.baseEndpoint) .build() .create(PetFinderApi::class.java) cache = RoomCache(database.organizationsDao(), database.animalsDao()) repository = PetFinderAnimalRepository( api, cache, apiAnimalMapper, apiPaginationMapper ) } @After fun teardown() { fakeServer.shutdown() } @Test fun requestMoreAnimals_success() = runBlocking { // Given val expectedAnimalId = 124L fakeServer.setHappyPathDispatcher() // When val paginatedAnimals = repository.requestMoreAnimals(1, 100) // Then val animal = paginatedAnimals.animals.first() assertThat(animal.id).isEqualTo(expectedAnimalId) } @Test fun insertAnimals_success() { // Given val expectedAnimalId = 124L runBlocking { fakeServer.setHappyPathDispatcher() val paginatedAnimals = repository.requestMoreAnimals(1, 100) val animal = paginatedAnimals.animals.first() // When repository.storeAnimals(listOf(animal)) } val testObserver = repository.getAnimals().test() testObserver.assertNoErrors() testObserver.assertNotComplete() testObserver.assertValue { it.first().id == expectedAnimalId } } }
0
Kotlin
0
0
97c8fc18f93ded73006d5f39daaaab88871d05c7
4,735
RW-PetSave-App
Apache License 2.0
compiler/tests-spec/testData/diagnostics/notLinked/contracts/declarations/contractBuilder/common/neg/1.kt
arrow-kt
109,678,056
false
null
// !LANGUAGE: +AllowContractsForCustomFunctions +UseCallsInPlaceEffect // !DIAGNOSTICS: -INVISIBLE_REFERENCE -INVISIBLE_MEMBER -UNUSED_VARIABLE -UNUSED_PARAMETER -UNREACHABLE_CODE -UNUSED_EXPRESSION // !USE_EXPERIMENTAL: kotlin.contracts.ExperimentalContracts /* KOTLIN DIAGNOSTICS NOT LINKED SPEC TEST (NEGATIVE) SECTION: contracts CATEGORY: declarations, contractBuilder, common NUMBER: 1 DESCRIPTION: Contract isn't first statement. */ import kotlin.contracts.* inline fun case_1(block: () -> Unit) { val value_1 = 1 <!CONTRACT_NOT_ALLOWED!>contract<!> { } return block() } inline fun case_2(block: () -> Unit) { 10 - 1 <!CONTRACT_NOT_ALLOWED!>contract<!> { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return block() } inline fun case_3(block: () -> Unit) { throw Exception() <!CONTRACT_NOT_ALLOWED!>contract<!> { callsInPlace(block, InvocationKind.UNKNOWN) } return block() } // это в негативные, inline fun case_4(block: () -> Unit) { .0009 return contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } }
12
null
1
43
d2a24985b602e5f708e199aa58ece652a4b0ea48
1,117
kotlin
Apache License 2.0
feature/settings/src/main/kotlin/com/github/ilikeyourhat/lsaa/feature/settings/home/SettingsUi.kt
ILikeYourHat
385,717,121
false
null
package com.github.ilikeyourhat.lsaa.feature.settings.home import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.github.ilikeyourhat.lsaa.feature.settings.R @Composable internal fun SettingsUi( uiListener: SettingsListener ) { MaterialTheme { Scaffold( topBar = { Toolbar() }, content = { paddingValues -> Content( modifier = Modifier.fillMaxSize() .padding(paddingValues), uiListener = uiListener ) } ) } } @Composable private fun Toolbar() { TopAppBar( title = { Text(text = stringResource(R.string.stg_settingsScreen_title)) }, elevation = 2.dp ) } @Composable private fun Content( uiListener: SettingsListener, modifier: Modifier = Modifier ) { Row( modifier = modifier ) { Item( text = stringResource(R.string.stg_licensesScreen_title), onClick = { uiListener.onLicensesClicked() } ) } } @Composable private fun Item(text: String, onClick: () -> Unit) { Box( modifier = Modifier .fillMaxWidth() .clickable { onClick() } ) { Text( modifier = Modifier .fillMaxWidth() .padding(8.dp), text = text ) } } @Preview( showBackground = true ) @Composable internal fun SettingsUi_Normal() { SettingsUi( uiListener = emptyListener ) } private val emptyListener = object : SettingsListener { override fun onLicensesClicked() = Unit }
12
Kotlin
2
4
3c2073e1eb9f10285c84382caf5caad455f2bb9a
2,260
Large-Scale-Android-App
Apache License 2.0
src/commonMain/kotlin/org.angproj.aux/io/Model.kt
angelos-project
677,039,667
false
{"Kotlin": 972623, "Python": 196308}
/** * Copyright (c) 2024 by <NAME> <<EMAIL>>. * * This software is available under the terms of the MIT license. Parts are licensed * under different terms if stated. The legal terms are attached to the LICENSE file * and are made available on: * * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT * * Contributors: * <NAME> - initial implementation */ package org.angproj.aux.io import org.angproj.aux.buf.AbstractSpeedCopy public class Model private constructor( size: Int, idxLimit: Int ): AbstractModel(size, idxLimit) { public constructor(size: Int) : this(size, size) override fun create(size: Int, idxLimit: Int): Model = Model(size, idxLimit) override fun <T: AbstractSpeedCopy> calculateInto(dest: T, destOff: Int, idxFrom: Int, idxTo: Int) { innerCopy(dest as Model, destOff, idxFrom, idxTo) } public companion object { public val typeSize: TypeSize = TypeSize.BYTE } }
0
Kotlin
0
0
7a4016cea0dbd37275d13cf9b929ed52c1d722ce
972
angelos-project-aux
MIT License
src/main/kotlin/dev/isxander/perko/Perko.kt
isXander
453,786,695
false
{"Java": 4962, "Kotlin": 4202}
package dev.isxander.perko import dev.isxander.perko.perks.Perk import dev.isxander.perko.perks.impl.TestSwordPerk import net.fabricmc.api.ModInitializer import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint import net.minecraft.item.Item import net.minecraft.item.SwordItem object Perko : ModInitializer, PreLaunchEntrypoint { val defaultPerks = mutableMapOf<Class<out Item>, MutableList<Function1<*, List<Perk>>>>() override fun onInitialize() { println("init") } override fun onPreLaunch() { addDefaultPerks<SwordItem> { listOf(TestSwordPerk(it)) } } inline fun <reified T : Item> addDefaultPerks(noinline action: (T) -> List<Perk>) { defaultPerks.computeIfAbsent(T::class.java) { mutableListOf() }.add(action) } }
0
Java
0
0
bd4211e77859d2761115971c56f17867bf34fad8
783
Perko
The Unlicense
toggles-prefs-noop/src/main/java/se/eelde/toggles/prefs/TogglesPreferencesImpl.kt
erikeelde
273,583,444
false
null
package se.eelde.toggles.prefs import android.content.Context @Suppress("LibraryEntitiesShouldNotBePublic") class TogglesPreferencesImpl(@Suppress("UNUSED_PARAMETER") context: Context) : TogglesPreferences { override fun getBoolean(key: String, defValue: Boolean): Boolean = defValue override fun getInt(key: String, defValue: Int): Int = defValue override fun getString(key: String, defValue: String): String = defValue override fun <T : Enum<T>> getEnum(key: String, type: Class<T>, defValue: T): T = defValue }
4
null
2
7
e5c226723c41bb1478916435820b49ac656f00cd
536
toggles
MIT License
app/src/test/java/za/co/foursure/weatherapp/viewModel/WeatherDetailViewModelTest.kt
masithedeveloper
401,830,096
false
{"Kotlin": 140195}
package za.co.foursure.weatherapp.viewModel import android.os.Build import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import za.co.foursure.weatherapp.db.WeatherDatabase import za.co.foursure.weatherapp.db.dao.ForecastDao import za.co.foursure.weatherapp.domain.datasource.forecast.ForecastLocalDataSource import za.co.foursure.weatherapp.ui.weather_detail.WeatherDetailViewModel import za.co.foursure.weatherapp.util.createSampleForecastResponse import za.co.foursure.weatherapp.util.getOrAwaitValue import com.google.common.truth.Truth import io.mockk.MockKAnnotations import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @Config(sdk = [Build.VERSION_CODES.P]) @RunWith(AndroidJUnit4::class) class WeatherDetailViewModelTest { @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() private lateinit var weatherDetailViewModel: WeatherDetailViewModel private lateinit var weatherDatabase: WeatherDatabase private lateinit var forecastDao: ForecastDao private lateinit var forecastLocalDataSource: ForecastLocalDataSource @Before fun setUp() { MockKAnnotations.init(this) weatherDatabase = Room.inMemoryDatabaseBuilder( ApplicationProvider.getApplicationContext(), WeatherDatabase::class.java ) .allowMainThreadQueries() .build() forecastDao = weatherDatabase.forecastDao() forecastLocalDataSource = ForecastLocalDataSource(forecastDao) weatherDetailViewModel = WeatherDetailViewModel(forecastLocalDataSource) } @After fun closeDatabase() { weatherDatabase.close() } @Test fun `insert forecast and when getForecast called the livedata result must be ForecastEntity`() { // When forecastLocalDataSource.insertForecast(createSampleForecastResponse()) // Then val result = weatherDetailViewModel.getForecast().getOrAwaitValue() Truth.assertThat(result.city?.cityName).isEqualTo("Istanbul") } }
0
Kotlin
0
0
41be540161c92319cb9809e4736024a40976af31
2,278
4-Sure-Weatherapp
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/ThumbDownRounded.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/ThumbDownRounded") @file:JsNonModule package mui.icons.material @JsName("default") external val ThumbDownRounded: SvgIconComponent
10
null
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
214
kotlin-wrappers
Apache License 2.0
samples/kofu-reactive-cassandra/src/main/kotlin/com/sample/Application.kt
spring-projects-experimental
134,733,282
false
null
/* * Copyright 2002-2018 the original author or authors. * * 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.sample import org.springframework.fu.kofu.reactiveWebApplication import org.testcontainers.containers.CassandraContainer fun app(properties: ApplicationProperties) = reactiveWebApplication { with(configurationProperties(properties, prefix = "sample")) { enable(dataConfig(cassandraHost, cassandraPort)) enable(webConfig(serverPort)) } } fun main() { val cassandraContainer = CassandraContainer().withInitScript("schema.cql") cassandraContainer.start() val properties = ApplicationProperties( cassandraHost = cassandraContainer.containerIpAddress, cassandraPort = cassandraContainer.firstMappedPort) app(properties).run() }
46
null
139
1,673
c41806b1429dc31f75e2cb0f69ddd51a0bd8e9da
1,276
spring-fu
Apache License 2.0
src/test/kotlin/com/atlassian/performance/tools/virtualusers/LoadTestTerminationIT.kt
atlassian
172,478,035
false
{"Gradle Kotlin DSL": 2, "CODEOWNERS": 1, "Markdown": 4, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Text": 1, "XML": 1, "Dockerfile": 1, "Kotlin": 80, "Java": 1, "YAML": 1}
package com.atlassian.performance.tools.virtualusers import com.atlassian.performance.tools.jiraactions.api.ActionType import com.atlassian.performance.tools.jiraactions.api.SeededRandom import com.atlassian.performance.tools.jiraactions.api.WebJira import com.atlassian.performance.tools.jiraactions.api.action.Action import com.atlassian.performance.tools.jiraactions.api.measure.ActionMeter import com.atlassian.performance.tools.jiraactions.api.memories.UserMemory import com.atlassian.performance.tools.jiraactions.api.scenario.Scenario import com.atlassian.performance.tools.virtualusers.api.VirtualUserLoad import com.atlassian.performance.tools.virtualusers.api.VirtualUserOptions import com.atlassian.performance.tools.virtualusers.api.browsers.Browser import com.atlassian.performance.tools.virtualusers.api.browsers.CloseableRemoteWebDriver import com.atlassian.performance.tools.virtualusers.api.config.VirtualUserBehavior import com.atlassian.performance.tools.virtualusers.api.config.VirtualUserTarget import com.sun.net.httpserver.HttpHandler import com.sun.net.httpserver.HttpServer import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.openqa.selenium.remote.DesiredCapabilities import org.openqa.selenium.remote.RemoteWebDriver import java.net.InetSocketAddress import java.net.URI import java.time.Duration import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger import kotlin.system.measureTimeMillis class LoadTestTerminationIT { private val load = VirtualUserLoad.Builder() .virtualUsers(3) .hold(Duration.ZERO) .ramp(Duration.ZERO) .flat(Duration.ofSeconds(21)) .build() @Test fun shouldHaveReasonableOverheadDespiteSlowNavigations() { val loadTest = prepareLoadTest(SlowShutdownBrowser::class.java) val termination = testTermination(loadTest, "shouldHaveReasonableOverheadDespiteSlowNavigations") assertThat(termination.overhead).isLessThan(Duration.ofSeconds(2) + LoadSegment.DRIVER_CLOSE_TIMEOUT) assertThat(termination.blockingThreads).isEmpty() } @Test fun shouldCloseAFastBrowser() { val loadTest = prepareLoadTest(FastShutdownBrowser::class.java) val termination = testTermination(loadTest, "shouldCloseAFastBrowser") assertThat(termination.overhead).isLessThan(Duration.ofSeconds(2)) assertThat(CLOSED_BROWSERS).contains(FastShutdownBrowser::class.java) assertThat(termination.blockingThreads).isEmpty() } private fun prepareLoadTest( browser: Class<out Browser> ): LoadTest { val options = VirtualUserOptions( target = VirtualUserTarget( webApplication = URI("http://doesnt-matter"), userName = "u", password = "p" ), behavior = VirtualUserBehavior.Builder(NavigatingScenario::class.java) .skipSetup(true) .browser(browser) .load(load) .build() ) return LoadTest( options = options, userGenerator = SuppliedUserGenerator() ) } private fun testTermination( test: LoadTest, label: String ): TerminationResult { val threadGroup = ThreadGroup(label) val threadName = "parent-for-$label" val testDuration = measureTimeMillis { Executors.newSingleThreadExecutor { Thread(threadGroup, it, threadName) }.submit { test.run() }.get() } Thread.sleep(200) // give the threads from the [test] a chance to die return TerminationResult( overhead = Duration.ofMillis(testDuration) - load.total, blockingThreads = threadGroup.listBlockingThreads().filter { it.name != threadName } ) } private class TerminationResult( val overhead: Duration, /** * If you want to find out who created these threads, you can debug with a breakpoint on [Thread.start] * and filter e.g. by [Thread.getName]. */ val blockingThreads: List<Thread> ) private fun ThreadGroup.listBlockingThreads(): List<Thread> { return listThreads().filter { it.isDaemon.not() } } private fun ThreadGroup.listThreads(): List<Thread> { val threads = Array<Thread?>(activeCount()) { null } enumerate(threads) return threads.toList().filterNotNull().filter { it.isAlive } } } private val CLOSED_BROWSERS: MutableList<Class<*>> = mutableListOf() private class SlowShutdownBrowser : SlowNavigationBrowser() { override val shutdown: Duration = Duration.ofSeconds(120) } private class FastShutdownBrowser : SlowNavigationBrowser() { override val shutdown: Duration = Duration.ofMillis(500) } private abstract class SlowNavigationBrowser : Browser { private val navigation: Duration = Duration.ofSeconds(10) abstract val shutdown: Duration override fun start(): CloseableRemoteWebDriver { val browserPort = 8500 + PORT_OFFSET.getAndIncrement() val browser = MockHttpServer(browserPort, shutdown) browser.register("/session", HttpHandler { http -> val sessionResponse = """ { "value": { "sessionId": "123", "capabilities": {} } } """.trimIndent() http.sendResponseHeaders(200, sessionResponse.length.toLong()) http.responseBody.bufferedWriter().use { it.write(sessionResponse) } http.close() }) browser.register("/session/123/url", HttpHandler { http -> Thread.sleep(navigation.toMillis()) http.sendResponseHeaders(200, 0) http.close() }) val startedBrowser = browser.start() val driver = RemoteWebDriver(browser.base.toURL(), DesiredCapabilities()) val clazz = this::class.java return object : CloseableRemoteWebDriver(driver) { override fun close() { super.close() startedBrowser.close() CLOSED_BROWSERS.add(clazz) } } } private companion object { val PORT_OFFSET = AtomicInteger(0) } } private class MockHttpServer( private val port: Int, private val shutdownSlowness: Duration ) { private val handlers: MutableMap<String, HttpHandler> = mutableMapOf() internal val base = URI("http://localhost:$port") internal fun register( context: String, handler: HttpHandler ): URI { handlers[context] = handler return base.resolve(context) } internal fun start(): AutoCloseable { val executorService: ExecutorService = Executors.newCachedThreadPool { Thread(it) .apply { name = "mock-http" } .apply { isDaemon = true } } val server = startHttpServer(executorService) return AutoCloseable { executorService.shutdownNow() Thread.sleep(shutdownSlowness.toMillis()) server.stop(0) } } private fun startHttpServer(executor: ExecutorService): HttpServer { val httpServer = HttpServer.create(InetSocketAddress(port), 0) httpServer.executor = executor handlers.forEach { (context, handler) -> httpServer.createContext(context).handler = handler } executor .submit { httpServer.start() } .get() return httpServer } } private class NavigatingScenario : Scenario { override fun getLogInAction( jira: WebJira, meter: ActionMeter, userMemory: UserMemory ): Action = object : Action { override fun run() {} } override fun getActions( jira: WebJira, seededRandom: SeededRandom, meter: ActionMeter ): List<Action> = listOf( object : Action { private val navigation = ActionType("Navigation") { Unit } override fun run() { meter.measure(navigation) { jira.navigateTo("whatever") } } } ) }
1
null
1
1
c1e8d65595c1482bd9b51a5fb980a30d5a4b3f60
8,395
virtual-users
Apache License 2.0
ktor-client/ktor-client-features/ktor-client-auth/jvm/test/DigestTest.kt
LloydFinch
166,520,021
false
null
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ import io.ktor.application.* import io.ktor.auth.* import io.ktor.client.features.auth.Auth import io.ktor.client.features.auth.providers.* import io.ktor.client.request.* import io.ktor.client.response.* import io.ktor.client.tests.utils.* import io.ktor.http.isSuccess import io.ktor.response.* import io.ktor.routing.* import io.ktor.server.cio.CIO import io.ktor.server.engine.* import org.junit.* import java.security.* class DigestTest : TestWithKtor() { override val server: ApplicationEngine = embeddedServer(CIO, serverPort) { install(Authentication) { digest("digest") { val password = "<PASSWORD>" algorithmName = "MD5" realm = "<EMAIL>" digestProvider { userName, realm -> digest(MessageDigest.getInstance(algorithmName), "$userName:$realm:$password") } } basic("basic") { validate { credential -> check("MyUser" == credential.name) check("1234" == credential.password) UserIdPrincipal("MyUser") } } } routing { authenticate("basic") { get("/basic") { call.respondText("ok") } } authenticate("digest") { get("/digest") { call.respondText("ok") } } } } @Test fun testDigestAuth() = clientTest(io.ktor.client.engine.cio.CIO) { config { install(Auth) { digest { username = "MyName" password = "<PASSWORD>" realm = "<EMAIL>" } } } test { client -> client.get<HttpResponse>(path = "/digest", port = serverPort).use { assert(it.status.isSuccess()) } } } @Test fun testBasicAuth(): Unit = clientTest(io.ktor.client.engine.cio.CIO) { config { install(Auth) { basic { username = "MyUser" password = "<PASSWORD>" } } } test { client -> client.get<String>(path = "/basic", port = serverPort) } } private fun digest(digester: MessageDigest, data: String): ByteArray { digester.reset() digester.update(data.toByteArray(Charsets.ISO_8859_1)) return digester.digest() } }
0
null
0
2
9b9fc6c3b853c929a806c65cf6bf7c104b4c07fc
2,721
ktor
Apache License 2.0
server-core/src/main/kotlin/com/lightningkite/lightningserver/websocket/WebSocketIdentifierSerializer.kt
lightningkite
512,032,499
false
{"Kotlin": 2353225, "TypeScript": 38628, "JavaScript": 118}
package com.lightningkite.lightningserver.websocket import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder object WebSocketIdentifierSerializer : KSerializer<WebSocketIdentifier> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("WebSocketIdentifier", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): WebSocketIdentifier = WebSocketIdentifier(decoder.decodeString()) override fun serialize(encoder: Encoder, value: WebSocketIdentifier) { encoder.encodeString(value.string) } }
1
Kotlin
1
5
f404cc57cbdbe2a90b4e59d4ecd5ad22e008a730
799
lightning-server
Apache License 2.0
components/src/main/kotlin/com/exyui/android/debugbottle/components/widgets/__FloatAnimatedDialog.kt
knowingman
71,956,841
true
{"Kotlin": 430762, "Java": 11466, "Shell": 1481}
package com.exyui.android.debugbottle.components.widgets import android.app.Dialog import android.app.DialogFragment import android.app.FragmentManager import android.os.Bundle import android.view.* import com.exyui.android.debugbottle.components.R /** * Created by yuriel on 9/26/16. */ abstract class __FloatAnimatedDialog : DialogFragment() { protected abstract val TAG: String protected abstract val title: Int override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val result = Dialog(activity) result.window.requestFeature(Window.FEATURE_NO_TITLE) result.setContentView(createView()) return result } override fun onStart() { super.onStart() dialog.window.attributes.gravity = Gravity.TOP dialog.window.attributes.width = WindowManager.LayoutParams.MATCH_PARENT dialog.window.attributes.height = WindowManager.LayoutParams.WRAP_CONTENT dialog.window.attributes.windowAnimations = R.style.__DialogAnimation dialog.window.setBackgroundDrawableResource(android.R.color.transparent) /** THIS WILL ADD AN ANIMATION WITH DIALOG APPEARANCE //Grab the window of the dialog, and change the width val lp = WindowManager.LayoutParams() val window = dialog.window lp.copyFrom(window.attributes) //This makes the dialog take up the full width lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT window.attributes = lp val attr = dialog.window.attributes attr.gravity = Gravity.TOP attr.flags = attr.flags and WindowManager.LayoutParams.FLAG_DIM_BEHIND.inv() window.attributes.gravity = Gravity.TOP val decorView = dialog.window.decorView val scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView, PropertyValuesHolder.ofFloat("scaleX", 0.0f, 1.0f), PropertyValuesHolder.ofFloat("scaleY", 0.0f, 1.0f), PropertyValuesHolder.ofFloat("alpha", 0.0f, 1.0f)) scaleDown.duration = animationDuration scaleDown.start() */ } override fun dismiss() { /** THIS WILL ADD AN ANIMATION WITH DIALOG DISMISS val decorView = dialog.window.decorView val scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView, PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.0f), PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.0f), PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f)) scaleDown.addListener(object : Animator.AnimatorListener { override fun onAnimationEnd(animation: Animator) { super@__FloatAnimatedDialog.dismiss() } override fun onAnimationStart(animation: Animator) { } override fun onAnimationCancel(animation: Animator) { } override fun onAnimationRepeat(animation: Animator) { } }) scaleDown.duration = animationDuration scaleDown.start() */ super.dismiss() } fun show(fm: FragmentManager) { show(fm, TAG) } abstract fun createView(): View }
0
Kotlin
0
1
d02988b0de207ea3f616221d1c5ffea310628736
3,265
debug-bottle
Apache License 2.0
app/src/main/kotlin/com/fibelatti/pinboard/features/tags/presentation/TagListLayout.kt
fibelatti
165,537,939
false
null
package com.fibelatti.pinboard.features.tags.presentation import android.animation.LayoutTransition import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.LinearLayout import androidx.core.view.isVisible import androidx.core.widget.doAfterTextChanged import com.fibelatti.core.extension.clearText import com.fibelatti.core.extension.gone import com.fibelatti.core.extension.hideKeyboard import com.fibelatti.core.extension.visible import com.fibelatti.pinboard.R import com.fibelatti.pinboard.databinding.LayoutTagListBinding import com.fibelatti.pinboard.features.tags.domain.model.Tag import com.fibelatti.pinboard.features.tags.domain.model.TagSorting class TagListLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { private val binding = LayoutTagListBinding.inflate(LayoutInflater.from(context), this) private var tagsAdapter: TagsAdapter? = null val isInputFocused: Boolean get() = binding.editTextTagFilter.isFocused init { orientation = VERTICAL layoutTransition = LayoutTransition().apply { enableTransitionType(LayoutTransition.CHANGE_APPEARING) enableTransitionType(LayoutTransition.CHANGE_DISAPPEARING) } binding.editTextTagFilter.doAfterTextChanged { tagsAdapter?.filter(query = it.toString()) } } fun setAdapter(adapter: TagsAdapter, onClickListener: (Tag) -> Unit = {}) { tagsAdapter = adapter adapter.onItemClicked = onClickListener binding.recyclerViewTags.adapter = adapter } fun setOnRefreshListener(onRefresh: () -> Unit) { binding.swipeToRefresh.setOnRefreshListener { binding.swipeToRefresh.isRefreshing = false onRefresh() } } fun setSortingClickListener(onSortingSelected: (List<Tag>, TagSorting) -> Unit) { binding.buttonTagSortingAtoZ.isChecked = true binding.buttonTagSortingAtoZ.setOnClickListener { binding.buttonTagSortingAtoZ.isChecked = true onModeSelected(onSortingSelected, TagSorting.AtoZ, filterVisible = false) } binding.buttonTagSortingMoreFirst.setOnClickListener { binding.buttonTagSortingMoreFirst.isChecked = true onModeSelected(onSortingSelected, TagSorting.MoreFirst, filterVisible = false) } binding.buttonTagSortingLessFirst.setOnClickListener { binding.buttonTagSortingLessFirst.isChecked = true onModeSelected(onSortingSelected, TagSorting.LessFirst, filterVisible = false) } binding.buttonTagSortingFilter.setOnClickListener { binding.buttonTagSortingFilter.isChecked = true onModeSelected(onSortingSelected, TagSorting.AtoZ, filterVisible = true) } } private fun onModeSelected( onSortingSelected: (List<Tag>, TagSorting) -> Unit, tagSorting: TagSorting, filterVisible: Boolean, ) { if (!filterVisible) { binding.root.hideKeyboard() binding.editTextTagFilter.clearText() } binding.textInputLayoutTagFilter.isVisible = filterVisible binding.recyclerViewTags.scrollToPosition(0) tagsAdapter?.let { onSortingSelected(it.getItems(), tagSorting) } } fun setInputFocusChangeListener(onInputFocused: (hasFocus: Boolean) -> Unit) { binding.editTextTagFilter.setOnFocusChangeListener { _, hasFocus -> onInputFocused(hasFocus) } } fun showLoading() { binding.progressBar.visible() binding.buttonGroupTagSorting.gone() binding.recyclerViewTags.gone() binding.layoutEmptyList.gone() } fun showTags(list: List<Tag>) { if (list.isNotEmpty()) { binding.buttonGroupTagSorting.visible() binding.recyclerViewTags.visible() binding.layoutEmptyList.gone() tagsAdapter?.submitList(list) val currentFilter = binding.editTextTagFilter.text.toString() if (currentFilter.isNotBlank()) { tagsAdapter?.filter(query = currentFilter) } } else { showEmptyLayout() } binding.progressBar.gone() } private fun showEmptyLayout() { binding.buttonGroupTagSorting.gone() binding.recyclerViewTags.gone() binding.layoutEmptyList.apply { setIcon(R.drawable.ic_tag) setTitle(R.string.tags_empty_title) setDescription(R.string.tags_empty_description) visible() } } fun getCurrentTagSorting(): TagSorting = when (binding.buttonGroupTagSorting.checkedButtonId) { R.id.buttonTagSortingMoreFirst -> TagSorting.MoreFirst R.id.buttonTagSortingLessFirst -> TagSorting.LessFirst else -> TagSorting.AtoZ } }
3
null
8
87
c10e57a97d4123be72fff7bbc4ac444b55b23bb7
4,986
pinboard-kotlin
Apache License 2.0
android/app/src/main/java/com/fabirt/roka/di/AppModule.kt
fabirt
282,489,397
false
null
package com.fabirt.roka.di import android.content.Context import com.fabirt.roka.core.data.database.AppDatabase import com.fabirt.roka.core.data.network.client.RecipesApiClient import com.fabirt.roka.core.data.network.services.RecipeService import com.fabirt.roka.core.data.network.services.RecipeServiceFakeImpl import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Singleton @Module @InstallIn(ApplicationComponent::class) object AppModule { @Provides @Singleton fun provideRecipeService(): RecipeService = RecipesApiClient.createRecipeService() @Provides @Singleton fun provideDatabase( @ApplicationContext context: Context ) = AppDatabase.createDatabase(context) @Provides @Singleton fun provideRecipeDao(database: AppDatabase) = database.recipeDao() }
0
Kotlin
14
62
f52145b2d3551b72e9478faef7d38bdfbb5aee8e
964
roka-recipe-app
MIT License
app/src/main/java/com/tandurteam/tandur/core/model/network/myplant/response/myplantlist/MyPlantListData.kt
Tandur-Team
490,700,073
false
null
package com.tandurteam.tandur.core.model.network.myplant.response.myplantlist import com.google.gson.annotations.SerializedName data class MyPlantListData( @SerializedName("_id") val id: String?, @SerializedName("is_harvested") val isHarvested: Int?, @SerializedName("plant_harvest_date") val plantHarvestDate: String?, @SerializedName("plant_name") val plantName: String?, @SerializedName("plant_start_date") val plantStartDate: String?, @SerializedName("satisfaction_rate") val satisfactionRate: Int?, val userId: String?, @SerializedName("image_url") val imageUrl: String )
0
Kotlin
0
1
edc412f999c5a202ed2a3f4203f63a99b6262dce
638
tandur-android
MIT License
server/src/main/kotlin/io/github/alessandrojean/tankobon/infrastructure/web/StringToImporterSourceSetConverter.kt
alessandrojean
609,405,137
false
null
package io.github.alessandrojean.tankobon.infrastructure.web import io.github.alessandrojean.tankobon.infrastructure.importer.ImporterSource import org.springframework.core.convert.converter.Converter import org.springframework.stereotype.Component @Component class StringToImporterSourceSetConverter : Converter<String, Set<ImporterSource>> { override fun convert(source: String): Set<ImporterSource> { val types = ImporterSource.values() val sources = source.split(",") return types.filter { it.name.lowercase() in sources }.toSet() } }
0
Kotlin
0
1
cb28b68c0b6f3b1de7f77450122a609295396c28
558
tankobon
MIT License
python/src/com/jetbrains/python/codeInsight/mlcompletion/correctness/PythonMLCompletionCorrectnessSupporter.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.codeInsight.mlcompletion.correctness import com.intellij.lang.Language import com.intellij.platform.ml.impl.correctness.MLCompletionCorrectnessSupporter import com.jetbrains.python.PythonLanguage import com.jetbrains.python.codeInsight.mlcompletion.correctness.autoimport.PythonImportFixer import com.jetbrains.python.codeInsight.mlcompletion.correctness.checker.PythonCorrectnessChecker class PythonMLCompletionCorrectnessSupporter : MLCompletionCorrectnessSupporter { override val correctnessChecker: PythonCorrectnessChecker = PythonCorrectnessChecker() override val importFixer: PythonImportFixer = PythonImportFixer() override fun isLanguageSupported(language: Language): Boolean { return language.isKindOf(PythonLanguage.INSTANCE) || language.displayName != "Jupyter" } }
251
null
5079
16,158
831d1a4524048aebf64173c1f0b26e04b61c6880
943
intellij-community
Apache License 2.0
app/src/main/java/com/example/burutoapp/domain/models/OnBoarding.kt
Mzazi25
528,442,786
false
{"Kotlin": 130574}
package com.example.burutoapp.domain.models import androidx.annotation.DrawableRes import com.example.burutoapp.R sealed class OnBoarding( @DrawableRes val image:Int, val title: String, val description: String ){ object First: OnBoarding( image = R.drawable.greetings, title = "Greetings", description = "Are you a <NAME>? Because if you are then we have great news for you!" ) object Second: OnBoarding( image = R.drawable.explore, title = "Explore", description = "Find your favourite heroes and learn some of the things you didn't know about" ) object Third: OnBoarding( image = R.drawable.power, title = "Power", description = "Check out your Heroes Power and see how much strong they are compared to others" ) }
0
Kotlin
0
2
849814c25164d23352eb066c3e361700f5b64919
831
BorutoApp
The Unlicense
app/src/main/java/com/chittchorefsm/features/viewAllOrder/interf/NewOrderSizeQtyDelOnClick.kt
DebashisINT
533,183,419
false
{"Kotlin": 11200956, "Java": 960181}
package com.chittchorefsm.features.viewAllOrder.interf import com.chittchorefsm.app.domain.NewOrderGenderEntity import com.chittchorefsm.features.viewAllOrder.model.ProductOrder import java.text.FieldPosition interface NewOrderSizeQtyDelOnClick { fun sizeQtySelListOnClick(product_size_qty: ArrayList<ProductOrder>) fun sizeQtyListOnClick(product_size_qty: ProductOrder,position: Int) }
0
Kotlin
0
0
dfdfafd5c35ebf69c1606fcf84af819079e25fb9
396
Chittchore
Apache License 2.0
app/src/main/java/com/chittchorefsm/features/viewAllOrder/interf/NewOrderSizeQtyDelOnClick.kt
DebashisINT
533,183,419
false
{"Kotlin": 11200956, "Java": 960181}
package com.chittchorefsm.features.viewAllOrder.interf import com.chittchorefsm.app.domain.NewOrderGenderEntity import com.chittchorefsm.features.viewAllOrder.model.ProductOrder import java.text.FieldPosition interface NewOrderSizeQtyDelOnClick { fun sizeQtySelListOnClick(product_size_qty: ArrayList<ProductOrder>) fun sizeQtyListOnClick(product_size_qty: ProductOrder,position: Int) }
0
Kotlin
0
0
dfdfafd5c35ebf69c1606fcf84af819079e25fb9
396
Chittchore
Apache License 2.0
js/js.translator/testData/reservedWords/cases/localVarLet.kt
msdgwzhy6
51,743,245
true
{"Markdown": 33, "XML": 665, "Ant Build System": 45, "Ignore List": 7, "Git Attributes": 1, "Kotlin": 20967, "Java": 4534, "Protocol Buffer": 7, "Text": 4663, "JavaScript": 63, "JAR Manifest": 3, "Roff": 46, "Roff Manpage": 11, "INI": 17, "HTML": 152, "Groovy": 23, "Java Properties": 14, "Maven POM": 49, "Gradle": 74, "CSS": 2, "Proguard": 1, "JFlex": 2, "Shell": 11, "Batchfile": 10, "ANTLR": 1}
package foo // NOTE THIS FILE IS AUTO-GENERATED by the generateTestDataForReservedWords.kt. DO NOT EDIT! fun box(): String { var let: Int = 0 testRenamed("let", { let }) return "OK" }
0
Java
0
1
f713adc96e9adeacb1373fc170a5ece1bf2fc1a2
199
kotlin
Apache License 2.0
feature/auth/src/main/java/com/flexcode/wedate/auth/presentation/profile_images_screen/ProfileImageState.kt
Felix-Kariuki
588,745,399
false
null
/* * Copyright 2023 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.flexcode.wedate.auth.presentation.profile_images_screen import com.flexcode.wedatecompose.network.data.models.auth.User data class ProfileImageState( val isLoading: String = "false", val userDetails: User? = null )
14
null
1
9
20a9b38cb4ae45572a248f819eca775e2d2f2678
829
Mingle
Apache License 2.0
ses-plugin-server/src/main/kotlin/jetbrains/buildServer/sesPlugin/teamcity/ui/EditSQSAjaxController.kt
JetBrains
105,000,686
false
{"Kotlin": 153538, "Java": 9533, "JavaScript": 6552, "CSS": 57}
package jetbrains.buildServer.sesPlugin.teamcity.ui import com.google.common.annotations.VisibleForTesting import jetbrains.buildServer.controllers.BaseController import jetbrains.buildServer.controllers.BasePropertiesBean import jetbrains.buildServer.serverSide.auth.Permission import jetbrains.buildServer.sesPlugin.data.AjaxRequestResult import jetbrains.buildServer.sesPlugin.teamcity.ui.ajax.AjaxRequest import jetbrains.buildServer.sesPlugin.teamcity.util.GsonView import jetbrains.buildServer.sesPlugin.teamcity.util.PluginPropertiesUtil import jetbrains.buildServer.sesPlugin.teamcity.util.SessionUserProvider import jetbrains.buildServer.web.openapi.WebControllerManager import org.springframework.web.servlet.ModelAndView import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class EditSQSAjaxController(private val ajaxRequests: List<AjaxRequest>, private val webControllerManager: WebControllerManager, private val sessionUserProvider: SessionUserProvider) : BaseController() { companion object { val URL = "/admin/editSQSParams.html" } fun init() { webControllerManager.registerController(URL, this) } @VisibleForTesting public override fun doHandle(request: HttpServletRequest, response: HttpServletResponse): ModelAndView { val modelAndView = ModelAndView(GsonView()) val user = sessionUserProvider.getUser(request) if (user == null) { modelAndView.model.put("result", AjaxRequestResult(false, "No user found")) return modelAndView } if (!user.isPermissionGrantedGlobally(Permission.CHANGE_SERVER_SETTINGS)) { modelAndView.model.put("result", AjaxRequestResult(false, "Not enough permissions")) return modelAndView } val res = doHandleInternal(request, response) modelAndView.model.put("result", res) return modelAndView } private fun doHandleInternal(request: HttpServletRequest, response: HttpServletResponse): AjaxRequestResult { val type = request.getParameter("type") ?: return AjaxRequestResult(false, "No action type provided") return ajaxRequests.find { it.id == type }?.let { val bean = BasePropertiesBean(HashMap()) PluginPropertiesUtil.bindPropertiesFromRequest(request, bean, true) return@let it.handle(bean) } ?: AjaxRequestResult(false, "Unknown action $type") } }
4
Kotlin
4
2
defc95b475b7971ca29a43beddc31d08ff96269f
2,553
TeamCity.SESPlugin
Apache License 2.0
src/main/java/net/oxyopia/vice/features/cooking/CookingAPI.kt
Oxyopiia
689,119,282
false
null
package net.oxyopia.vice.features.cooking import net.oxyopia.vice.Vice import net.oxyopia.vice.config.features.worlds.CookingStorage import net.oxyopia.vice.data.World import net.oxyopia.vice.events.ChatEvent import net.oxyopia.vice.events.TitleEvent import net.oxyopia.vice.events.core.SubscribeEvent import net.oxyopia.vice.utils.DevUtils import net.oxyopia.vice.utils.Utils import net.oxyopia.vice.utils.TimeUtils.timeDelta import kotlin.time.Duration.Companion.seconds object CookingAPI { private val cooking: CookingStorage get() = Vice.storage.cooking val currentOrder: CookingOrder get() = CookingOrder.getByName(cooking.currentOrder) ?: CookingOrder.NONE val orderCurrentItemIndex get() = cooking.currentOrderProgress val stock: Int get() = cooking.stock var heldItem = CookingItem.NONE private var lastSeenNewOrder = 0L private val heldItemRegex by lazy { Regex("You are currently holding (?:a |an )?(.*)") } private val ingredientsRegex by lazy { Regex("(\\d+) Ingredients Left") } private val stockRegex by lazy { Regex("Your current stock is (\\d+)/\\d+") } private fun updateOrder(order: CookingOrder) { cooking.currentOrder = order.displayName cooking.currentOrderProgress = 0 if (order != CookingOrder.NONE) { cooking.totalBurgerRequests[order.name] = cooking.totalBurgerRequests.getOrDefault(order.name, 0) + 1 } Vice.storage.markDirty() DevUtils.sendDebugChat("&&6COOKING &&rUpdated current order to &&e${currentOrder.name}", "COOKING_DEBUGGER") } @SubscribeEvent fun onTitle(event: TitleEvent) { if (event.title.contains("+1 Stock")) { cooking.stock += 1 Vice.storage.markDirty() } } @SubscribeEvent fun onChatMessage(event: ChatEvent) { if (!World.Burger.isInWorld()) return val content = event.string val hideHandledMessages = Vice.config.HIDE_HANDLED_COOKING_MESSAGES when { content.contains("NEW ORDER") || content.contains("BOSS ORDER") -> { lastSeenNewOrder = System.currentTimeMillis() } lastSeenNewOrder.timeDelta() <= 1.seconds -> { val order = CookingOrder.getByName(content) ?: return updateOrder(order) } content.contains("Order Complete") || content.contains("Incorrect Ingredient ") -> { if (content.contains("Order Complete")) { cooking.totalBurgersComplete[currentOrder.name] = cooking.totalBurgersComplete.getOrDefault(currentOrder.name, 0) + 1 } updateOrder(CookingOrder.NONE) if (!Vice.config.AUTO_APPLY_BREAD) heldItem = CookingItem.NONE } heldItemRegex.find(content.removeSuffix(".")) != null -> { val match = heldItemRegex.find(content.removeSuffix("."))?.groupValues?.get(1) heldItem = CookingItem.getByName(match.toString()) ?: CookingItem.NONE DevUtils.sendDebugChat("&&6COOKING &&rUpdated held item to &&d${heldItem.name}", "COOKING_DEBUGGER") if (hideHandledMessages) { event.cancel() if (heldItem == CookingItem.COOKED_MEAT) { Utils.playSound("block.note_block.pling", pitch = 1.5f, volume = 3f) BurgerTimer.cooking = null } } } ingredientsRegex.find(content) != null -> { val ingredientsRemaining = ingredientsRegex.find(content)?.groupValues?.get(1)?.toIntOrNull() ?: return if (currentOrder != CookingOrder.NONE && ingredientsRemaining > 0) { cooking.currentOrderProgress = currentOrder.recipe.size - ingredientsRemaining Vice.storage.markDirty() DevUtils.sendDebugChat("&&6COOKING &&rNext Item: ${currentOrder.recipe[orderCurrentItemIndex]}", "COOKING_DEBUGGER") } if (hideHandledMessages) event.cancel() } stockRegex.find(content) != null -> { val stockValue = stockRegex.find(content)?.groupValues?.get(1)?.toIntOrNull() ?: return cooking.stock = stockValue Vice.storage.markDirty() DevUtils.sendDebugChat("&&6COOKING &&rUpdated Stock to $stock", "COOKING_DEBUGGER") if (hideHandledMessages) event.cancel() } } } }
6
null
1
2
e9aa1527b093391b8b418a9e53acc2e83aab529b
3,909
ViceMod
MIT License
markup/core/src/commonMain/kotlin/raven/Html.kt
aSoft-Ltd
849,606,763
false
{"Kotlin": 62632, "HTML": 24145}
package raven class Html( val lang: String, val dir: String, val head: Head, val body: Body ) class HtmlScope { internal var head = Head(mutableListOf(), mutableListOf()) internal var body = Body(mutableMapOf(), mutableListOf()) fun head(builder: HeadScope.() -> Unit): Head { val scope = HeadScope(head) scope.builder() return head } fun body(styles: Styles = css(), builder: ComponentScope<Body>.() -> Unit): Body { val default = css().width("100%").margin("0").padding("0") body.styles.putAll((default + styles).definitions) return scopeOf(body).also(builder).parent } }
0
Kotlin
0
0
b2feaf2166e65b7f8c2a0269c179480975223e19
664
raven-core
MIT License
components/data-support/src/main/kotlin/io/newsanalyzer/datasupport/DatabaseTemplate.kt
tyknkd
756,621,540
false
{"Kotlin": 92477, "FreeMarker": 4724, "Shell": 2140, "Dockerfile": 2067, "CSS": 1818}
package io.newsanalyzer.datasupport import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.* import com.zaxxer.hikari.* open class DatabaseTemplate(dbName: String, tables: List<Table>) { var database: Database init { val driverClassName = "org.postgresql.Driver" val port = System.getenv("POSTGRES_PORT") val host = if (System.getenv("OS_ENV") == "container") { System.getenv("POSTGRES_HOST") } else { "localhost" } val password = System.getenv("POSTGRES_PASSWORD") if (password == null || password == "") { throw RuntimeException("Database password environment variable 'POSTGRES_PASSWORD' is empty or missing") } val user = System.getenv("POSTGRES_USER") val jdbcUrl = "jdbc:postgresql://$host:$port/$dbName?reWriteBatchedInserts=true" database = Database.connect( createHikariDataSource( url = jdbcUrl, driver = driverClassName, user = user, passwd = password) ) transaction(database) { for (table in tables) { SchemaUtils.create(table) } } } private fun createHikariDataSource(url: String, driver: String, user: String, passwd: String) = HikariDataSource(HikariConfig().apply { jdbcUrl = url driverClassName = driver username = user password = <PASSWORD> maximumPoolSize = 3 isAutoCommit = false transactionIsolation = "TRANSACTION_REPEATABLE_READ" validate() }) }
0
Kotlin
0
0
e2315aafc13a7eaad70540ab7c5b6b58a2a4f6fc
1,806
news-analyzer
FSF All Permissive License
dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/predicate/range/BetweenRangeSpecificationUnitTests.kt
lucasdillmann
766,655,271
false
{"Kotlin": 343330, "ANTLR": 1950}
package br.com.dillmann.dynamicquery.specification.predicate.range import br.com.dillmann.dynamicquery.specification.parameter.Parameter import io.mockk.every import io.mockk.mockk import io.mockk.verify import jakarta.persistence.criteria.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import kotlin.test.assertEquals /** * [BetweenRangeSpecification] unit tests */ class BetweenRangeSpecificationUnitTests { private val attributeName = mockk<Parameter>() private val startValue = mockk<Parameter>() private val endValue = mockk<Parameter>() private val startExpression = mockk<Expression<String>>() private val endExpression = mockk<Expression<String>>() private val path = mockk<Expression<String>>() private val root = mockk<Root<Any>>() private val query = mockk<CriteriaQuery<Any>>() private val builder = mockk<CriteriaBuilder>() private val predicate = mockk<Predicate>() private val specification = BetweenRangeSpecification(attributeName, startValue, endValue) @BeforeEach fun setUp() { every { attributeName.asExpression(any(), any(), any()) } returns path every { startValue.asExpression(any(), any(), any(), any<Class<String>>()) } returns startExpression every { endValue.asExpression(any(), any(), any(), any<Class<String>>()) } returns endExpression every { path.javaType } returns String::class.java every { builder.between(any<Expression<String>>(), any<Expression<String>>(), any<Expression<String>>()) } returns predicate } @Test fun `toPredicate should resolve and use the target using the given Parameter`() { // execution specification.toPredicate(root, query, builder) // validation verify { attributeName.asExpression(root, query, builder) } verify { builder.between(path, any<Expression<String>>(), any<Expression<String>>()) } } @Test fun `toPredicate should parse the start value to the target type using the given Parameter`() { // execution specification.toPredicate(root, query, builder) // validation verify { startValue.asExpression(root, query, builder, String::class.java) } verify { builder.between(any<Expression<String>>(), startExpression, any<Expression<String>>()) } } @Test fun `toPredicate should parse the end value to the target type using the given Parameter`() { // execution specification.toPredicate(root, query, builder) // validation verify { endValue.asExpression(root, query, builder, String::class.java) } verify { builder.between(any<Expression<String>>(), any<Expression<String>>(), endExpression) } } @Test fun `toPredicate should create and return the expected predicate`() { // execution val result = specification.toPredicate(root, query, builder) // validation assertEquals(predicate, result) } }
0
Kotlin
0
1
e30e8b3d26cc2f23c976f73207bf7a7e7fbb91ad
2,997
dynamic-query
MIT License
src/main/kotlin/org/itaya/pixiv/basic/ability/process/piece/save/IMGSaveStep.kt
Ita-Ya
704,809,151
false
{"Kotlin": 48081, "Assembly": 811}
package org.kyaru.pixiv.basic.ability.process.piece.save import org.kyaru.pixiv.basic.item.Artwork import java.io.IOException import java.nio.file.Path import javax.imageio.ImageIO class IMGSaveStep : SaveStep() { override fun store(targetDir: Path, artwork: Artwork): List<Path> { return ArrayList<Path>().apply { for ((index, fileName) in artwork.fileNames.withIndex()) { try { val image = artwork.images[index] val suffix = fileName.substring(fileName.length - 3) Path.of(targetDir.toString(), fileName).let { it.toFile().createNewFile() ImageIO.write(image, suffix, it.toFile()) add(it) } } catch (e: IOException) { throw RuntimeException(e) } } } } }
0
Kotlin
0
0
13a768073b98ba9393e22ad698fde33ebafb3668
889
pixiv-artists-api
MIT License
feature/profile/src/main/kotlin/team/duckie/app/android/feature/profile/viewmodel/state/ProfileState.kt
duckie-team
503,869,663
false
null
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ package team.duckie.app.android.feature.profile.viewmodel.state import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import team.duckie.app.android.domain.user.model.User import team.duckie.app.android.domain.user.model.UserProfile import team.duckie.app.android.feature.profile.dummy.skeletonUserProfile import team.duckie.app.android.common.compose.ui.dialog.DuckieSelectableType data class ProfileState( val isLoading: Boolean = true, val isError: Boolean = false, val userProfile: UserProfile = skeletonUserProfile(), val me: User? = null, val isMe: Boolean = false, val reportDialogVisible: Boolean = false, val follow: Boolean = false, val reportExamId: Int = 0, val userId: Int = 0, val bottomSheetDialogType: ImmutableList<DuckieSelectableType> = persistentListOf(), val ignoreDialogVisible: Boolean = false, )
32
null
2
8
5dbd5b7a42c621931d05a96e66431f67a3a50762
1,098
duckie-android
MIT License
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/common/model/VersionedEntity.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.common.model import java.util.UUID interface VersionedEntity { val identifier: UUID? val version: Long? }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
370
bosch-pt-refinemysite-backend
Apache License 2.0
app/src/main/java/com/alirahimi/digikalaclone/viewmodel/ProfileViewModel.kt
Aliiiw
612,510,322
false
null
package com.alirahimi.digikalaclone.viewmodel import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.alirahimi.digikalaclone.data.model.basket.BasketDetail import com.alirahimi.digikalaclone.data.model.basket.BasketItem import com.alirahimi.digikalaclone.data.model.basket.CartStatus import com.alirahimi.digikalaclone.data.model.home.StoreProduct import com.alirahimi.digikalaclone.data.model.profile.LoginRequest import com.alirahimi.digikalaclone.data.model.profile.LoginResponse import com.alirahimi.digikalaclone.data.remote.NetworkResult import com.alirahimi.digikalaclone.repository.BasketRepository import com.alirahimi.digikalaclone.repository.ProfileRepository import com.alirahimi.digikalaclone.ui.screens.basket.BasketScreenState import com.alirahimi.digikalaclone.ui.screens.profile.ProfileScreenState import com.alirahimi.digikalaclone.util.DigitHelper.applyDiscount import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ProfileViewModel @Inject constructor(private val repository: ProfileRepository) : ViewModel() { var screenState by mutableStateOf(ProfileScreenState.LOGIN_STATE) var inputPhoneState by mutableStateOf("") var inputPasswordState by mutableStateOf("") val loginResponseFlow = MutableStateFlow<NetworkResult<LoginResponse>>(NetworkResult.Loading()) var loadingState by mutableStateOf(false) fun login() { viewModelScope.launch { loadingState = true val loginRequest = LoginRequest(phone = inputPhoneState, password = inputPasswordState) loginResponseFlow.emit(repository.login(loginRequest)) } } fun refreshToken(phone: String, password: String) { viewModelScope.launch { val loginRequest = LoginRequest(phone = phone, password = password) loginResponseFlow.emit(repository.login(loginRequest)) } } }
0
Kotlin
0
4
0e503827a19eb619c348dfcec1998afb1b00c1b9
2,284
Digikala-clone
MIT License
server/src/main/kotlin/com/sebastiansokolowski/auctionhunter/allegro_api/AuthInterceptor.kt
sebastiansokolowski
82,472,206
false
{"Java": 99429, "Kotlin": 56005, "JavaScript": 32024, "HTML": 3888, "CSS": 930}
package com.sebastiansokolowski.auctionhunter.allegro_api import com.sebastiansokolowski.auctionhunter.allegro_api.response.AuthResponse import com.sebastiansokolowski.auctionhunter.allegro_api.response.RefreshTokenResponse import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response class AuthInterceptor(clientId: String, clientSecret: String) : Interceptor { private val sessionManager = SessionManager() private val allegroAuthClient = AllegroAuthClient(clientId, clientSecret) override fun intercept(chain: Interceptor.Chain): Response { val requestBuilder = chain.request().newBuilder() if (sessionManager.isAuthTokenValid()) { sessionManager.fetchAuthToken()?.let { setAuthHeader(requestBuilder, it) } } else { var token: String? = null var expiresIn: Long? = null //oauth token-12 hours validity val authResponse = auth() if (authResponse != null) { token = authResponse.access_token expiresIn = authResponse.expires_in } //refresh token-3 months validity if (token != null) { val refreshTokenResponse = refreshToken(token) if (refreshTokenResponse != null) { token = refreshTokenResponse.refresh_token expiresIn = refreshTokenResponse.expires_in } } if (token != null && expiresIn != null) { sessionManager.saveAuthToken(token, expiresIn) setAuthHeader(requestBuilder, token) } } return chain.proceed(requestBuilder.build()) } private fun setAuthHeader(requestBuilder: Request.Builder, token: String) { requestBuilder.addHeader("Authorization", "Bearer $token") requestBuilder.addHeader("Accept", "application/vnd.allegro.public.v1+json") } private fun auth(): AuthResponse? { val response = allegroAuthClient.auth().execute() if (response.isSuccessful && response.body() != null) { return response.body() } return null } private fun refreshToken(token: String): RefreshTokenResponse? { val response = allegroAuthClient.refresh(token).execute() if (response.isSuccessful && response.body() != null) { return response.body() } return null } }
1
null
1
1
816c4397a002ea8898aec8cc898c9802077a2257
2,482
AuctionHunter---Allegro
Apache License 2.0
data/legacy/src/main/java/app/tivi/data/util/StoreExtensions.kt
chrisbanes
100,624,553
false
null
/* * Copyright 2020 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.tivi.data import com.dropbox.android.external.store4.Store import com.dropbox.android.external.store4.StoreResponse import com.dropbox.android.external.store4.fresh import com.dropbox.android.external.store4.get import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filterNot suspend inline fun <Key : Any, Output : Any> Store<Key, Output>.fetch( key: Key, forceFresh: Boolean = false, ): Output = when { // If we're forcing a fresh fetch, do it now forceFresh -> fresh(key) else -> get(key) } fun <T> Flow<StoreResponse<T>>.filterForResult(): Flow<StoreResponse<T>> = filterNot { it is StoreResponse.Loading || it is StoreResponse.NoNewData }
39
null
792
5,749
5dc4d831fd801afab556165d547042c517f98875
1,291
tivi
Apache License 2.0
src/main/kotlin/com/seko0716/springboot/starter/oauth2/social/domains/User.kt
Sergey34
127,253,488
false
{"Kotlin": 34421}
package com.seko0716.springboot.starter.oauth2.social.domains import com.seko0716.springboot.starter.oauth2.social.infrastructure.annotations.NoArgs import org.bson.types.ObjectId import javax.persistence.Entity import javax.persistence.Id import javax.persistence.ManyToMany @NoArgs @Entity data class User(@Id var id: ObjectId = ObjectId(), var socialAccountId: String, var login: String, var email: String? = null, var firstName: String? = null, var lastName: String? = null, var enabled: Boolean = true, @ManyToMany var roles: List<Role> = ArrayList(), val authServiceType: String = "BASE")
0
Kotlin
3
9
255c7c5ce34ab0ae03331126ff0344a4d131a688
724
spring-boot-starter-security-oauth-social
The Unlicense
app/src/main/java/com/myth/movieapp/presentation/di/RemoteDataModule.kt
MichaelGift
631,115,747
false
{"Kotlin": 23570}
package com.myth.movieapp.presentation.di import com.myth.movieapp.data.api.TMDBService import com.myth.movieapp.data.datasource.MovieRemoteDataSource import com.myth.movieapp.data.datasourceimplementation.MovieRemoteDataSourceImplementation import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class RemoteDataModule(private val apikey:String) { @Singleton @Provides fun providesMovieRemoteDataSource(tmdbService: TMDBService):MovieRemoteDataSource{ return MovieRemoteDataSourceImplementation( tmdbService, apikey ) } }
0
Kotlin
0
2
70ef3d4501a1b9c8b96092f364a7324955a6de71
608
Movie-Recommendations-App
Apache License 2.0
embrace-android-sdk/src/main/java/io/embrace/android/embracesdk/internal/payload/SpanMapper.kt
embrace-io
704,537,857
false
{"Kotlin": 3102378, "C": 189946, "Java": 179815, "C++": 13140, "CMake": 4188}
package io.embrace.android.embracesdk.internal.payload import io.embrace.android.embracesdk.arch.schema.AppTerminationCause import io.embrace.android.embracesdk.arch.schema.EmbType import io.embrace.android.embracesdk.arch.schema.ErrorCodeAttribute import io.embrace.android.embracesdk.internal.clock.millisToNanos import io.embrace.android.embracesdk.internal.spans.EmbraceSpanData import io.embrace.android.embracesdk.internal.spans.hasFixedAttribute import io.embrace.android.embracesdk.internal.spans.setFixedAttribute import io.embrace.android.embracesdk.internal.spans.toStatus import io.embrace.android.embracesdk.spans.EmbraceSpanEvent import io.opentelemetry.api.trace.SpanId import io.opentelemetry.api.trace.StatusCode internal fun EmbraceSpanData.toNewPayload() = Span( traceId = traceId, spanId = spanId, parentSpanId = parentSpanId, name = name, startTimeUnixNano = startTimeNanos, endTimeUnixNano = endTimeNanos, status = status.toStatus(), events = events.map(EmbraceSpanEvent::toNewPayload), attributes = attributes.toNewPayload() ) internal fun EmbraceSpanEvent.toNewPayload() = SpanEvent( name = name, timeUnixNano = timestampNanos, attributes = attributes.toNewPayload() ) internal fun SpanEvent.toOldPayload() = EmbraceSpanEvent( name = name ?: "", timestampNanos = timeUnixNano ?: 0, attributes = attributes?.toOldPayload() ?: emptyMap() ) internal fun Map<String, String>.toNewPayload(): List<Attribute> = map { (key, value) -> Attribute(key, value) } internal fun List<Attribute>.toOldPayload(): Map<String, String> = associate { Pair(it.key ?: "", it.data ?: "") }.filterKeys { it.isNotBlank() } internal fun Span.toOldPayload(): EmbraceSpanData { return EmbraceSpanData( traceId = traceId ?: "", spanId = spanId ?: "", parentSpanId = parentSpanId ?: SpanId.getInvalid(), name = name ?: "", startTimeNanos = startTimeUnixNano ?: 0, endTimeNanos = endTimeUnixNano ?: 0L, status = when (status) { Span.Status.UNSET -> StatusCode.UNSET Span.Status.OK -> StatusCode.OK Span.Status.ERROR -> StatusCode.ERROR else -> StatusCode.UNSET }, events = events?.map { it.toOldPayload() } ?: emptyList(), attributes = attributes?.toOldPayload() ?: emptyMap() ) } internal fun EmbraceSpanData.toFailedSpan(endTimeMs: Long): EmbraceSpanData { val newAttributes = mutableMapOf<String, String>().apply { setFixedAttribute(ErrorCodeAttribute.Failure) if (hasFixedAttribute(EmbType.Ux.Session)) { setFixedAttribute(AppTerminationCause.Crash) } } return copy( endTimeNanos = endTimeMs.millisToNanos(), status = StatusCode.ERROR, attributes = attributes.plus(newAttributes) ) } internal fun Span.toFailedSpan(endTimeMs: Long): Span { val newAttributes = mutableMapOf<String, String>().apply { setFixedAttribute(ErrorCodeAttribute.Failure) if (hasFixedAttribute(EmbType.Ux.Session)) { setFixedAttribute(AppTerminationCause.Crash) } } return copy( endTimeUnixNano = endTimeMs.millisToNanos(), status = Span.Status.ERROR, attributes = newAttributes.map { Attribute(it.key, it.value) }.plus(attributes ?: emptyList()) ) }
9
Kotlin
7
130
e3ab4c793ce7fceae98cf82ff68d1ee6cd33a2c1
3,387
embrace-android-sdk
Apache License 2.0
app/src/main/java/com/example/cointrackr/ui/TopGainLossFragment.kt
Ankitsh-rtx
655,849,197
false
null
package com.example.cointrackr.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.ViewGroup import androidx.lifecycle.lifecycleScope import com.example.cointrackr.adapter.MarketAdapter import com.example.cointrackr.api.ApiInterface import com.example.cointrackr.api.ApiUtilities import com.example.cointrackr.databinding.FragmentTopGainLossBinding import com.example.cointrackr.models.CryptoCurrency import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.* import kotlin.collections.ArrayList class TopGainLossFragment : Fragment() { lateinit var binding: FragmentTopGainLossBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentTopGainLossBinding.inflate(layoutInflater) getMarketData() return binding.root } private fun getMarketData() { val position = requireArguments().getInt("position") lifecycleScope.launch(Dispatchers.IO){ val res = ApiUtilities.getInstance().create(ApiInterface::class.java) .getMarketData() if(res.body()!=null){ withContext(Dispatchers.Main){ val dataItem = res.body()!!.data.cryptoCurrencyList Collections.sort(dataItem){ o1,o2->(o2.quotes[0].percentChange24h.toInt()) .compareTo((o1.quotes[0].percentChange24h.toInt())) } val list = ArrayList<CryptoCurrency>() if(position == 0 ){ list.clear() binding.spinKitView.visibility = GONE; for(i in 0..14){ list.add(dataItem[i]) } binding.topGainLoseRecyclerView.adapter = MarketAdapter( requireContext(), list, "home" ) }else{ list.clear() binding.spinKitView.visibility = GONE; for(i in 0..14){ list.add(dataItem[dataItem.size-1-i]) } binding.topGainLoseRecyclerView.adapter = MarketAdapter( requireContext(), list, "home" ) } } } } } }
0
Kotlin
0
1
cceeda5eb2a03d6c5fd38daf50e29c1ef1ec1a6a
2,827
CoinTrackr
MIT License
src/test/kotlin/Day20Test.kt
mgellert
572,594,052
false
{"Kotlin": 45517}
import java.util.* import kotlin.test.Test import kotlin.test.assertEquals class Day20Test { @Test fun `should mix example input`() { val mix = GrovePositioningSystem.mix(testInput, LinkedList(testInput)).map { it.value } assertEquals(listOf<Long>(-2, 1, 2, -3, 4, 0, 3), mix) } @Test fun `should decrypt example`() { val sum = GrovePositioningSystem.sumOfCoordinates(testInput) assertEquals(3, sum) } @Test fun `should mix example with non unique numbers`() { val input = listOf<Long>(0, -1, -1, 1).map { GrovePositioningSystem.Container(it) } val mix = GrovePositioningSystem.mix(input, LinkedList(input)).map { it.value } assertEquals(listOf<Long>(-1, 1, -1, 0), mix) } @Test fun `should solve day 20 part 1`() { val sum = GrovePositioningSystem.sumOfCoordinates(input) assertEquals(4151, sum) } @Test fun `should decrypt using improved mixing`() { val mix = GrovePositioningSystem.improvedMix(testInput).map { it.value } assertEquals(listOf<Long>(0, -2434767459, 1623178306, 3246356612, -1623178306, 2434767459, 811589153), mix) } @Test fun `should solve day 20 part 2`() { val sum = GrovePositioningSystem.improvedSumOfCoordinates(input) assertEquals(7848878698663, sum) } companion object { private val input by lazy { GrovePositioningSystem.readGrooveCoordinates() } private val testInput = """ 1 2 -3 3 -2 0 4 """.trimIndent().split("\n").map { GrovePositioningSystem.Container(it.trim().toLong()) } } }
0
Kotlin
0
0
2ce7dba06f924223069ea337ad3eb7b79a759766
1,711
advent-of-code-2022-kotlin
The Unlicense
compiler/frontend/src/org/jetbrains/kotlin/psi/FindDocComment.kt
staltz
52,316,479
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.psi.findDocComment import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.psi.psiUtil.siblings import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.PsiComment import org.jetbrains.kotlin.psi.psiUtil.allChildren fun findDocComment(declaration: KtDeclaration): KDoc? { return declaration.allChildren .dropWhile { it !is KDoc && (it is PsiWhiteSpace || it is PsiComment) } .first() as? KDoc }
0
null
0
1
80074c71fa925a1c7173e3fffeea4cdc5872460f
1,125
kotlin
Apache License 2.0
android/app/src/main/java/org/bitcoinppl/cove/Extention.kt
bitcoinppl
808,235,398
false
{"Swift": 684819, "Rust": 258970, "Kotlin": 203233, "Shell": 4523, "Just": 1801}
import org.bitcoinppl.cove.AutoComplete open class Bip39AutoComplete : org.bitcoinppl.cove.Bip39AutoComplete(), AutoComplete {}
17
Swift
2
24
bf3673f6f8f78d89195cbab7e633ce0bca54737c
128
cove
MIT License
app/src/main/java/com/developerbreach/developerbreach/ui/favorites/FavoritesFragment.kt
RajashekarRaju
285,625,118
false
{"Kotlin": 164789}
package com.developerbreach.developerbreach.ui.favorites // //import android.os.Bundle //import android.view.LayoutInflater //import android.view.View //import android.view.ViewGroup //import androidx.fragment.app.Fragment //import androidx.fragment.app.viewModels //import androidx.navigation.fragment.findNavController //import com.developerbreach.developerbreach.databinding.FragmentFavoritesBinding //import com.developerbreach.developerbreach.utils.RecyclerViewItemDecoration.Companion.setItemSpacing //import java.util.concurrent.TimeUnit // //class FavoritesFragment : Fragment() { // // private val viewModel: FavoritesViewModel by viewModels() // // override fun onCreateView( // inflater: LayoutInflater, container: ViewGroup?, // savedInstanceState: Bundle? // ): View { // // Get reference to binding and inflate this class layout. // val binding = FragmentFavoritesBinding.inflate(inflater, container, false) // // Set item decoration for items inside recycler view. // setItemSpacing(resources, binding.favoritesRecyclerView) // // Time taken for fragment to enter with transition // postponeEnterTransition(300L, TimeUnit.MILLISECONDS) // binding.lifecycleOwner = this // // Allows Data Binding to Observe LiveData with the lifecycle of this Fragment. // binding.viewModel = viewModel // binding.navController = findNavController() // binding.executePendingBindings() // // Return root binding view. // return binding.root // } //}
0
Kotlin
0
0
65e3019f6babda8ca722a734f5d5b23012b5f7e9
1,564
developers-breach-android
Apache License 2.0
domain/src/main/kotlin/team/mobileb/opgg/domain/usecase/CheckRoomUseCase.kt
OPGG-HACKTHON
391,351,999
false
null
package team.mobileb.opgg.domain.usecase import team.mobileb.opgg.domain.model.CheckInfo import team.mobileb.opgg.domain.repository.RoomRepository private typealias BaseCheckRoomUseCase = BaseUseCase<String, CheckInfo> class CheckRoomUseCase(private val repository: RoomRepository) : BaseCheckRoomUseCase { override suspend fun invoke(parameter: String) = repository.checkRoom(inviteCode = parameter) }
0
Kotlin
1
23
26036b3a9e38b3e2e127746dcda733b108138e61
410
mobile-b-android
MIT License
compiler/testData/debug/stepping/chainCall.kt
JetBrains
3,432,266
false
null
// FILE: test.kt class A { fun foo() = this inline fun bar() = this } fun box() { val a = A() a.foo() .foo() a.bar() .bar() } // EXPECTATIONS JVM_IR // test.kt:10 box // test.kt:4 <init> // test.kt:10 box // test.kt:11 box // test.kt:5 foo // test.kt:12 box // test.kt:5 foo // test.kt:12 box // test.kt:14 box // test.kt:6 box // test.kt:15 box // test.kt:6 box // test.kt:16 box // EXPECTATIONS JS_IR // test.kt:10 box // test.kt:4 <init> // test.kt:11 box // test.kt:5 foo // test.kt:12 box // test.kt:5 foo // test.kt:16 box // EXPECTATIONS WASM // test.kt:1 $box // test.kt:10 $box (12, 12) // test.kt:7 $A.<init> // test.kt:11 $box (4, 6) // test.kt:5 $A.foo (16, 20, 16, 20) // test.kt:12 $box (9, 9) // test.kt:15 $box (9, 9) // test.kt:14 $box // test.kt:6 $box (23, 27, 23, 27) // test.kt:16 $box
184
null
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
850
kotlin
Apache License 2.0
masterswitch/src/main/java/com/smp/masterswitchpreference/MasterSwitchPreferenceFragment.kt
svenoaks
284,879,301
false
null
package com.smp.masterswitchpreference import android.content.Context import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.Keep import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.recyclerview.widget.RecyclerView @Keep open class MasterSwitchPreferenceFragment : PreferenceFragmentCompat() { @Keep companion object { fun newInstance(attrs: MasterSwitchPreferenceAttrs): MasterSwitchPreferenceFragment { val frag = MasterSwitchPreferenceFragment() with(Bundle()) { putParcelable(ATTRS_KEY_NAME, attrs) frag.arguments = this } return frag } } val attrs: MasterSwitchPreferenceAttrs by lazy { val args = requireArguments() args.classLoader = MasterSwitchPreferenceAttrs::class.java.classLoader args.getParcelable<MasterSwitchPreferenceAttrs>(ATTRS_KEY_NAME)!! } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.blank_preference_screen) val masterSwitchPreference = MasterSwitchSwitchPreference(requireContext()) masterSwitchPreference.key = attrs.key masterSwitchPreference.setDefaultValue(attrs.defaultValue) preferenceScreen.addPreference(masterSwitchPreference) addPreferencesFromResource(R.xml.explanation_preference_screen) val explanationText = findPreference<Preference>("com_smp_explanation_key")!! attrs.includedPrefScreen?.let { addPreferencesFromResource(it) } val includedPrefs = mutableListOf<Preference>() for (i in 2 until preferenceScreen.preferenceCount) { val pref = preferenceScreen.getPreference(i) includedPrefs.add(pref) } attrs.excludedPrefScreen?.let { addPreferencesFromResource(it) } setupMasterSwitch(masterSwitchPreference, explanationText, includedPrefs) setupExplanationText(explanationText) } private fun setupExplanationText(explanationText: Preference) { explanationText.apply { attrs.explanationIcon?.let { iconRes -> setIcon(iconRes) icon?.setTint(attrs.explanationIconTintColor) } } } override fun onCreateRecyclerView( inflater: LayoutInflater, parent: ViewGroup, state: Bundle? ): RecyclerView { return super.onCreateRecyclerView(inflater, parent, state).apply { itemAnimator = null layoutAnimation = null } } private fun setupMasterSwitch(masterSwitch: MasterSwitchSwitchPreference, explanationText: Preference, includedPrefs: List<Preference>) { fun handleExplanationText(on: Boolean) { if (attrs.hideExplanation) explanationText.isVisible = !on explanationText.summary = if (on) { attrs.switchOnExplanationText } else { attrs.switchOffExplanationText } includedPrefs.forEach { it.isVisible = on } } fun titleValue(on: Boolean): String = if (on) { attrs.switchOnText } else { attrs.switchOffText } masterSwitch.apply { fun setBackgroundColor(on: Boolean) { if (on) { applySwitchOnBackgroundColor() } else { applySwitchOffBackgroundColor() } } attrs = this@MasterSwitchPreferenceFragment.attrs applySwitchLayout() attrs.key.let { key = it setDefaultValue(attrs.defaultValue) } title = titleValue(isChecked) handleExplanationText(isChecked) setOnPreferenceChangeListener { _, newValue -> title = titleValue(newValue as Boolean) handleExplanationText(newValue) setBackgroundColor(newValue) true } } } } internal fun dpToPixels(context: Context, dipValue: Float): Float { val metrics = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics) }
3
null
2
6
cc3557da9dd804f7378a98a9c394610eac4d9b67
4,512
MasterSwitchPreference
Apache License 2.0
masterswitch/src/main/java/com/smp/masterswitchpreference/MasterSwitchPreferenceFragment.kt
svenoaks
284,879,301
false
null
package com.smp.masterswitchpreference import android.content.Context import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.Keep import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.recyclerview.widget.RecyclerView @Keep open class MasterSwitchPreferenceFragment : PreferenceFragmentCompat() { @Keep companion object { fun newInstance(attrs: MasterSwitchPreferenceAttrs): MasterSwitchPreferenceFragment { val frag = MasterSwitchPreferenceFragment() with(Bundle()) { putParcelable(ATTRS_KEY_NAME, attrs) frag.arguments = this } return frag } } val attrs: MasterSwitchPreferenceAttrs by lazy { val args = requireArguments() args.classLoader = MasterSwitchPreferenceAttrs::class.java.classLoader args.getParcelable<MasterSwitchPreferenceAttrs>(ATTRS_KEY_NAME)!! } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.blank_preference_screen) val masterSwitchPreference = MasterSwitchSwitchPreference(requireContext()) masterSwitchPreference.key = attrs.key masterSwitchPreference.setDefaultValue(attrs.defaultValue) preferenceScreen.addPreference(masterSwitchPreference) addPreferencesFromResource(R.xml.explanation_preference_screen) val explanationText = findPreference<Preference>("com_smp_explanation_key")!! attrs.includedPrefScreen?.let { addPreferencesFromResource(it) } val includedPrefs = mutableListOf<Preference>() for (i in 2 until preferenceScreen.preferenceCount) { val pref = preferenceScreen.getPreference(i) includedPrefs.add(pref) } attrs.excludedPrefScreen?.let { addPreferencesFromResource(it) } setupMasterSwitch(masterSwitchPreference, explanationText, includedPrefs) setupExplanationText(explanationText) } private fun setupExplanationText(explanationText: Preference) { explanationText.apply { attrs.explanationIcon?.let { iconRes -> setIcon(iconRes) icon?.setTint(attrs.explanationIconTintColor) } } } override fun onCreateRecyclerView( inflater: LayoutInflater, parent: ViewGroup, state: Bundle? ): RecyclerView { return super.onCreateRecyclerView(inflater, parent, state).apply { itemAnimator = null layoutAnimation = null } } private fun setupMasterSwitch(masterSwitch: MasterSwitchSwitchPreference, explanationText: Preference, includedPrefs: List<Preference>) { fun handleExplanationText(on: Boolean) { if (attrs.hideExplanation) explanationText.isVisible = !on explanationText.summary = if (on) { attrs.switchOnExplanationText } else { attrs.switchOffExplanationText } includedPrefs.forEach { it.isVisible = on } } fun titleValue(on: Boolean): String = if (on) { attrs.switchOnText } else { attrs.switchOffText } masterSwitch.apply { fun setBackgroundColor(on: Boolean) { if (on) { applySwitchOnBackgroundColor() } else { applySwitchOffBackgroundColor() } } attrs = this@MasterSwitchPreferenceFragment.attrs applySwitchLayout() attrs.key.let { key = it setDefaultValue(attrs.defaultValue) } title = titleValue(isChecked) handleExplanationText(isChecked) setOnPreferenceChangeListener { _, newValue -> title = titleValue(newValue as Boolean) handleExplanationText(newValue) setBackgroundColor(newValue) true } } } } internal fun dpToPixels(context: Context, dipValue: Float): Float { val metrics = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics) }
3
null
2
6
cc3557da9dd804f7378a98a9c394610eac4d9b67
4,512
MasterSwitchPreference
Apache License 2.0
library/src/main/java/com/zerlings/library/SmartSpinner.kt
ZAndroidH
445,982,646
true
{"Kotlin": 25424}
package com.zerlings.library import android.R.attr import android.annotation.SuppressLint import android.content.Context import android.graphics.Color import android.graphics.drawable.Drawable import android.support.annotation.ColorInt import android.support.annotation.DrawableRes import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat import android.support.v7.widget.AppCompatTextView import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.util.TypedValue import android.view.Gravity import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.PopupWindow import kotlinx.android.synthetic.main.spinner_menu.view.* class SmartSpinner @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = attr.textViewStyle) : AppCompatTextView(context, attrs, defStyleAttr) { private val menuPaddingStart: Int private val menuPaddingEnd: Int private val menuWidth: Int private val menuOffsetX: Int private val menuOffsetY: Int private val presetIndex: Int private val presetText: String? private val spinnerTextSize: Float private val arrowDrawable: Drawable private val isArrowHidden: Boolean private val showSelectedColor: Boolean @ColorInt private val textTint: Int @ColorInt private val selectedTint: Int @DrawableRes private val headBackground: Int @DrawableRes private val menuBackground: Int @DrawableRes private val selectedBackground: Int @ColorInt private val arrowTint: Int @DrawableRes private val arrowResId: Int private val dropDownMenu: PopupWindow private val recyclerView: RecyclerView private val entries: Array<CharSequence>? private var selectedIndex = -1 private var adapter: SmartSpinnerAdapter<CharSequence>? = null private var onItemSelectedListener: ((View, Int) -> Unit)? = null private var onSpinnerResetListener: (() -> Unit)? = null private var initialized = false init { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SmartSpinner) //setMenuPaddingAndLocation menuPaddingStart = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_menuPaddingStart, 0) menuPaddingEnd = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_menuPaddingEnd, 0) menuWidth = typedArray.getLayoutDimension(R.styleable.SmartSpinner_menuWidth, -3) menuOffsetX = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_menuOffsetX, 0) menuOffsetY = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_menuOffsetY, 0) //setTextStyle spinnerTextSize = typedArray.getDimension(R.styleable.SmartSpinner_textSize, resources.getDimension(R.dimen.default_text_size)) setTextSize(TypedValue.COMPLEX_UNIT_PX, spinnerTextSize) textTint = typedArray.getColor(R.styleable.SmartSpinner_textColor, Color.BLACK) selectedTint = typedArray.getColor(R.styleable.SmartSpinner_selectedColor, Color.CYAN) setTextColor(textTint) gravity = typedArray.getInt(R.styleable.SmartSpinner_textAlignment, Gravity.START) or Gravity.CENTER_VERTICAL //setBackground headBackground = typedArray.getResourceId(R.styleable.SmartSpinner_spinnerBackground, R.color.light_gray) setBackgroundResource(headBackground) menuBackground = typedArray.getResourceId(R.styleable.SmartSpinner_menuBackground, headBackground) selectedBackground = typedArray.getResourceId(R.styleable.SmartSpinner_selectedBackground, menuBackground) //setPreset presetText = typedArray.getString(R.styleable.SmartSpinner_presetText) presetIndex = if (presetText != null) -1 else typedArray.getInt(R.styleable.SmartSpinner_presetIndex, 0) entries = typedArray.getTextArray(R.styleable.SmartSpinner_entries) text = presetText ?: entries?.get(0) showSelectedColor = typedArray.getBoolean(R.styleable.SmartSpinner_showSelectedColor, false) //setArrow isArrowHidden = typedArray.getBoolean(R.styleable.SmartSpinner_hideArrow, false) arrowTint = typedArray.getColor(R.styleable.SmartSpinner_arrowTint, Color.BLACK) arrowResId = typedArray.getResourceId(R.styleable.SmartSpinner_arrowDrawable, R.drawable.arrow) arrowDrawable = ContextCompat.getDrawable(getContext(), arrowResId)!! DrawableCompat.setTint(arrowDrawable, arrowTint) setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, if (!isArrowHidden) arrowDrawable else null, null) compoundDrawablePadding = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_arrowPadding, 100) //setPopupMenu val popupView = View.inflate(context, R.layout.spinner_menu, null) recyclerView = popupView.rcv recyclerView.setBackgroundResource(menuBackground) recyclerView.layoutManager = LinearLayoutManager(context) if (typedArray.getBoolean(R.styleable.SmartSpinner_showDivider, false)){ val dividerColor = typedArray.getColor(R.styleable.SmartSpinner_dividerColor, Color.LTGRAY) val dividerPadding = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_dividerPadding, 0) val dividerHeight = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_dividerHeight, dip2px(context, 1f)) recyclerView.addItemDecoration(BaseSpinnerDivider(context, dividerColor, dividerPadding, dividerHeight)) } setAdapter(SmartSpinnerAdapter(R.layout.spinner_simple_item, entries?.toMutableList() ?: ArrayList(), menuPaddingStart, menuPaddingEnd, textTint, selectedTint, menuBackground, selectedBackground, textSize, gravity)) dropDownMenu = PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { isFocusable = true isOutsideTouchable = true isTouchable = true } isClickable = true typedArray.recycle() } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { if (isEnabled && event.action == MotionEvent.ACTION_UP) { if (!initialized){ resizeDropDownMenu() initialized = true } if (!dropDownMenu.isShowing && adapter!!.itemCount > 0) { adapter!!.notifyDataSetChanged() dropDownMenu.showAsDropDown(this, menuOffsetX, menuOffsetY) } else { dropDownMenu.dismiss() } } return super.onTouchEvent(event) } private fun setAdapter(baseAdapter: SmartSpinnerAdapter<CharSequence>){ adapter = baseAdapter recyclerView.adapter = adapter adapter!!.apply { setSelectedPosition(selectedIndex) onItemClickListener = {view, position -> setSelectedIndex(view, position) dropDownMenu.dismiss() } } reset() } fun reset(){ setSelectedIndex(this, presetIndex, false) onSpinnerResetListener?.invoke() ?: if (presetIndex != -1) { onItemSelectedListener?.invoke(this, presetIndex) } } fun setSelectedIndex(view: View, position: Int, selected: Boolean = true){ selectedIndex = position adapter?.setSelectedPosition(position) text = if (position == -1) presetText else adapter?.getData()?.get(position) setTextColor(if (position != presetIndex && showSelectedColor) selectedTint else textTint) if (selected && position != -1){ onItemSelectedListener?.invoke(view, position) } } fun setDataSource(dataSource: MutableList<CharSequence>){ adapter?.setData(dataSource) setSelectedIndex(this, presetIndex, false) } private fun resizeDropDownMenu(){ dropDownMenu.width = if (menuWidth == -3) width else menuWidth (adapter as SmartSpinnerAdapter).apply { setItemHeight(height) } } fun getItemAtPosition(position: Int): CharSequence? { return adapter?.getData()?.get(position) } fun getSelectedItem(): CharSequence? { return if (text == presetText) null else text } fun getSelectedIndex(): Int { return selectedIndex } fun setOnItemSelectedListener(listener: (View, Int) -> Unit){ onItemSelectedListener = listener } fun setOnSpinnerResetListener(listener: () -> Unit){ onSpinnerResetListener = listener } private fun dip2px(context: Context, dpValue: Float): Int { val scale = context.resources.displayMetrics.density return (dpValue * scale + 0.5f).toInt() } }
0
null
0
0
8eb9ac92d6fe8635b51928dc5b362dc325c546ec
8,907
SmartSpinner
Apache License 2.0
library/src/main/java/com/zerlings/library/SmartSpinner.kt
ZAndroidH
445,982,646
true
{"Kotlin": 25424}
package com.zerlings.library import android.R.attr import android.annotation.SuppressLint import android.content.Context import android.graphics.Color import android.graphics.drawable.Drawable import android.support.annotation.ColorInt import android.support.annotation.DrawableRes import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat import android.support.v7.widget.AppCompatTextView import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.util.TypedValue import android.view.Gravity import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.PopupWindow import kotlinx.android.synthetic.main.spinner_menu.view.* class SmartSpinner @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = attr.textViewStyle) : AppCompatTextView(context, attrs, defStyleAttr) { private val menuPaddingStart: Int private val menuPaddingEnd: Int private val menuWidth: Int private val menuOffsetX: Int private val menuOffsetY: Int private val presetIndex: Int private val presetText: String? private val spinnerTextSize: Float private val arrowDrawable: Drawable private val isArrowHidden: Boolean private val showSelectedColor: Boolean @ColorInt private val textTint: Int @ColorInt private val selectedTint: Int @DrawableRes private val headBackground: Int @DrawableRes private val menuBackground: Int @DrawableRes private val selectedBackground: Int @ColorInt private val arrowTint: Int @DrawableRes private val arrowResId: Int private val dropDownMenu: PopupWindow private val recyclerView: RecyclerView private val entries: Array<CharSequence>? private var selectedIndex = -1 private var adapter: SmartSpinnerAdapter<CharSequence>? = null private var onItemSelectedListener: ((View, Int) -> Unit)? = null private var onSpinnerResetListener: (() -> Unit)? = null private var initialized = false init { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SmartSpinner) //setMenuPaddingAndLocation menuPaddingStart = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_menuPaddingStart, 0) menuPaddingEnd = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_menuPaddingEnd, 0) menuWidth = typedArray.getLayoutDimension(R.styleable.SmartSpinner_menuWidth, -3) menuOffsetX = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_menuOffsetX, 0) menuOffsetY = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_menuOffsetY, 0) //setTextStyle spinnerTextSize = typedArray.getDimension(R.styleable.SmartSpinner_textSize, resources.getDimension(R.dimen.default_text_size)) setTextSize(TypedValue.COMPLEX_UNIT_PX, spinnerTextSize) textTint = typedArray.getColor(R.styleable.SmartSpinner_textColor, Color.BLACK) selectedTint = typedArray.getColor(R.styleable.SmartSpinner_selectedColor, Color.CYAN) setTextColor(textTint) gravity = typedArray.getInt(R.styleable.SmartSpinner_textAlignment, Gravity.START) or Gravity.CENTER_VERTICAL //setBackground headBackground = typedArray.getResourceId(R.styleable.SmartSpinner_spinnerBackground, R.color.light_gray) setBackgroundResource(headBackground) menuBackground = typedArray.getResourceId(R.styleable.SmartSpinner_menuBackground, headBackground) selectedBackground = typedArray.getResourceId(R.styleable.SmartSpinner_selectedBackground, menuBackground) //setPreset presetText = typedArray.getString(R.styleable.SmartSpinner_presetText) presetIndex = if (presetText != null) -1 else typedArray.getInt(R.styleable.SmartSpinner_presetIndex, 0) entries = typedArray.getTextArray(R.styleable.SmartSpinner_entries) text = presetText ?: entries?.get(0) showSelectedColor = typedArray.getBoolean(R.styleable.SmartSpinner_showSelectedColor, false) //setArrow isArrowHidden = typedArray.getBoolean(R.styleable.SmartSpinner_hideArrow, false) arrowTint = typedArray.getColor(R.styleable.SmartSpinner_arrowTint, Color.BLACK) arrowResId = typedArray.getResourceId(R.styleable.SmartSpinner_arrowDrawable, R.drawable.arrow) arrowDrawable = ContextCompat.getDrawable(getContext(), arrowResId)!! DrawableCompat.setTint(arrowDrawable, arrowTint) setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, if (!isArrowHidden) arrowDrawable else null, null) compoundDrawablePadding = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_arrowPadding, 100) //setPopupMenu val popupView = View.inflate(context, R.layout.spinner_menu, null) recyclerView = popupView.rcv recyclerView.setBackgroundResource(menuBackground) recyclerView.layoutManager = LinearLayoutManager(context) if (typedArray.getBoolean(R.styleable.SmartSpinner_showDivider, false)){ val dividerColor = typedArray.getColor(R.styleable.SmartSpinner_dividerColor, Color.LTGRAY) val dividerPadding = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_dividerPadding, 0) val dividerHeight = typedArray.getDimensionPixelSize(R.styleable.SmartSpinner_dividerHeight, dip2px(context, 1f)) recyclerView.addItemDecoration(BaseSpinnerDivider(context, dividerColor, dividerPadding, dividerHeight)) } setAdapter(SmartSpinnerAdapter(R.layout.spinner_simple_item, entries?.toMutableList() ?: ArrayList(), menuPaddingStart, menuPaddingEnd, textTint, selectedTint, menuBackground, selectedBackground, textSize, gravity)) dropDownMenu = PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { isFocusable = true isOutsideTouchable = true isTouchable = true } isClickable = true typedArray.recycle() } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { if (isEnabled && event.action == MotionEvent.ACTION_UP) { if (!initialized){ resizeDropDownMenu() initialized = true } if (!dropDownMenu.isShowing && adapter!!.itemCount > 0) { adapter!!.notifyDataSetChanged() dropDownMenu.showAsDropDown(this, menuOffsetX, menuOffsetY) } else { dropDownMenu.dismiss() } } return super.onTouchEvent(event) } private fun setAdapter(baseAdapter: SmartSpinnerAdapter<CharSequence>){ adapter = baseAdapter recyclerView.adapter = adapter adapter!!.apply { setSelectedPosition(selectedIndex) onItemClickListener = {view, position -> setSelectedIndex(view, position) dropDownMenu.dismiss() } } reset() } fun reset(){ setSelectedIndex(this, presetIndex, false) onSpinnerResetListener?.invoke() ?: if (presetIndex != -1) { onItemSelectedListener?.invoke(this, presetIndex) } } fun setSelectedIndex(view: View, position: Int, selected: Boolean = true){ selectedIndex = position adapter?.setSelectedPosition(position) text = if (position == -1) presetText else adapter?.getData()?.get(position) setTextColor(if (position != presetIndex && showSelectedColor) selectedTint else textTint) if (selected && position != -1){ onItemSelectedListener?.invoke(view, position) } } fun setDataSource(dataSource: MutableList<CharSequence>){ adapter?.setData(dataSource) setSelectedIndex(this, presetIndex, false) } private fun resizeDropDownMenu(){ dropDownMenu.width = if (menuWidth == -3) width else menuWidth (adapter as SmartSpinnerAdapter).apply { setItemHeight(height) } } fun getItemAtPosition(position: Int): CharSequence? { return adapter?.getData()?.get(position) } fun getSelectedItem(): CharSequence? { return if (text == presetText) null else text } fun getSelectedIndex(): Int { return selectedIndex } fun setOnItemSelectedListener(listener: (View, Int) -> Unit){ onItemSelectedListener = listener } fun setOnSpinnerResetListener(listener: () -> Unit){ onSpinnerResetListener = listener } private fun dip2px(context: Context, dpValue: Float): Int { val scale = context.resources.displayMetrics.density return (dpValue * scale + 0.5f).toInt() } }
0
null
0
0
8eb9ac92d6fe8635b51928dc5b362dc325c546ec
8,907
SmartSpinner
Apache License 2.0
room/compiler/src/main/kotlin/androidx/room/log/RLog.kt
FYI-Google
258,765,297
false
null
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package androidx.room.log import androidx.room.processor.Context import androidx.room.vo.Warning import java.io.StringWriter import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.util.Elements import javax.tools.Diagnostic import javax.tools.Diagnostic.Kind.ERROR import javax.tools.Diagnostic.Kind.NOTE import javax.tools.Diagnostic.Kind.WARNING class RLog( val messager: Messager, val suppressedWarnings: Set<Warning>, val defaultElement: Element? ) { private fun String.safeFormat(vararg args: Any): String { try { return format(args) } catch (ex: Throwable) { // the input string might be from random source in which case we rather print the // msg as is instead of crashing while reporting an error. return this } } fun d(element: Element, msg: String, vararg args: Any) { messager.printMessage(NOTE, msg.safeFormat(args), element) } fun d(msg: String, vararg args: Any) { messager.printMessage(NOTE, msg.safeFormat(args)) } fun e(element: Element, msg: String, vararg args: Any) { messager.printMessage(ERROR, msg.safeFormat(args), element) } fun e(msg: String, vararg args: Any) { messager.printMessage(ERROR, msg.safeFormat(args), defaultElement) } fun w(warning: Warning, element: Element? = null, msg: String, vararg args: Any) { if (suppressedWarnings.contains(warning)) { return } messager.printMessage(WARNING, msg.safeFormat(args), element ?: defaultElement) } fun w(warning: Warning, msg: String, vararg args: Any) { if (suppressedWarnings.contains(warning)) { return } messager.printMessage(WARNING, msg.safeFormat(args), defaultElement) } interface Messager { fun printMessage(kind: Diagnostic.Kind, msg: String, element: Element? = null) } class ProcessingEnvMessager(val processingEnv: ProcessingEnvironment) : Messager { override fun printMessage(kind: Diagnostic.Kind, msg: String, element: Element?) { processingEnv.messager.printMessage( kind, if (element != null && element.isFromCompiledClass()) { msg.appendElement(processingEnv.elementUtils, element) } else { msg }, element) } } class CollectingMessager : Messager { private val messages = mutableMapOf<Diagnostic.Kind, MutableList<Pair<String, Element?>>> () override fun printMessage(kind: Diagnostic.Kind, msg: String, element: Element?) { messages.getOrPut(kind, { arrayListOf() }).add(Pair(msg, element)) } fun hasErrors() = messages.containsKey(Diagnostic.Kind.ERROR) fun writeTo(context: Context) { val printMessage = context.logger.messager::printMessage messages.forEach { pair -> val kind = pair.key pair.value.forEach { (msg, element) -> printMessage(kind, msg, element) } } } } companion object { /** * Indicates whether an element comes from a compiled class. * * If this method fails to identify if the element comes from a compiled class it will * default to returning false. Note that this is a poor-man's method of identifying if the * java source of the element is available without depending on compiler tools. */ private fun Element.isFromCompiledClass(): Boolean { fun getClassFileString(symbol: Any): String = try { symbol.javaClass.getDeclaredField("classfile").get(symbol).toString() } catch (ex: NoSuchFieldException) { getClassFileString( symbol.javaClass.superclass.getDeclaredField("owner").get(symbol)) } return try { getClassFileString(this).let { it.contains(".jar") || it.contains(".class") } } catch (ex: Throwable) { false } } private fun String.appendElement(elementUtils: Elements, element: Element): String { return StringBuilder(this).apply { append(" - ") when (element.kind) { ElementKind.CLASS, ElementKind.INTERFACE, ElementKind.CONSTRUCTOR -> append(element) ElementKind.FIELD, ElementKind.METHOD, ElementKind.PARAMETER -> append("$element in ${element.enclosingElement}") else -> { // Not sure how to nicely print the element, delegate to utils then. append("In:\n") append(StringWriter().apply { elementUtils.printElements(this, element) }.toString()) } } }.toString() } } }
0
null
0
6
b9cd83371e928380610719dfbf97c87c58e80916
6,015
platform_frameworks_support
Apache License 2.0
app/src/main/java/com/example/musicplayercompose/ui/playerview/viewmodel/PlayScreenViewModel.kt
KevinMartinezC
627,693,804
false
null
package com.example.musicplayercompose.ui.playerview.viewmodel import android.content.Context import android.net.Uri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.musicplayercompose.R import com.example.musicplayercompose.model.Song import com.example.musicplayercompose.model.media.MediaPlayerHolder import com.example.musicplayercompose.ui.homeview.viewmodel.HomeScreenViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch class PlayScreenViewModel( val homeScreenViewModel: HomeScreenViewModel, ) : ViewModel(){ private var isSongTitleInitialized = false private val sliderPosition = MutableStateFlow(INITIAL_VALUE_SLIDER_POSITION) private val songTitle = MutableStateFlow<String?>(null) private val currentSongIndex = MutableStateFlow(INITIAL_VALUE_INDEX) private val songAlbumArtUri = MutableStateFlow<Uri?>(null) private val playPauseButtonMutableStateFlow = MutableStateFlow(R.drawable.baseline_stop_24) private val songs: StateFlow<List<Song>> = homeScreenViewModel.uiState.songsStateFlow val uiState = PlayerUIState( songTitle, songAlbumArtUri, currentSongIndex, playPauseButtonMutableStateFlow, sliderPosition = sliderPosition.asStateFlow() ) val currentSong: StateFlow<Song?> = currentSongIndex.map { index -> songs.value.getOrNull(index) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null) fun onSliderPositionChanged(newSliderPosition: Float) { MediaPlayerHolder.mediaPlayer?.let { mediaPlayer -> val newPosition = (newSliderPosition * mediaPlayer.duration).toInt() mediaPlayer.seekTo(newPosition) } } fun updateSliderPosition(mediaPlayerHolder: MediaPlayerHolder) { viewModelScope.launch { while (true) { mediaPlayerHolder.mediaPlayer?.let { mediaPlayer -> if (mediaPlayer.isPlaying) { val currentPosition = mediaPlayer.currentPosition.toFloat() val duration = mediaPlayer.duration.toFloat() val progress = currentPosition / duration sliderPosition.value = progress } } delay(1000) } } } fun setSongTitle(song: Song) { this.songTitle.value = song.title val index = songs.value.indexOfFirst { it == song } currentSongIndex.value = index songAlbumArtUri.value = song.albumArtUri isSongTitleInitialized = true } private fun playSong(context: Context, mediaPlayerHolder: MediaPlayerHolder) { mediaPlayerHolder.mediaPlayer?.let { mediaPlayer -> if (mediaPlayer.isPlaying) { mediaPlayer.stop() } mediaPlayer.reset() val songs = homeScreenViewModel.uiState.songsStateFlow.value if (currentSongIndex.value !in songs.indices) { currentSongIndex.value = INITIAL_VALUE_INDEX } val song = songs[currentSongIndex.value] mediaPlayer.setDataSource(context, song.songUri) mediaPlayer.prepare() mediaPlayer.setOnPreparedListener { mediaPlayer.start() playPauseButtonMutableStateFlow.value = R.drawable.baseline_stop_24 setSongTitle(song) } } } fun onPlayPauseButtonClick() { MediaPlayerHolder.mediaPlayer?.let { mediaPlayer -> if (mediaPlayer.isPlaying) { mediaPlayer.pause() playPauseButtonMutableStateFlow.value = R.drawable.outline_play_arrow_24 } else { mediaPlayer.start() playPauseButtonMutableStateFlow.value = R.drawable.baseline_stop_24 } } } fun onPreviousButtonClick( context: Context, mediaPlayerHolder: MediaPlayerHolder ) { viewModelScope.launch { songs.collect { songs -> val currentSongIndexValue = currentSongIndex.value val newSongIndex = if (currentSongIndexValue > 0) { currentSongIndexValue - 1 } else { songs.size - 1 } currentSongIndex.value = newSongIndex val newSong = songs.getOrNull(newSongIndex) newSong?.let { setSongTitle(it) playSong(context, mediaPlayerHolder) } } } } fun onNextButtonClick( context: Context, mediaPlayerHolder: MediaPlayerHolder ) { viewModelScope.launch { songs.collect { songs -> val currentSongIndexValue = currentSongIndex.value val newSongIndex = if (currentSongIndexValue < songs.size - 1) { currentSongIndexValue + 1 } else { INITIAL_VALUE_INDEX } currentSongIndex.value = newSongIndex val newSong = songs.getOrNull(newSongIndex) newSong?.let { setSongTitle(it) playSong(context, mediaPlayerHolder) } } } } companion object { const val INITIAL_VALUE_INDEX = 0 const val INITIAL_VALUE_SLIDER_POSITION = 0f } }
0
Kotlin
0
0
0fce426b7a3d5be481fd91004348939db3192490
5,817
MusicPlayerComposeMVVM
MIT License
packages/webservice/app/src/test/kotlin/com/yahoo/navi/ws/test/integration/AsyncQueryTest.kt
yavin-dev
101,244,961
false
null
/** * Copyright 2021 Yahoo Holdings Inc. * Licensed under the terms of the MIT license. See accompanying LICENSE.md file for terms. */ package com.yahoo.yavin.ws.test.integration import com.jayway.restassured.RestAssured.given import com.yahoo.yavin.ws.test.framework.IntegrationTest import org.apache.http.HttpStatus import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.nullValue import org.junit.jupiter.api.Test class AsyncQueryTest : IntegrationTest() { private val user = "user" private val adminUser = "adminUser" private val guestUser = "guestUser" private val adminRole = "admin" private val guestRole = "guest" private val id = "edc4a871-dff2-4054-804e-d80075cf830e" @Test fun testAsyncQueryPermissions() { registerUser(user) registerUser(adminUser) registerUser(guestUser) registerRole(adminRole) registerRole(guestRole) registerUserRole(adminRole, adminUser) registerUserRole(guestRole, guestUser) given() .header("User", user) .contentType("application/vnd.api+json") .body( """ { "data": { "type": "asyncQuery", "id": "$id", "attributes": { "asyncAfterSeconds": 0, "query": "/roles", "queryType": "JSONAPI_V1_0", "status": "QUEUED" } } } """.trimIndent() ) .When() .post("asyncQuery") .then() .assertThat() .statusCode(HttpStatus.SC_CREATED) .body("data.id", equalTo(id)) .body("data.type", equalTo("asyncQuery")) .body("data.attributes.status", equalTo("PROCESSING")) .body("data.attributes.result", nullValue()) /* * Owner can query the status */ given() .header("User", user) .contentType("application/vnd.api+json") .When() .get("/asyncQuery/$id") .then() .statusCode(org.apache.http.HttpStatus.SC_OK) /* * Admin can query the status */ given() .header("User", adminUser) .contentType("application/vnd.api+json") .When() .get("/asyncQuery/$id") .then() .statusCode(org.apache.http.HttpStatus.SC_OK) /* * No other user can query the status */ given() .header("User", guestUser) .contentType("application/vnd.api+json") .When() .get("/asyncQuery/$id") .then() .statusCode(org.apache.http.HttpStatus.SC_NOT_FOUND) } }
83
null
38
86
cd2b41054f723789600f5de4ae7d4f16f11584b5
2,999
framework
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/SearchLocation.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled 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.rounded.Icons public val Icons.Filled.SearchLocation: ImageVector get() { if (_searchLocation != null) { return _searchLocation!! } _searchLocation = Builder(name = "SearchLocation", 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(23.707f, 22.293f) lineToRelative(-5.946f, -5.946f) curveToRelative(1.412f, -1.725f, 2.261f, -3.928f, 2.261f, -6.325f) curveTo(20.021f, 4.508f, 15.535f, 0.021f, 10.021f, 0.021f) reflectiveCurveTo(0.021f, 4.508f, 0.021f, 10.021f) reflectiveCurveToRelative(4.486f, 10.0f, 10.0f, 10.0f) curveToRelative(2.398f, 0.0f, 4.601f, -0.849f, 6.325f, -2.261f) lineToRelative(5.946f, 5.946f) curveToRelative(0.195f, 0.195f, 0.451f, 0.293f, 0.707f, 0.293f) reflectiveCurveToRelative(0.512f, -0.098f, 0.707f, -0.293f) curveToRelative(0.391f, -0.391f, 0.391f, -1.023f, 0.0f, -1.414f) close() moveTo(13.535f, 12.535f) lineToRelative(-1.821f, 1.781f) curveToRelative(-0.473f, 0.463f, -1.093f, 0.693f, -1.714f, 0.693f) reflectiveCurveToRelative(-1.241f, -0.23f, -1.715f, -0.693f) lineToRelative(-1.812f, -1.773f) curveToRelative(-0.952f, -0.951f, -1.473f, -2.207f, -1.473f, -3.543f) reflectiveCurveToRelative(0.521f, -2.592f, 1.465f, -3.535f) curveToRelative(0.943f, -0.944f, 2.199f, -1.465f, 3.535f, -1.465f) reflectiveCurveToRelative(2.591f, 0.521f, 3.535f, 1.465f) reflectiveCurveToRelative(1.465f, 2.199f, 1.465f, 3.535f) reflectiveCurveToRelative(-0.521f, 2.592f, -1.465f, 3.535f) close() moveTo(10.0f, 6.0f) curveToRelative(-0.802f, 0.0f, -1.555f, 0.312f, -2.12f, 0.879f) curveToRelative(-0.567f, 0.566f, -0.88f, 1.319f, -0.88f, 2.121f) reflectiveCurveToRelative(0.312f, 1.555f, 0.879f, 2.121f) lineToRelative(1.805f, 1.766f) curveToRelative(0.174f, 0.17f, 0.458f, 0.17f, 0.632f, 0.0f) lineToRelative(1.813f, -1.773f) curveToRelative(0.559f, -0.559f, 0.871f, -1.312f, 0.871f, -2.113f) reflectiveCurveToRelative(-0.313f, -1.555f, -0.879f, -2.121f) curveToRelative(-0.566f, -0.566f, -1.32f, -0.879f, -2.121f, -0.879f) close() moveTo(10.0f, 9.993f) curveToRelative(-0.552f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f) reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f) reflectiveCurveToRelative(1.0f, 0.448f, 1.0f, 1.0f) reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f) close() } } .build() return _searchLocation!! } private var _searchLocation: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,874
icons
MIT License
network/src/main/java/com/eslam/network/ApiResponse.kt
zerox321
271,759,108
false
null
package com.eslam.network import okhttp3.ResponseBody import retrofit2.Response @Suppress("unused") sealed class ApiResponse<out T> { /** * API Success response class from retrofit. * * [data] is optional. (There are responses without data) */ class Success<T>(response: Response<T>) : ApiResponse<T>() { val data: T? = response.body() override fun toString() = "[ApiResponse.Success]: $data" } /** * API Failure response class. * * ## Throw Exception case. * Gets called when an unexpected exception occurs while creating the request or processing the response. * * ## API Network format error case. * API communication conventions do not match or applications need to handle errors. * * ## API Network Excepttion error case. * Gets called when an unexpected exception occurs while creating the request or processing the response. */ sealed class Failure<out T> { class Error<out T>(response: Response<out T>) : ApiResponse<T>() { val responseBody: ResponseBody? = response.errorBody()?.apply { close() } val code: Int = response.code() override fun toString(): String = "[ApiResponse.Failure $code]: ${responseBody?.string()}" } class Exception<out T>(exception: Throwable) : ApiResponse<T>() { val message: String? = exception.localizedMessage override fun toString(): String = "[ApiResponse.Failure]: $message" } } companion object { /** * ApiResponse Factory * * [Failure] factory function. Only receives [Throwable] arguments. */ fun <T> error(ex: Throwable) = Failure.Exception<T>(ex) /** * ApiResponse Factory * * [f] Create ApiResponse from [retrofit2.Response] returning from the block. * If [retrofit2.Response] has no errors, it will create [ApiResponse.Success] * If [retrofit2.Response] has errors, it will create [ApiResponse.Failure.Error] */ fun <T> of(f: () -> Response<T>): ApiResponse<T> = try { val response = f() if (response.isSuccessful) { Success(response) } else { Failure.Error(response) } } catch (ex: Exception) { Failure.Exception(ex) } } }
0
Kotlin
1
2
ebc1141adce891971a6d220490e68ad106abc946
2,213
TMDB-MVVM
Apache License 2.0
modern-treasury-kotlin-core/src/main/kotlin/com/moderntreasury/api/models/AccountCollectionFlowListParams.kt
Modern-Treasury
665,762,762
false
null
// File generated from our OpenAPI spec by Stainless. package com.moderntreasury.api.models import com.moderntreasury.api.core.JsonValue import com.moderntreasury.api.core.NoAutoDetect import com.moderntreasury.api.core.toUnmodifiable import com.moderntreasury.api.models.* import java.util.Objects class AccountCollectionFlowListParams constructor( private val afterCursor: String?, private val clientToken: String?, private val counterpartyId: String?, private val externalAccountId: String?, private val perPage: Long?, private val status: String?, private val additionalQueryParams: Map<String, List<String>>, private val additionalHeaders: Map<String, List<String>>, private val additionalBodyProperties: Map<String, JsonValue>, ) { fun afterCursor(): String? = afterCursor fun clientToken(): String? = clientToken fun counterpartyId(): String? = counterpartyId fun externalAccountId(): String? = externalAccountId fun perPage(): Long? = perPage fun status(): String? = status internal fun getQueryParams(): Map<String, List<String>> { val params = mutableMapOf<String, List<String>>() this.afterCursor?.let { params.put("after_cursor", listOf(it.toString())) } this.clientToken?.let { params.put("client_token", listOf(it.toString())) } this.counterpartyId?.let { params.put("counterparty_id", listOf(it.toString())) } this.externalAccountId?.let { params.put("external_account_id", listOf(it.toString())) } this.perPage?.let { params.put("per_page", listOf(it.toString())) } this.status?.let { params.put("status", listOf(it.toString())) } params.putAll(additionalQueryParams) return params.toUnmodifiable() } internal fun getHeaders(): Map<String, List<String>> = additionalHeaders fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is AccountCollectionFlowListParams && this.afterCursor == other.afterCursor && this.clientToken == other.clientToken && this.counterpartyId == other.counterpartyId && this.externalAccountId == other.externalAccountId && this.perPage == other.perPage && this.status == other.status && this.additionalQueryParams == other.additionalQueryParams && this.additionalHeaders == other.additionalHeaders && this.additionalBodyProperties == other.additionalBodyProperties } override fun hashCode(): Int { return Objects.hash( afterCursor, clientToken, counterpartyId, externalAccountId, perPage, status, additionalQueryParams, additionalHeaders, additionalBodyProperties, ) } override fun toString() = "AccountCollectionFlowListParams{afterCursor=$afterCursor, clientToken=$clientToken, counterpartyId=$counterpartyId, externalAccountId=$externalAccountId, perPage=$perPage, status=$status, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } @NoAutoDetect class Builder { private var afterCursor: String? = null private var clientToken: String? = null private var counterpartyId: String? = null private var externalAccountId: String? = null private var perPage: Long? = null private var status: String? = null private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf() private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf() private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(accountCollectionFlowListParams: AccountCollectionFlowListParams) = apply { this.afterCursor = accountCollectionFlowListParams.afterCursor this.clientToken = accountCollectionFlowListParams.clientToken this.counterpartyId = accountCollectionFlowListParams.counterpartyId this.externalAccountId = accountCollectionFlowListParams.externalAccountId this.perPage = accountCollectionFlowListParams.perPage this.status = accountCollectionFlowListParams.status additionalQueryParams(accountCollectionFlowListParams.additionalQueryParams) additionalHeaders(accountCollectionFlowListParams.additionalHeaders) additionalBodyProperties(accountCollectionFlowListParams.additionalBodyProperties) } fun afterCursor(afterCursor: String) = apply { this.afterCursor = afterCursor } fun clientToken(clientToken: String) = apply { this.clientToken = clientToken } fun counterpartyId(counterpartyId: String) = apply { this.counterpartyId = counterpartyId } fun externalAccountId(externalAccountId: String) = apply { this.externalAccountId = externalAccountId } fun perPage(perPage: Long) = apply { this.perPage = perPage } fun status(status: String) = apply { this.status = status } fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply { this.additionalQueryParams.clear() putAllQueryParams(additionalQueryParams) } fun putQueryParam(name: String, value: String) = apply { this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) } fun putQueryParams(name: String, values: Iterable<String>) = apply { this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) } fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply { additionalQueryParams.forEach(this::putQueryParams) } fun removeQueryParam(name: String) = apply { this.additionalQueryParams.put(name, mutableListOf()) } fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply { this.additionalHeaders.clear() putAllHeaders(additionalHeaders) } fun putHeader(name: String, value: String) = apply { this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) } fun putHeaders(name: String, values: Iterable<String>) = apply { this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) } fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply { additionalHeaders.forEach(this::putHeaders) } fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply { this.additionalBodyProperties.clear() this.additionalBodyProperties.putAll(additionalBodyProperties) } fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { this.additionalBodyProperties.put(key, value) } fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply { this.additionalBodyProperties.putAll(additionalBodyProperties) } fun build(): AccountCollectionFlowListParams = AccountCollectionFlowListParams( afterCursor, clientToken, counterpartyId, externalAccountId, perPage, status, additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), additionalBodyProperties.toUnmodifiable(), ) } }
3
null
2
2
776a9b5bb0c3057643ba163b01fdcc14a92e3941
8,404
modern-treasury-kotlin
MIT License
app/src/main/java/com/example/clonethreads/Models/UserModel.kt
aspirers01
746,045,724
false
{"Kotlin": 106428}
package com.example.clonethreads.Models data class UserModel ( val username:String="", val email:String="", val password:String="", val image:String="", val uid:String="", val bio:String="", )
0
Kotlin
0
0
bf84b0079ac549f28fbed8a553b28ed57d12d5d7
241
clonethreads
MIT License
Music-Player-GO-main/project/app/src/main/java/com/iven/musicplayergo/preferences/SettingsFragment.kt
cano696969
786,286,313
false
null
package com.example.rove.preferences import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.browser.customtabs.CustomTabsIntent import androidx.core.net.toUri import androidx.fragment.app.Fragment import androidx.fragment.app.commit import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.example.rove.RovePreferences import com.example.rove.R import com.example.rove.databinding.FragmentSettingsBinding import com.example.rove.ui.UIControlInterface import com.example.rove.utils.Versioning /** * A simple [Fragment] subclass. * Use the [SettingsFragment.newInstance] factory method to * create an instance of this fragment. */ class SettingsFragment : Fragment() { private var _fragmentSettingsBinding: FragmentSettingsBinding? = null private lateinit var mUIControlInterface: UIControlInterface private var mPreferencesFragment: PreferencesFragment? = null override fun onAttach(context: Context) { super.onAttach(context) // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mUIControlInterface = activity as UIControlInterface } catch (e: ClassCastException) { e.printStackTrace() } } override fun onDestroyView() { super.onDestroyView() _fragmentSettingsBinding = null } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _fragmentSettingsBinding = FragmentSettingsBinding.inflate(inflater, container, false) return _fragmentSettingsBinding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) _fragmentSettingsBinding?.searchToolbar?.run { inflateMenu(R.menu.menu_settings) setNavigationOnClickListener { mUIControlInterface.onCloseActivity() } setOnMenuItemClickListener { when (it.itemId) { R.id.github_page -> openGitHubPage() R.id.locale_switcher -> openLocaleSwitcher() } return@setOnMenuItemClickListener true } } mPreferencesFragment = PreferencesFragment.newInstance() mPreferencesFragment?.let { fm -> childFragmentManager.commit { replace(R.id.fragment_layout, fm) } } } fun getPreferencesFragment() = mPreferencesFragment @SuppressLint("SuspiciousIndentation") private fun openLocaleSwitcher() { val locales = ContextUtils.getLocalesList(resources) val dialog: MaterialAlertDialogBuilder = MaterialAlertDialogBuilder(requireContext()).setTitle(R.string.locale_pref_title).setItems(locales.values.toTypedArray()) { _, which -> // Respond to item chosen val newLocale = locales.keys.elementAt(which) if (RovePreferences.getPrefsInstance().locale != newLocale) { RovePreferences.getPrefsInstance().locale = locales.keys.elementAt(which) mUIControlInterface.onAppearanceChanged(isThemeChanged = false) } }.setNegativeButton(R.string.cancel, null) if (RovePreferences.getPrefsInstance().locale != null) { dialog.setNeutralButton(R.string.sorting_pref_default) { _, _ -> RovePreferences.getPrefsInstance().locale = null mUIControlInterface.onAppearanceChanged(isThemeChanged = false) } } dialog.show() } private fun openGitHubPage() { val customTabsIntent = CustomTabsIntent.Builder() .setShareState(CustomTabsIntent.SHARE_STATE_ON) .setShowTitle(true) .build() val parsedUri = getString(R.string.app_git).toUri() val info = solveInfo(customTabsIntent.intent) if (info.size > 0) { customTabsIntent.launchUrl(requireContext(), parsedUri) return } //from: https://github.com/immuni-app/immuni-app-android/blob/development/extensions/src/main/java/it/ministerodellasalute/immuni/extensions/utils/ExternalLinksHelper.kt val browserIntent = Intent(Intent.ACTION_VIEW, parsedUri) browserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK val fallbackInfo = solveInfo(browserIntent) if (fallbackInfo.size > 0) { requireContext().startActivity(browserIntent) return } Toast.makeText(requireContext(), R.string.error_no_browser, Toast.LENGTH_SHORT).show() } @Suppress("DEPRECATION") private fun solveInfo(intent: Intent): MutableList<ResolveInfo> { val manager = requireContext().packageManager return if (Versioning.isTiramisu()) { manager.queryIntentActivities(intent, PackageManager.ResolveInfoFlags.of( PackageManager.MATCH_DEFAULT_ONLY.toLong() )) } else { manager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) } } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment SettingsFragment. */ @JvmStatic fun newInstance() = SettingsFragment() } }
10
null
0
1
f2c39a7bf9fc014c314d592bcd0ccc56c471cd2c
5,772
Lab-Studio-Apps
MIT License
common/src/desktopMain/kotlin/com/darkrockstudios/apps/hammer/common/components/projectselection/accountsettings/PlatformSettingsComponent.desktop.kt
Wavesonics
499,367,913
false
{"Kotlin": 1630287, "Swift": 32452, "CSS": 2064, "Ruby": 1578, "Shell": 361}
package com.darkrockstudios.apps.hammer.common.components.projectselection.accountsettings import com.arkivanov.decompose.ComponentContext import com.arkivanov.decompose.value.Value import com.arkivanov.decompose.value.getAndUpdate import com.darkrockstudios.apps.hammer.common.components.SavableComponent import com.darkrockstudios.apps.hammer.common.components.savableState import com.darkrockstudios.apps.hammer.common.data.globalsettings.GlobalSettingsRepository import com.darkrockstudios.apps.hammer.common.data.migrator.DataMigrator import com.darkrockstudios.apps.hammer.common.data.projectsrepository.ProjectsRepository import com.darkrockstudios.apps.hammer.common.dependencyinjection.injectMainDispatcher import com.darkrockstudios.apps.hammer.common.fileio.HPath import com.darkrockstudios.apps.hammer.common.fileio.okio.toHPath import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import okio.Path.Companion.toPath import org.koin.core.component.get import org.koin.core.component.inject class DesktopPlatformSettingsComponent(componentContext: ComponentContext) : PlatformSettings, SavableComponent<DesktopPlatformSettingsComponent.PlatformState>(componentContext) { private val mainDispatcher by injectMainDispatcher() private val globalSettingsRepository: GlobalSettingsRepository by inject() private val projectsRepository: ProjectsRepository by inject() private val _state by savableState { PlatformState( projectsDir = projectsRepository.getProjectsDirectory(), ) } override val state: Value<PlatformState> = _state override fun getStateSerializer() = PlatformState.serializer() init { watchSettingsUpdates() } private fun watchSettingsUpdates() { scope.launch { globalSettingsRepository.globalSettingsUpdates.collect { settings -> withContext(dispatcherMain) { _state.getAndUpdate { val projectsPath = settings.projectsDirectory.toPath().toHPath() it.copy( projectsDir = projectsPath, ) } } } } } fun setProjectsDir(path: String) { val hpath = HPath( path = path, name = "", isAbsolute = true ) scope.launch { globalSettingsRepository.updateSettings { it.copy( projectsDirectory = path ) } projectsRepository.ensureProjectDirectory() // Migrate the new project directory if needed val dataMigrator: DataMigrator = get<DataMigrator>() dataMigrator.handleDataMigration() withContext(mainDispatcher) { _state.getAndUpdate { it.copy(projectsDir = hpath) } } } } @Serializable data class PlatformState( val projectsDir: HPath, ) }
19
Kotlin
6
128
5eb281596110fe9c315f9c53d5412a93078f870d
2,669
hammer-editor
MIT License
src/main/kotlin/waffle/domain/entity/WebCheckpoint.kt
tmyksj
571,796,959
false
null
package waffle.domain.entity import waffle.domain.model.WebSnapshot import waffle.domain.time.now import java.time.LocalDateTime import java.util.* /** * Checkpoint of pages. */ data class WebCheckpoint( /** * ID. */ val id: UUID = UUID.randomUUID(), /** * WebFlow. */ val flow: WebFlow, /** * Snapshots. */ val snapshots: List<WebSnapshot> = listOf(), /** * State. */ val state: State = State.Ready, /** * Date that the creation was started. */ val startedDate: LocalDateTime? = null, /** * Date that the creation was completed. */ val completedDate: LocalDateTime? = null, /** * Date that the creation was failed. */ val failedDate: LocalDateTime? = null, /** * Date that the entity was created. */ val createdDate: LocalDateTime = now(), /** * Date that the entity was recently modified. */ val lastModifiedDate: LocalDateTime = createdDate, ) { /** * WebCheckpoint state. */ enum class State { /** * The creation is ready. */ Ready, /** * The creation was started. */ Started, /** * The creation was completed. */ Completed, /** * The creation was failed. */ Failed, } }
0
Kotlin
0
0
cd399f56945bb259117e0b4f6991d5f5b7711a73
1,420
waffle
Apache License 2.0
app/src/main/java/com/kylecorry/trail_sense/shared/sensors/altimeter/FusedAltimeter.kt
kylecorry31
215,154,276
false
null
package com.kylecorry.trail_sense.shared.sensors class FusedAltimeter(private val gps: IGPS, private val barometer: IBarometer) : AbstractSensor(), IAltimeter { override val altitude: Float get() = baseAltitude + altitudeChange override val hasValidReading: Boolean get() = gotGps private var altitudeChange = 0f private var lastBarometricAltitude: Float? = null private var baseAltitude = 0f private var started = false private var gotGps = false init { if (gps.hasValidReading){ gotGps = true baseAltitude = gps.altitude } } private fun onGPSUpdate(): Boolean { baseAltitude = gps.altitude gotGps = true notifyListeners() return false } private fun onBarometerUpdate(): Boolean { val lastAltitude = lastBarometricAltitude if (lastAltitude != null) { altitudeChange += barometer.altitude - lastAltitude } lastBarometricAltitude = barometer.altitude if (gotGps) { notifyListeners() } return true } override fun startImpl() { altitudeChange = 0f started = true lastBarometricAltitude = null baseAltitude = gps.altitude gps.start(this::onGPSUpdate) barometer.start(this::onBarometerUpdate) } override fun stopImpl() { started = false gps.stop(this::onGPSUpdate) barometer.stop(this::onBarometerUpdate) } }
401
null
49
739
e06d698b18f2d20e384f5a31aa3226741beb6a69
1,529
Trail-Sense
MIT License
testingplaygroundapp/src/main/java/com/programmersbox/testingplaygroundapp/cardgames/CardUtils.kt
jakepurple13
243,099,864
false
null
package com.programmersbox.testingplaygroundapp.cardgames import android.content.Context import com.programmersbox.funutils.cards.Card import com.programmersbox.funutils.cards.CardColor import com.programmersbox.funutils.cards.Suit import com.programmersbox.loggingutils.FrameType import com.programmersbox.loggingutils.frame import com.programmersbox.testingplayground.color val Card.valueTen: Int get() = if (value > 10) 10 else value fun Card.getImage(context: Context): Int = context.resources.getIdentifier(getCardName(), "drawable", context.packageName) private fun Card.getCardName() = if (cardName(value) == "clear" || cardName(value) == "b1fv") cardName(value) else { cardName(value) + when (suit) { Suit.CLUBS -> 1 Suit.SPADES -> 2 Suit.HEARTS -> 3 Suit.DIAMONDS -> 4 } } private fun cardName(num: Int): String = when (num) { 1 -> "ace" 2 -> "two" 3 -> "three" 4 -> "four" 5 -> "five" 6 -> "six" 7 -> "seven" 8 -> "eight" 9 -> "nine" 10 -> "ten" 11 -> "jack" 12 -> "queen" 13 -> "king" 15 -> "clear" else -> "b1fv" } fun List<Card>.asciiCards(padding: String = "", colorRed: Int = 0xff0000, colorBlack: Int = 0xffffff, equalText: (List<Card>) -> String): String { val lines = asciiCards(padding, colorRed, colorBlack).lines().toMutableList() lines[lines.size / 2 - 1] += equalText(this) return lines.joinToString("\n") } fun List<Card>.asciiCards(padding: String = "", colorRed: Int = 0xff0000, colorBlack: Int = 0xffffff): String { val m = map { it.color to it.asciiCard().lines() } val size = m.random().second.size - 1 val s = StringBuilder() fun CardColor.asciiColor() = when (this) { CardColor.RED -> colorRed CardColor.BLACK -> colorBlack } for (i in 0..size) s.append(m.joinToString(padding) { it.second[i].color(it.first.asciiColor()) }).append("\n") return s.toString() } fun Card.asciiCard(): String { val spaceLength = 10 val symbol = toSymbolString() val spaces = fun(num: Int) = " ".repeat(num) return listOf( " $symbol${spaces(spaceLength - symbol.length)}", "", "", "${spaces(spaceLength / 2)}${suit.unicodeSymbol}${spaces(spaceLength / 2)}", "", "", "${spaces(spaceLength - symbol.length)}$symbol " ).frame(FrameType.OVAL) }
10
Kotlin
1
8
904eb4dc9d6ca3024df1096a4a8ccadaca566a4c
2,395
HelpfulTools
Apache License 2.0
app/src/main/java/com/urbanist/music/feature/map/domain/EventsRepository.kt
MrSwimmer
187,322,536
false
null
package com.urbanist.music.feature.map.domain import io.reactivex.Observable interface EventsRepository { fun observeEvents(): Observable<List<Event>> }
0
Kotlin
0
4
6c9971bca1d7ef41d6b3f00d86c49e7f0916c507
159
urbanist-music
Apache License 2.0
src/studio/papercube/ipprobe/Ip4Address.kt
PaperCube
135,261,702
false
{"Kotlin": 12560}
package studio.papercube.ipprobe import java.util.* class Ip4Address(address: IntArray) { companion object { /** * Parses either full ip or partial ip. * Partial ip refers to those whose several parts in the end are omitted. * This method will return the smallest possible ip. * * For example, it will return 172.28.71.0 with an input value 172.28.71 * * @param ip an ip address represented in string * * @return an [Ip4Address] corresponding to input */ fun parseMin(ip: String): Ip4Address { val parts = try { ip.split('.').toIntArray() } catch (e: NumberFormatException) { throw IllegalArgumentException("$ip is not a valid ip") } val size = parts.size return Ip4Address(parts) } private fun List<String>.toIntArray(): IntArray { return IntArray(size) { i -> this[i].toInt() } } /** * Parses either full ip or partial ip. * Partial ip refers to those whose several parts in the end are omitted. * This method will return the largest possible ip. * * For example, it will return 172.28.71.0 with an input value 172.28.71 * * @param ip an ip address represented in string * * @return an [Ip4Address] corresponding to input */ fun parseMax(ip: String): Ip4Address { val parts = ip.split('.').toIntArray() val size = parts.size val addressArray = IntArray(4) { i -> if (i >= size) 255 else parts[i] } return Ip4Address(addressArray) } } private val address = IntArray(4) init { for (i in 0..3) { this.address[i] = address.getOrNull(i) ?: break } } constructor(p1: Int, p2: Int, p3: Int, p4: Int) : this(intArrayOf(p1, p2, p3, p4)) operator fun plus(inc: Int): Ip4Address { val newAddress = Ip4Address(address) var increment = inc for (i in 3 downTo 0) { val value = address[i] + increment; newAddress.address[i] = value % 256 increment = value / 256 if (increment == 0) { break } } if (increment > 0) { return Ip4Address(0, 0, 0, 0) + (increment - 1) } return newAddress } operator fun compareTo(another: Ip4Address): Int { return Integer.compare(toInt(), another.toInt()) } private fun toInt(): Int { return (address[0] and 0xFF shl 24) or (address[1] and 0xFF shl 16) or (address[2] and 0xFF shl 8) or (address[3] and 0xFF) } override fun toString(): String { return address.joinToString(separator = ".") } override fun equals(other: Any?): Boolean { if (this === other) return true return if (other is Ip4Address) { Arrays.equals(address, other.address) } else false } override fun hashCode(): Int { return Arrays.hashCode(address) } operator fun rangeTo(end: Ip4Address): Ip4AddressRange { return Ip4AddressRange(this, end) } operator fun get(index: Int): Int { return this.address[index] } }
0
Kotlin
0
0
39573eb71ab0fb6ba07cf2d7921420afb0794ed0
3,459
lan-ip-availability-prober
MIT License
MyHairDiary_c/app/src/main/java/com/example/myhairdiary_c/diary/MyHairDiary.kt
sungdoolim
238,624,065
false
null
package com.example.myhairdiary_c.diary import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import android.view.MotionEvent import android.view.VelocityTracker import android.view.View import android.widget.AbsListView import android.widget.LinearLayout import android.widget.NumberPicker import android.widget.Toast import androidx.annotation.RequiresApi import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.marginTop import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.load.engine.Resource import com.example.myhairdiary_c.R import com.example.myhairdiary_c.designers.photourl import com.example.myhairdiary_c.firedb.fireDB import com.example.myhairdiary_c.main.Home2 import com.example.myhairdiary_c.main.second.second_home import com.example.myhairdiary_c.mypage.Mypage import com.example.myhairdiary_c.style.MyAdapter import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.tabs.TabLayout import kotlinx.android.synthetic.main.activity_detailed_designer3.* import kotlinx.android.synthetic.main.activity_home2.* import kotlinx.android.synthetic.main.activity_my_hair_diary.* import kotlinx.android.synthetic.main.activity_my_hair_diary.view.* import kotlinx.android.synthetic.main.bottom_navi.* import kotlinx.android.synthetic.main.diary_uppertab.* class MyHairDiary : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_my_hair_diary) botnav.getMenu().getItem(2).setChecked(true) // 바텀네비 고정입니다. 원래 이런식으로 하는건 아니죠.... botnav.setOnNavigationItemSelectedListener(this) // 다이어리 탭입니다 val db=fireDB(this) val pref=getSharedPreferences("session",0) // session으로 preference에 저장한 것을 불러옵니다. val id:String=pref.getString("id","").toString() val profile=pref.getString("profile","").toString() val major=pref.getString("major","").toString() val major_length=pref.getString("major_length","").toString() val region=pref.getString("region","").toString() diary_uppertab.addOnTabSelectedListener(object:TabLayout.OnTabSelectedListener{ override fun onTabSelected(tab: TabLayout.Tab) { // 탭에 따라 메서드가 달라집니다. // 내가 올린 사진 / 디자이너가 올려준 사진들을 보게 됩니다. var i = tab.position if(i==0){ tab.text="냐옹" select_my_register(db,id)// 내가 올린 게시물들을 봅니다 }else{ select_designer_register(db,id) // 디자이너가 나에게 써준 기록을 봅니다 } } override fun onTabUnselected(tab: TabLayout.Tab) { } override fun onTabReselected(tab: TabLayout.Tab) { } }) var isvisible=false mhd_float.setOnClickListener(){ // 플로팅 버튼입니다. float2,3버튼을 보이게 하며 현재 기능은 3버튼만 기능을 가집니다. isvisible=!isvisible Toast.makeText(this,"floating test",Toast.LENGTH_SHORT).show() if(isvisible){ mhd_float2.visibility= View.VISIBLE mhd_float3.visibility=View.VISIBLE }else{ mhd_float2.visibility= View.INVISIBLE mhd_float3.visibility=View.INVISIBLE } } mhd_float2.setOnClickListener(){ // var intent= Intent(this, Home2::class.java) // startActivity(intent) } mhd_float3.setOnClickListener(){ var intent= Intent(this, MyBoard::class.java) startActivity(intent) } mhd_iv1.setOnClickListener(){ // 이걸로 그리드뷰의 넓이를 조절하려 했으나 실패했습니다... if(mhd_gridview.top==450){ mhd_gridview.top=600 }else{ mhd_gridview.top=450 } } select_my_register(db,id)// 처음 화면은 내가 올린 게시물을 보는 것 입니다. } override fun onNavigationItemSelected(item: MenuItem): Boolean { // bottom navigation의 버튼 이벤트 입니다. when(item.itemId){ R.id.bottom1-> { var intent= Intent(this, Home2::class.java) startActivity(intent) } R.id.bottom2-> { var intent= Intent(this, second_home::class.java) startActivity(intent) } R.id.bottom3->{ var intent= Intent(this, this::class.java) startActivity(intent) } R.id.bottom4->{ var intent= Intent(this, Mypage::class.java) startActivity(intent) } // R.id.bottom5->supportFragmentManager.beginTransaction().replace(R.id.framelayout, home()).commit() else ->"" } return true; } fun select_my_register(db: fireDB,id:String) { // 내가 올린 사진을 불러옵니다 val firestore=db.firestore firestore?.collection("hair_photo").whereEqualTo("id",id).get() .addOnCompleteListener { if(it.isSuccessful){ println("mhd_photo 접근 성공") var userDTO=ArrayList<photourl>() for(dc in it.result!!.documents){ dc.toObject(photourl::class.java)?.let { it1 -> userDTO.add(it1) // firebase로 부터 데이터를 가져오면 데이터들을 클래스에 담습니다. 그 클래스를 arraylist에 담습니다. } } if(userDTO.size==0){ // 만약 아직 기록이 없다면... mhd_gridview.visibility=View.INVISIBLE isexist.visibility=View.VISIBLE // mhd_gridview.y= 100f// 이거로 변경해도 되나.... Toast.makeText(this,"아직 나의 헤어 기록이 없어요!",Toast.LENGTH_SHORT).show() mhd_gridview.removeAllViewsInLayout() mhd_gridview.refreshDrawableState() var adapter = MyAdapter( applicationContext, R.layout.mhdgrid_adapter, // GridView 항목의 레이아웃 row.xml userDTO,-1 ) mhd_gridview.adapter = adapter mhd_gridview.setOnItemClickListener { parent, view, position, id -> var item= style_grid.adapter.getItem(position) as photourl println("${item.name}")// 이렇게 데이터 받을수 있고... } }else{// 기록이 있으면 어댑터 적용 mhd_gridview.visibility=View.VISIBLE isexist.visibility=View.INVISIBLE // mhd_gridview.y= 500f// 이거로 변경해도 되나.... // mhd_iv1.layoutParams= ConstraintLayout.LayoutParams(50,50) var adapter = MyAdapter( applicationContext, R.layout.mhdgrid_adapter, // GridView 항목의 레이아웃 row.xml userDTO,1 ) mhd_gridview.adapter = adapter mhd_gridview.setOnItemClickListener { parent, view, position, id -> var item= mhd_gridview.adapter.getItem(position) as photourl println("${item.name}")// 이렇게 데이터 받을수 있고... } } }else{ println("fail") } } } fun select_designer_register(db: fireDB, id:String) { // 디자이너가 찍은 내 사진을 불러옵니다. val firestore=db.firestore firestore?.collection("hair_photo").whereEqualTo("customid",id).get() .addOnCompleteListener { if(it.isSuccessful){ println("mhd_designer 접근 성공") var userDTO=ArrayList<photourl>() for(dc in it.result!!.documents){ dc.toObject(photourl::class.java)?.let { it1 -> userDTO.add(it1) // firebase로 부터 데이터를 가져오면 데이터들을 클래스에 담습니다. 그 클래스를 arraylist에 담습니다. } } if(userDTO.size==0) { mhd_gridview.visibility=View.INVISIBLE isexist.visibility=View.VISIBLE //mhd_iv1.setLeftTopRightBottom(0,10,0,100) var adapter = MyAdapter( applicationContext, R.layout.mhdgrid_adapter, // GridView 항목의 레이아웃 row.xml userDTO,-1 ) mhd_gridview.adapter = adapter mhd_gridview.setOnItemClickListener { parent, view, position, id -> var item= style_grid.adapter.getItem(position) as photourl println("${item.name}")// 이렇게 데이터 받을수 있고... } Toast.makeText(this,"아직 나의 헤어 기록이 없어요!",Toast.LENGTH_SHORT).show() } else{ mhd_gridview.visibility=View.VISIBLE isexist.visibility=View.INVISIBLE // mhd_iv1.top=110 var adapter = MyAdapter( applicationContext, R.layout.mhdgrid_adapter, // GridView 항목의 레이아웃 row.xml userDTO,1 ) mhd_gridview.adapter = adapter mhd_gridview.setOnItemClickListener { parent, view, position, id -> var item= style_grid.adapter.getItem(position) as photourl println("${item.name}")// 이렇게 데이터 받을수 있고... } } }else{ println("fail") } } } }
1
null
1
1
dc08834dafcef20209ba15bcff114f9f55775913
10,246
android_practice
Apache License 2.0
app/src/main/java/com/azuredragon/app/ui/launchrouter/LaunchRouterFragment.kt
bastionkid
536,519,741
false
null
package com.azuredragon.app.ui.launchrouter import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.runtime.getValue import androidx.compose.ui.graphics.Color import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.azuredragon.app.R import com.azuredragon.core.ui.compose.composeWithSurface import com.azuredragon.core.ui.navigation.getNavOptionsForPopUpToSelfInclusive import com.azuredragon.core.ui.navigation.navigateToDeepLinkSafely class LaunchRouterFragment: Fragment() { private val viewModel: LaunchRouterViewModel by viewModels() @OptIn(ExperimentalLifecycleComposeApi::class) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return composeWithSurface( context = requireContext(), backgroundColor = Color.Transparent, statusBarColor = Color.Transparent, navigationBarColor = Color.Transparent, ) { val uiState by viewModel.launchRoute.collectAsStateWithLifecycle() when (uiState) { LaunchRoute.Login -> { navigateToDeepLink("app://azuredragon.com/login") } LaunchRoute.Home -> { navigateToDeepLink("app://azuredragon.com/home") } else -> { // default is null so no need to do anything here } } } } private fun navigateToDeepLink(deepLink: String) { navigateToDeepLinkSafely( currentDestinationId = R.id.launchRouterFragment, deepLink = deepLink, navOptions = getNavOptionsForPopUpToSelfInclusive(R.id.launchRouterFragment), ) } }
1
Kotlin
0
0
ca22bbdfc1c6e9263d33693f03e1e67d7cef2630
2,021
android-app-template
Apache License 2.0
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/Parallelize.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: Parallelize * * Full name: System`Parallelize * * Usage: Parallelize[expr] evaluates expr using automatic parallelization. * * DistributedContexts :> $Context * Options: Method -> Automatic * * HoldFirst * Attributes: Protected * * local: paclet:ref/Parallelize * Documentation: web: http://reference.wolfram.com/language/ref/Parallelize.html * * Definitions: Parallelize[Parallel`Kernels`Private`args$___] := (Parallel`Protected`doAutolaunch[TrueQ[Parallel`Static`$enableLaunchFeedback]]; Parallelize[Parallel`Kernels`Private`args$]) * * Own values: None * * Down values: Parallelize[Parallel`Kernels`Private`args$___] := (Parallel`Protected`doAutolaunch[TrueQ[Parallel`Static`$enableLaunchFeedback]]; Parallelize[Parallel`Kernels`Private`args$]) * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun parallelize(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("Parallelize", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,393
mathemagika
Apache License 2.0
app/src/main/java/colorpickerlayout/inlacou/bvapps/com/colorpickerlayout/ExampleColorPickerView.kt
inlacou
114,781,033
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 9, "XML": 17, "Java": 2}
package colorpickerlayout.inlacou.bvapps.com.colorpickerlayout import android.graphics.Color import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.widget.Toast import colorpickerlayout.inlacou.bvapps.com.colorpicklayout.ColorListener import colorpickerlayout.inlacou.bvapps.com.colorpicklayout.ColorPickLayout import colorpickerlayout.inlacou.bvapps.com.colorpicklayout.ColorWrapper import colorpickerlayout.inlacou.bvapps.com.colorpicklayout.Utils import kotlinx.android.synthetic.main.activity_example.* class ExampleColorPickerView : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_example) colorPickerLayout.setSelector(colorListener) colorPickerLayout.singleClickListener = object: ColorPickLayout.SingleClickListener{ override fun onSingleClick() { Toast.makeText(this@ExampleColorPickerView, "Single click", Toast.LENGTH_SHORT).show() } } Log.d("color", Utils.getColorHtml(Color.BLACK)) Log.d("color", ""+Color.parseColor("#DDDDDD")) } private val colorListener = object: ColorListener { override fun onColorSelected(envelope: ColorWrapper) { colorDisplay.setBackgroundColor(envelope.color) } } }
1
null
1
1
7aa713ab12df88432f9e4d7d81ae810a74b67e15
1,298
ColorPickLayout
MIT License
app/src/main/java/top/rainysummer/openhappyhackingcalendar/MonthActivity.kt
lzcapp
332,923,922
false
null
package top.rainysummer.openhappyhackingcalendar import android.annotation.SuppressLint import android.content.Intent import android.os.Build import android.os.Bundle import android.util.TypedValue import android.view.* import android.view.GestureDetector.SimpleOnGestureListener import android.widget.LinearLayout import android.widget.TableLayout import android.widget.TableRow import android.widget.TextView import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import com.xhinliang.lunarcalendar.LunarCalendar import java.util.* class MonthActivity : AppCompatActivity() { @SuppressLint("ClickableViewAccessibility") @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_month) val calendar: Calendar = Calendar.getInstance() val dateNum = calendar.get(Calendar.DATE) val yearNum = calendar.get(Calendar.YEAR) val monthNum = calendar.get(Calendar.MONTH) val monthName = arrayOf( "January 一月", "February 二月", "March 三月", "April 四月", "May 五月", "June 六月", "July 七月", "August 八月", "September 九月", "October 十月", "November 十一月", "December 十二月" ) val month = monthName[monthNum] val textMonth = findViewById<TextView>(R.id.textMonth) textMonth.text = month val lunar = LunarCalendar.obtainCalendar(yearNum, monthNum + 1, dateNum) val td_num: Int = if (lunar.lunarMonth == "腊") { yearNum - 4 } else { yearNum - 3 } val tian = arrayOf("癸", "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬") val di = arrayOf("亥", "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌") val lunarYear = tian[td_num % 10] + di[td_num % 12] + "年" val textYear = findViewById<TextView>(R.id.textYear) textYear.text = buildString { append(yearNum.toString()) append(" · ") append(lunarYear) } val startOfMonth = Calendar.getInstance() startOfMonth.set(yearNum, monthNum, 1) var weekIndex: Int = startOfMonth.get(Calendar.DAY_OF_WEEK) - 2 if (weekIndex == -1) { weekIndex = 6 } val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH) for (i in 0 until daysInMonth) { val lunarCalender = LunarCalendar.obtainCalendar(yearNum, monthNum + 1, i + 1) val index = weekIndex + i val wk = index % 7 val it = index / 7 val weekid: Int = resources.getIdentifier("week$it", "id", packageName) val weekrow = findViewById<TableRow>(weekid) val lpweek: LinearLayout.LayoutParams = weekrow.layoutParams as TableLayout.LayoutParams lpweek.topMargin = 50 weekrow.layoutParams = lpweek weekrow.visibility = View.VISIBLE val chnweekid: Int = resources.getIdentifier("chnweek$it", "id", packageName) val chnweekrow = findViewById<TableRow>(chnweekid) val lpchnweek: LinearLayout.LayoutParams = chnweekrow.layoutParams as TableLayout.LayoutParams lpchnweek.topMargin = 0 chnweekrow.layoutParams = lpchnweek chnweekrow.visibility = View.VISIBLE; val dayid: Int = resources.getIdentifier("day$it$wk", "id", packageName) val daycell = findViewById<TextView>(dayid) daycell.text = (i + 1).toString() daycell.width = 120 daycell.setPadding(0, 0, 0, 0) val chnid: Int = resources.getIdentifier("chn$it$wk", "id", packageName) val chndaycell = findViewById<TextView>(chnid) val festivals = lunarCalender.festivals var festivalStr = "" for (festival in festivals.set) { festivalStr += festival } if (festivalStr != "") { chndaycell.text = festivalStr chndaycell.setTextColor(resources.getColor(android.R.color.holo_red_light, theme)) } else { chndaycell.text = lunarCalender.lunarDay } chndaycell.width = 120 chndaycell.includeFontPadding = false chndaycell.height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 55F, this.resources.displayMetrics).toInt() chndaycell.setPadding(0, 0, 0, 0) val today = calendar.get(Calendar.DATE) + weekIndex - 1 val wkToday = today % 7 val itToday = today / 7 val idDayToday: Int = resources.getIdentifier("day$itToday$wkToday", "id", packageName) val idChnToday: Int = resources.getIdentifier("chn$itToday$wkToday", "id", packageName) val cellDayToday = findViewById<TextView>(idDayToday) val cellChnToday = findViewById<TextView>(idChnToday) //cellDayToday.setTypeface(cellDayToday.typeface, Typeface.BOLD); //cellChnToday.setTypeface(cellChnToday.typeface, Typeface.BOLD); cellDayToday.setTextColor(resources.getColor(android.R.color.holo_blue_dark, theme)) cellChnToday.setTextColor(resources.getColor(android.R.color.holo_blue_dark, theme)) } val detector = GestureDetector(this, object : SimpleOnGestureListener() { override fun onDoubleTap(e: MotionEvent): Boolean { val intent = Intent() intent.setClass(this@MonthActivity, DayActivity::class.java) startActivity(intent) this@MonthActivity.finish() return true } override fun onDoubleTapEvent(e: MotionEvent): Boolean { return true } override fun onDown(e: MotionEvent): Boolean { return true } }) val layout = findViewById<LinearLayout>(R.id.layout1) layout.setOnTouchListener { _, event -> detector.onTouchEvent(event) } } }
1
null
1
2
96a6517fc5b1600c3c80bacb8f4c070fdb9fb12e
6,260
Android.OHHC
Apache License 2.0
src/test/kotlin/g1301_1400/s1351_count_negative_numbers_in_a_sorted_matrix/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
package g1301_1400.s1351_count_negative_numbers_in_a_sorted_matrix import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun countNegatives() { assertThat( Solution() .countNegatives( arrayOf( intArrayOf(4, 3, 2, -1), intArrayOf(3, 2, 1, -1), intArrayOf(1, 1, -1, -2), intArrayOf(-1, -1, -2, -3) ) ), equalTo(8) ) } @Test fun countNegatives2() { assertThat( Solution().countNegatives(arrayOf(intArrayOf(3, 2), intArrayOf(1, 0))), equalTo(0) ) } }
0
Kotlin
20
43
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
776
LeetCode-in-Kotlin
MIT License
plugins/music_player/android/src/main/kotlin/com/xhhold/plugin/music_player/MediaNotificationManager.kt
xiaohuihuiold
380,486,716
false
null
package com.xhhold.plugin.music_player import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import androidx.core.app.NotificationCompat import androidx.media.session.MediaButtonReceiver import com.xhhold.plugin.music_player.drawable.TextDrawable import com.xhhold.plugin.music_player.ext.toBitmap class MediaNotificationManager(private val service: MusicService) { private val notificationManager = service.getSystemService(NotificationManager::class.java).apply { cancelAll() } private val playAction: NotificationCompat.Action private val pauseAction: NotificationCompat.Action private val skipPreviousAction: NotificationCompat.Action private val skipNextAction: NotificationCompat.Action private val favoriteAction: NotificationCompat.Action private val unFavoriteAction: NotificationCompat.Action companion object { const val TAG = "MediaNotificationManager" const val ID = 0x01 const val CHANNEL_ID = "com.xhhold.plugin.music_player.channel" } init { playAction = createAction(R.drawable.ic_play, R.string.play, PlaybackStateCompat.ACTION_PLAY) pauseAction = createAction(R.drawable.ic_pause, R.string.pause, PlaybackStateCompat.ACTION_PAUSE) skipPreviousAction = createAction( R.drawable.ic_skip_previous, R.string.skip_previous, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS ) skipNextAction = createAction( R.drawable.ic_skip_next, R.string.skip_next, PlaybackStateCompat.ACTION_SKIP_TO_NEXT ) favoriteAction = createAction( R.drawable.ic_favorite_border, R.string.favorite, PlaybackStateCompat.ACTION_SET_RATING ) unFavoriteAction = createAction( R.drawable.ic_favorite, R.string.unfavorite, PlaybackStateCompat.ACTION_SET_RATING ) } fun start( description: MediaDescriptionCompat, state: PlaybackStateCompat, token: MediaSessionCompat.Token ) { service.startForeground(ID, getNotification(description, state, token).build()) } fun update( description: MediaDescriptionCompat, state: PlaybackStateCompat, token: MediaSessionCompat.Token ) { val notification = getNotification(description, state, token) notificationManager.notify(ID, notification.build()) } fun stop(remove: Boolean) { service.stopForeground(remove) } private fun getNotification( description: MediaDescriptionCompat, state: PlaybackStateCompat, token: MediaSessionCompat.Token ): NotificationCompat.Builder { if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) { val channel = NotificationChannel( CHANNEL_ID, "MediaSession", NotificationManager.IMPORTANCE_MIN ).apply { this.description = "MediaSession" } notificationManager.createNotificationChannel(channel) } return NotificationCompat.Builder(service, CHANNEL_ID).apply { val icon = description.iconUri val text = (description.title ?: description.subtitle ?: "").toString() val bitmap = if (icon != null) { icon.toBitmap(service.contentResolver, text) } else { val drawable = TextDrawable(text) drawable.toBitmap(512, 512) } setColorized(true) setContentTitle(description.title) setContentText(description.subtitle) setSmallIcon(R.drawable.ic_music) setVisibility(NotificationCompat.VISIBILITY_PUBLIC) setDeleteIntent(createIntent(PlaybackStateCompat.ACTION_STOP)) setLargeIcon(bitmap) addAction(skipPreviousAction) addAction(if (state.state != PlaybackStateCompat.STATE_PLAYING) playAction else pauseAction) addAction(skipNextAction) setStyle( androidx.media.app.NotificationCompat.MediaStyle() .setMediaSession(token) .setShowActionsInCompactView(0, 1, 2) .setShowCancelButton(true) .setCancelButtonIntent(createIntent(PlaybackStateCompat.ACTION_STOP)) ) } } private fun createIntent(action: Long): PendingIntent = MediaButtonReceiver.buildMediaButtonPendingIntent(service, action) private fun createAction(icon: Int, title: Int, action: Long): NotificationCompat.Action = NotificationCompat.Action( icon, service.getString(title), MediaButtonReceiver.buildMediaButtonPendingIntent(service, action) ) }
0
Kotlin
0
0
077ed5c596f5212975478fe1c3f9f8644d8fb045
5,260
listening
Apache License 2.0
apps/androidData/src/main/java/com/baptistecarlier/am24/data/repository/StorageRepositoryImpl.kt
BapNesS
781,361,632
false
{"Kotlin": 58941}
package com.baptistecarlier.am24.data.repository import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.preferencesDataStore import com.baptistecarlier.am24.shared.domain.repository.StorageRepository import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map private object OnboardingKeys { val keyListMode = booleanPreferencesKey("keyListMode") } internal val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "OmgAppSettings") class StorageRepositoryImpl( private val dataStore: DataStore<Preferences>, ) : StorageRepository { override suspend fun getListMode(): Boolean { return dataStore.data.map { it[OnboardingKeys.keyListMode] ?: true }.first() } override suspend fun updateListMode(isList: Boolean) { dataStore.edit { it[OnboardingKeys.keyListMode] = isList } } }
0
Kotlin
0
3
8a07812369181db3a041fe7c9f78a99bbc8ab717
1,077
goat-multiplatform
Apache License 2.0
src/main/kotlin/archangeldlt/ArchangelConfig.kt
archangel-dlt
161,204,132
false
{"Gradle": 2, "Markdown": 3, "INI": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Java Properties": 2, "Java": 4, "XSLT": 1, "XML": 2, "Kotlin": 16, "AsciiDoc": 1}
package archangeldlt import tornadofx.ConfigProperties import kotlin.reflect.KProperty class ConfigProp(private val key: String, private val defaultValue: String) { operator fun getValue(thisRef: ArchangelConfig, property: KProperty<*>): String { return thisRef.config.string(key, defaultValue) } operator fun setValue(thisRef: ArchangelConfig, property: KProperty<*>, value: String) { thisRef.config.set(key, value) thisRef.config.save() } } class ArchangelConfig(val config: ConfigProperties) { private val KEY_ENDPOINT = "endpoints" private val KEY_USERADDRESS = "userAddress" private val KEY_WALLETFILE = "walletFile" private val KEY_PASSWORD = "password" var endpoint: String by ConfigProp(KEY_ENDPOINT, "https://blockchain.surrey.ac.uk/ethereum/") var userAddress: String by ConfigProp(KEY_USERADDRESS, "0x0000000000000000000000000000000000000000") var walletFile: String by ConfigProp(KEY_WALLETFILE, "") var password: String by ConfigProp(KEY_PASSWORD, "") }
0
Kotlin
0
1
24e5c7831f8b7370e16d4786724243997bebe640
1,044
archangel-desktop
MIT License
library/location/src/main/kotlin/xyz/fcampbell/rxplayservices/locationservices/action/geocode/ReverseGeocode.kt
francoiscampbell
75,945,848
true
null
package xyz.fcampbell.rxplayservices.locationservices.action.geocode import android.content.Context import android.location.Address import android.location.Geocoder import io.reactivex.Observable import io.reactivex.ObservableEmitter import io.reactivex.ObservableOnSubscribe import io.reactivex.schedulers.Schedulers import java.io.IOException import java.util.* internal class ReverseGeocode( private val ctx: Context, private val locale: Locale, private val latitude: Double, private val longitude: Double, private val maxResults: Int ) : ObservableOnSubscribe<List<Address>> { override fun subscribe(emitter: ObservableEmitter<List<Address>>) { val geocoder = Geocoder(ctx, locale) try { emitter.onNext(geocoder.getFromLocation(latitude, longitude, maxResults)) emitter.onComplete() } catch (e: IOException) { // If it's a service not available error try a different approach using google web service if (e.message.equals("Service not Available", ignoreCase = true)) { Observable.create(FallbackReverseGeocodeFromEmitter(locale, latitude, longitude, maxResults)) .subscribeOn(Schedulers.io()) .subscribe({ emitter.onNext(it) }, { emitter.onError(it) }, { emitter.onComplete() }) } else { emitter.onError(e) } } } }
1
Kotlin
2
10
b7461e4534a81d78f7bf70a6047395b059e61c3c
1,611
RxPlayServices
Apache License 2.0
platform/platform-impl/src/com/intellij/ide/CommandLineProcessor.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector import com.intellij.ide.CommandLineProcessorResult.Companion.createError import com.intellij.ide.actions.ShowLogAction import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.lightEdit.LightEdit import com.intellij.ide.lightEdit.LightEditFeatureUsagesUtil import com.intellij.ide.lightEdit.LightEditFeatureUsagesUtil.OpenPlace import com.intellij.ide.lightEdit.LightEditService import com.intellij.ide.lightEdit.LightEditUtil import com.intellij.ide.util.PsiNavigationSupport import com.intellij.idea.CommandLineArgs import com.intellij.idea.findStarter import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.application.* import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.platform.CommandLineProjectOpenProcessor import com.intellij.platform.PlatformProjectOpenProcessor.Companion.configureToOpenDotIdeaOrCreateNewIfNotExists import com.intellij.util.PlatformUtils import com.intellij.util.io.URLUtil import io.netty.handler.codec.http.QueryStringDecoder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.VisibleForTesting import java.nio.file.InvalidPathException import java.nio.file.Path import java.util.concurrent.CancellationException import java.util.concurrent.CompletableFuture object CommandLineProcessor { private val LOG = logger<CommandLineProcessor>() private const val OPTION_WAIT = "--wait" @JvmField val OK_FUTURE: CompletableFuture<CliResult> = CompletableFuture.completedFuture(CliResult.OK) @ApiStatus.Internal const val SCHEME_INTERNAL = "!!!internal!!!" @VisibleForTesting @ApiStatus.Internal suspend fun doOpenFileOrProject(file: Path, shouldWait: Boolean): CommandLineProcessorResult { var project: Project? = null if (!LightEditUtil.isForceOpenInLightEditMode()) { val options = OpenProjectTask { // do not check for .ipr files in the specified directory // (@develar: it is existing behaviour, I am not fully sure that it is correct) preventIprLookup = true configureToOpenDotIdeaOrCreateNewIfNotExists(projectDir = file, projectToClose = null) } project = ProjectUtil.openOrImportAsync(file, options) } return if (project == null) { doOpenFile(ioFile = file, line = -1, column = -1, tempProject = false, shouldWait = shouldWait) } else { CommandLineProcessorResult(project, if (shouldWait) CommandLineWaitingManager.getInstance().addHookForProject(project) else OK_FUTURE) } } private suspend fun doOpenFile(ioFile: Path, line: Int, column: Int, tempProject: Boolean, shouldWait: Boolean): CommandLineProcessorResult { var projects = if (tempProject) emptyList() else ProjectManagerEx.getOpenProjects() if (!tempProject && projects.isEmpty() && PlatformUtils.isDataGrip()) { val recentProjectManager = RecentProjectsManager.getInstance() if (recentProjectManager.willReopenProjectOnStart() && recentProjectManager.reopenLastProjectsOnStart()) { projects = ProjectManagerEx.getOpenProjects() } } val file = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(ioFile) if (file == null) { if (LightEditUtil.isLightEditEnabled()) { val lightEditProject = LightEditUtil.openFile(ioFile, true) if (lightEditProject != null) { val future = if (shouldWait) CommandLineWaitingManager.getInstance().addHookForPath(ioFile) else OK_FUTURE return CommandLineProcessorResult(lightEditProject, future) } } return createError(IdeBundle.message("dialog.message.can.not.open.file", ioFile.toString())) } if (projects.isEmpty()) { val project = CommandLineProjectOpenProcessor.getInstance().openProjectAndFile(ioFile, line, column, tempProject) ?: return createError(IdeBundle.message("dialog.message.no.project.found.to.open.file.in")) return CommandLineProcessorResult(project, if (shouldWait) CommandLineWaitingManager.getInstance().addHookForFile(file) else OK_FUTURE) } NonProjectFileWritingAccessProvider.allowWriting(listOf(file)) val project: Project? if (LightEditUtil.isForceOpenInLightEditMode()) { project = LightEditService.getInstance().openFile(file) LightEditFeatureUsagesUtil.logFileOpen(project, OpenPlace.CommandLine) } else { project = findBestProject(file, projects) val navigatable = if (line > 0) { OpenFileDescriptor(project, file, line - 1, column.coerceAtLeast(0)) } else { PsiNavigationSupport.getInstance().createNavigatable(project, file, -1) } project.coroutineScope.launch(Dispatchers.EDT) { navigatable.navigate(true) } } return CommandLineProcessorResult(project, if (shouldWait) CommandLineWaitingManager.getInstance().addHookForFile(file) else OK_FUTURE) } private suspend fun findBestProject(file: VirtualFile, projects: List<Project>): Project { for (project in projects) { val fileIndex = ProjectFileIndex.getInstance(project) if (readAction { fileIndex.isInContent(file) }) { return project } } val project = IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project return if (project != null && !LightEdit.owns(project)) project else projects.first() } @ApiStatus.Internal fun scheduleProcessProtocolCommand(rawUri: @NlsSafe String) { ApplicationManager.getApplication().coroutineScope.launch { processProtocolCommand(rawUri) } } @ApiStatus.Internal suspend fun processProtocolCommand(rawUri: @NlsSafe String): CliResult { LOG.info("external URI request:\n$rawUri") check(!ApplicationManager.getApplication().isHeadlessEnvironment) { "cannot process URI requests in headless state" } val internal = rawUri.startsWith(SCHEME_INTERNAL) val uri = if (internal) rawUri.substring(SCHEME_INTERNAL.length) else rawUri val separatorStart = uri.indexOf(URLUtil.SCHEME_SEPARATOR) require(separatorStart >= 0) { uri } val scheme = uri.substring(0, separatorStart) val query = uri.substring(separatorStart + URLUtil.SCHEME_SEPARATOR.length) val cliResult = try { if (internal) processInternalProtocol(query) else processProtocol(scheme, query) } catch (e: CancellationException) { throw e } catch (e: Throwable) { LOG.error(e) CliResult(0, IdeBundle.message("ide.protocol.exception", e.javaClass.simpleName, e.message)) } if (cliResult.message != null) { val title = IdeBundle.message("ide.protocol.cannot.title") Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, title, cliResult.message!!, NotificationType.WARNING) .addAction(ShowLogAction.notificationAction()) .notify(null) } return cliResult } private val PROTOCOL_EP_NAME = ExtensionPointName<ProtocolHandler>("com.intellij.protocolHandler") private suspend fun processProtocol(scheme: String, query: String): CliResult { for (handler in PROTOCOL_EP_NAME.iterable) { if (scheme == handler.scheme) { return handler.process(query) } } return CliResult(/* exitCode = */ 0, /* message = */ IdeBundle.message("ide.protocol.unsupported", scheme)) } private suspend fun processInternalProtocol(query: String): CliResult { val decoder = QueryStringDecoder(query) if ("open" == decoder.path().trimEnd('/')) { val parameters = decoder.parameters() val fileStr = parameters["file"]?.lastOrNull() if (!fileStr.isNullOrBlank()) { val file = parseFilePath(fileStr, null) if (file != null) { val line = parameters["line"]?.lastOrNull()?.toIntOrNull() ?: -1 val column = parameters["column"]?.lastOrNull()?.toIntOrNull() ?: -1 val (project) = openFileOrProject(file = file, line = line, column = column, tempProject = false, shouldWait = false, lightEditMode = false) LifecycleUsageTriggerCollector.onProtocolOpenCommandHandled(project) return CliResult.OK } } } return CliResult(0, IdeBundle.message("ide.protocol.internal.bad.query", query)) } suspend fun processExternalCommandLine(args: List<String>, currentDirectory: String?): CommandLineProcessorResult { val logMessage = StringBuilder() logMessage.append("External command line:").append('\n') logMessage.append("Dir: ").append(currentDirectory).append('\n') for (arg in args) { logMessage.append(arg).append('\n') } logMessage.append("-----") LOG.info(logMessage.toString()) if (args.isEmpty()) { return CommandLineProcessorResult(project = null, future = OK_FUTURE) } val result = processApplicationStarters(args, currentDirectory) return result ?: processOpenFile(args, currentDirectory) } private suspend fun processApplicationStarters(args: List<String>, currentDirectory: String?): CommandLineProcessorResult? { val command = args.first() val starter = try { findStarter(command) ?: return null } catch (e: CancellationException) { throw e } catch (e: Throwable) { LOG.error(e) return null } if (!starter.canProcessExternalCommandLine()) { return createError(IdeBundle.message("dialog.message.only.one.instance.can.be.run.at.time", ApplicationNamesInfo.getInstance().productName)) } LOG.info("Processing command with $starter") val requiredModality = starter.requiredModality if (requiredModality == ApplicationStarter.NOT_IN_EDT) { val result = starter.processExternalCommandLine(args, currentDirectory) return CommandLineProcessorResult(project = null, result = result) } val modalityState = if (requiredModality == ApplicationStarter.ANY_MODALITY) { ModalityState.any() } else { ModalityState.defaultModalityState() } return withContext(Dispatchers.EDT + modalityState.asContextElement()) { val result = starter.processExternalCommandLine(args, currentDirectory) CommandLineProcessorResult(project = null, result = result) } } private suspend fun processOpenFile(args: List<String>, currentDirectory: String?): CommandLineProcessorResult { var projectAndCallback: CommandLineProcessorResult? = null var line = -1 var column = -1 var tempProject = false val shouldWait = args.contains(OPTION_WAIT) var lightEditMode = false var i = 0 while (i < args.size) { var arg = args[i] if (CommandLineArgs.isKnownArgument(arg) || OPTION_WAIT == arg) { i++ continue } if (arg == "-l" || arg == "--line") { i++ if (i == args.size) break line = args[i].toIntOrNull() ?: -1 i++ continue } if (arg == "-c" || arg == "--column") { i++ if (i == args.size) break column = args[i].toIntOrNull() ?: -1 i++ continue } if (arg == "--temp-project") { tempProject = true i++ continue } if (arg == "-e" || arg == "--edit") { lightEditMode = true i++ continue } if (arg == "-p" || arg == "--project") { // Skip, replaced with the opposite option above // TODO<rv>: Remove in future versions i++ continue } if (StringUtilRt.isQuotedString(arg)) { arg = StringUtilRt.unquoteString(arg) } val file = parseFilePath(arg, currentDirectory) ?: return createError(IdeBundle.message("dialog.message.invalid.path", arg)) projectAndCallback = openFileOrProject(file = file, line = line, column = column, tempProject = tempProject, shouldWait = shouldWait, lightEditMode = lightEditMode) if (shouldWait) { break } column = -1 line = column tempProject = false i++ } projectAndCallback?.let { return it } if (shouldWait) { return CommandLineProcessorResult( project = null, result = CliResult(1, IdeBundle.message("dialog.message.wait.must.be.supplied.with.file.or.project.to.wait.for")) ) } else if (lightEditMode) { LightEditService.getInstance().showEditorWindow() return CommandLineProcessorResult(project = LightEditService.getInstance().project, future = OK_FUTURE) } else { return CommandLineProcessorResult(project = null, future = OK_FUTURE) } } private fun parseFilePath(path: String, currentDirectory: String?): Path? { try { // handle paths like '/file/foo\qwe' var file = Path.of(FileUtilRt.toSystemDependentName(path)) if (!file.isAbsolute) { file = if (currentDirectory == null) file.toAbsolutePath() else Path.of(currentDirectory).resolve(file) } file.normalize() return file } catch (e: InvalidPathException) { LOG.warn(e) return null } } private suspend fun openFileOrProject(file: Path, line: Int, column: Int, tempProject: Boolean, shouldWait: Boolean, lightEditMode: Boolean): CommandLineProcessorResult { return LightEditUtil.computeWithCommandLineOptions(shouldWait, lightEditMode).use { val asFile = line != -1 || tempProject if (asFile) { doOpenFile(file, line, column, tempProject, shouldWait) } else { doOpenFileOrProject(file, shouldWait) } } } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
15,239
intellij-community
Apache License 2.0
src/ru/alexxxdev/kGen/ClassSpec.kt
alexxxdev
84,447,501
false
null
package ru.alexxxdev.kGen import ru.alexxxdev.kGen.FieldSpec.PropertyType import ru.alexxxdev.kGen.FieldSpec.PropertyType.READONLY import ru.alexxxdev.kGen.FieldSpec.ValueType import ru.alexxxdev.kGen.FieldSpec.ValueType.NOTNULL /** * Created by alexxxdev on 28.02.17. */ class ClassSpec(val kind: Kind, internal val name: String) : IAppendable { enum class Kind { CLASS, INTERFACE, OBJECT } private var imports = mutableListOf<TypeName>() private var fields = mutableListOf<FieldSpec>() private var methods = mutableListOf<MethodSpec>() private var parameterized = mutableListOf<ParameterizedName>() private var modifiers: Array<Modifier> = emptyArray() val listImports get() = this.imports.distinctBy { (it as ru.alexxxdev.kGen.ClassName).canonicalName } operator fun Modifier.unaryPlus() { modifiers = modifiers.plus(this) } operator fun ParameterizedName.unaryPlus() { parameterized.add(this) } fun field(name: String, propertyType: PropertyType = READONLY, valueType: ValueType = NOTNULL, init: FieldSpec.() -> String) = addField(FieldSpec(name, propertyType, valueType), init) fun method(name: String, vararg mods: Modifier, init: MethodSpec.() -> Unit) = addMethod(MethodSpec(name), mods = *mods, init = init) private fun addMethod(methodSpec: MethodSpec, vararg mods: Modifier, init: MethodSpec.() -> Unit): MethodSpec { methodSpec.init() mods.forEach { methodSpec.addModificator(it) } methodSpec.build() methods.add(methodSpec) return methodSpec } private fun addField(fieldSpec: FieldSpec, init: FieldSpec.() -> String): FieldSpec { fieldSpec.initializer = fieldSpec.init() fieldSpec.build() fields.add(fieldSpec) return fieldSpec } fun build() { methods.forEach { imports.addAll(it.listImports) } fields.forEach { imports.addAll(it.listImports) } } override fun writeTo(codeWriter: CodeWriter) { modifiers.forEach { when (it) { Modifier.DEFAULT -> { } else -> { codeWriter.out("${it.name.toLowerCase()} ") } } } when (kind) { ClassSpec.Kind.CLASS -> codeWriter.out("class $name") ClassSpec.Kind.INTERFACE -> codeWriter.out("interface $name") ClassSpec.Kind.OBJECT -> codeWriter.out("object $name") } if (parameterized.isNotEmpty()) { codeWriter.out("<") parameterized.forEachIndexed { index, parameterizedName -> if (index > 0) codeWriter.out(",") if (parameterizedName.name == null) { parameterizedName.className?.let { codeWriter.out(it.name) } } else { codeWriter.out(parameterizedName.name) parameterizedName.className?.let { codeWriter.out(": ${it.name}") } } } codeWriter.out(">") } codeWriter.out("{") codeWriter.indent() fields.sortedBy { it.name } .forEach { codeWriter.out("\n") it.writeTo(codeWriter) } methods.sortedBy { it.name } .forEach { codeWriter.out("\n\n") it.writeTo(codeWriter) } codeWriter.unindent() codeWriter.out("\n") codeWriter.out("}") } }
0
Kotlin
0
0
07ab50d0260e64e722c215cf40010df4b72f5c6e
3,733
kGen
Apache License 2.0
src/main/kotlin/ch/sourcemotion/vertx/kinesis/consumer/orchestra/impl/redis/lua/LuaScriptLoader.kt
wem
253,237,315
false
null
package ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl.redis.lua import io.vertx.kotlin.coroutines.await import io.vertx.redis.client.Command import io.vertx.redis.client.Redis import io.vertx.redis.client.Request /** * Simple a loader with cache of LUA scripts used for short, fast operations against Redis. */ internal object LuaScriptLoader { private val scriptCache = HashMap<LuaScriptDescription, String>() suspend fun loadScriptSha(scriptDescription: LuaScriptDescription, redis: Redis): String { return scriptCache.getOrPut(scriptDescription) { val scriptContent = LuaScriptLoader::class.java.getResourceAsStream(scriptDescription.path) .use { ins -> ins.bufferedReader(Charsets.UTF_8).use { reader -> reader.readText() } } return loadScriptRedis(scriptContent, redis) } } private suspend fun loadScriptRedis(scriptContent: String, redis: Redis): String { return redis.send(Request.cmd(Command.SCRIPT).arg("LOAD").arg(scriptContent)).await().toString() } }
10
Kotlin
0
3
a2290613daf15c96034bf5d3d67103ddc8741776
1,062
vertx-kinesis-consumer-orchestra
MIT License
app/src/main/java/org/wikipedia/descriptions/DescriptionEditReviewView.kt
greatfire
460,298,221
true
{"Kotlin": 2932557, "Java": 68018, "C++": 37990, "Python": 23673, "CMake": 1104, "Jinja": 533, "Shell": 521}
package org.wikipedia.descriptions import android.content.Context import android.net.Uri import android.util.AttributeSet import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import org.wikipedia.databinding.ViewDescriptionEditReviewBinding import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_ARTICLE_DESCRIPTION import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_DEFAULT import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_IMAGE_CAPTION import org.wikipedia.suggestededits.PageSummaryForEdit import org.wikipedia.util.L10nUtil import org.wikipedia.util.StringUtil import org.wikipedia.views.ViewUtil class DescriptionEditReviewView constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) { private val binding = ViewDescriptionEditReviewBinding.inflate(LayoutInflater.from(context), this) val isShowing: Boolean get() = visibility == VISIBLE fun show() { visibility = VISIBLE } fun hide() { visibility = GONE } fun setSummary(summaryForEdit: PageSummaryForEdit, description: String, captionReview: Boolean) { L10nUtil.setConditionalLayoutDirection(this, summaryForEdit.lang) if (captionReview) { setGalleryReviewView(summaryForEdit, description) binding.licenseView.buildLicenseNotice(ARG_NOTICE_IMAGE_CAPTION) } else { setDescriptionReviewView(summaryForEdit, description) binding.licenseView.buildLicenseNotice(if (summaryForEdit.description.isNullOrEmpty()) ARG_NOTICE_ARTICLE_DESCRIPTION else ARG_NOTICE_DEFAULT) } } private fun setDescriptionReviewView(summaryForEdit: PageSummaryForEdit, description: String) { binding.galleryContainer.visibility = GONE binding.articleTitle.text = StringUtil.fromHtml(summaryForEdit.displayTitle) binding.articleSubtitle.text = description binding.articleExtract.text = StringUtil.fromHtml(summaryForEdit.extractHtml) if (summaryForEdit.thumbnailUrl.isNullOrBlank()) { binding.articleImage.visibility = GONE binding.articleExtract.maxLines = ARTICLE_EXTRACT_MAX_LINE_WITHOUT_IMAGE } else { binding.articleImage.visibility = VISIBLE binding.articleImage.loadImage(Uri.parse(summaryForEdit.getPreferredSizeThumbnailUrl())) binding.articleExtract.maxLines = ARTICLE_EXTRACT_MAX_LINE_WITH_IMAGE } } private fun setGalleryReviewView(summaryForEdit: PageSummaryForEdit, description: String) { binding.articleContainer.visibility = GONE binding.indicatorDivider.visibility = GONE binding.galleryDescriptionText.text = StringUtil.fromHtml(description) if (summaryForEdit.thumbnailUrl.isNullOrBlank()) { binding.galleryImage.visibility = GONE } else { binding.galleryImage.visibility = VISIBLE ViewUtil.loadImage(binding.galleryImage, summaryForEdit.getPreferredSizeThumbnailUrl()) } binding.licenseView.darkLicenseView() } companion object { const val ARTICLE_EXTRACT_MAX_LINE_WITH_IMAGE = 5 const val ARTICLE_EXTRACT_MAX_LINE_WITHOUT_IMAGE = 15 } }
29
Kotlin
624
38
8c8de602274b0132fc5d22b394a2c47fcd0bf2eb
3,345
apps-android-wikipedia-envoy
Apache License 2.0
src/test/kotlin/org/rust/ide/inspections/RsLiteralOutOfRangeInspectionTest.kt
intellij-rust
42,619,487
false
{"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import org.junit.Test class RsLiteralOutOfRangeInspectionTest: RsInspectionsTestBase(RsLiteralOutOfRangeInspection::class) { fun `test declaration max u8`() = checkByText(""" fn main() { let x: u8 = /*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/; } """) fun `test declaration good u8`() = checkByText( """ fn main() { let x: u8 = 255; } """) fun `test declaration good i8`() = checkByText( """ fn main() { let x: i8 = -128; } """) fun `test declaration fix type`() = checkFixByText("Change type of `x` to `u16`", """ fn main() { let x: u8 = /*error descr="The literal `256` does not fit into the type `u8`"*/256/*caret*//*error**/; } """, """ fn main() { let x: u16 = 256; } """) fun `test declaration fix bigger type`() = checkFixByText("Change type of `x` to `u64`", """ fn main() { let x: u8 = /*error descr="The literal `10000000000` does not fit into the type `u8`"*/10_000_000_000/*caret*//*error**/; } """, """ fn main() { let x: u64 = 10_000_000_000; } """.trimIndent()) fun `test declaration max u16`() = checkByText( """ fn main() { let x: u16 = /*error descr="The literal `65536` does not fit into the type `u16`"*/65_536/*error**/; } """) fun `test declaration good i16`() = checkByText( """ fn main() { let x: i16 = -32_768; } """) fun `test declaration max u32`() = checkByText( """ fn main() { let x: u32 = /*error descr="The literal `4294967296` does not fit into the type `u32`"*/4_294_967_296/*error**/; } """) @Test(expected = Throwable::class) // Please remove once const evaluation is fixed fun `test declaration max i32`() = checkByText( """ fn main() { let x: u32 = /*error descr="The literal `2147483648` does not fit into the type `i32`"*/2_147_483_648/*error**/; } """) fun `test declaration good u32`() = checkByText( """ fn main() { let x: u32 = 4_294_967_295; } """) fun `test declaration good i32`() = checkByText( """ fn main() { let x: i32 = -2_147_483_648; } """) @Test(expected = Throwable::class) // Please remove once const evaluation is fixed fun `test declaration max i64`() = checkByText( """ fn main() { let x: i64 = /*error descr="The literal `9223372036854775808` does not fit into the type `i64`"*/9_223_372_036_854_775_808/*error**/; } """) fun `test declaration good i64`() = checkByText( """ fn main() { let x: i64 = 9_223_372_036_854_775_807; } """) @Test(expected = Throwable::class) // Please remove once const evaluation is fixed fun `test declaration max u64`() = checkByText( """ fn main() { let x: u64 = /*error descr="The literal `18446744073709551616` does not fit into the type `u64`"*/18_446_744_073_709_551_616/*error**/; } """) fun `test declaration good u64`() = checkByText( """ fn main() { let x: u64 = 18_446_744_073_709_551_615; } """) fun `test simple assignment to u8`() = checkByText( """ fn main() { let x: u8; x = /*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/; } """) fun `test simple struct literal`() = checkByText( """ struct Foo { x: u8 } fn main() { let f = Foo { x: /*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/ }; } """) fun `test struct literal fix`() = checkFixByText("Change type of `x` to `u16`", """ struct Foo { x: u8 } fn main() { let f = Foo { x: /*error descr="The literal `256` does not fit into the type `u8`"*/256/*caret*//*error**/ }; } """, """ struct Foo { x: u16 } fn main() { let f = Foo { x: 256 }; } """.trimIndent()) fun `test multiple fields struct literal`() = checkByText( """ struct Foo { x: u8, y: u8 } fn main() { let f = Foo { x: 255, y: /*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/ }; } """) fun `test multiple error struct literal`() = checkByText( """ struct Foo { x: u16, y: u8 } fn main() { let f = Foo { x: /*error descr="The literal `100000000` does not fit into the type `u16`"*/100_000_000/*error**/, y: /*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/ }; } """) fun `test indirect struct literal`() = checkByText( """ struct Foo { x: u8 } fn main() { let x = /*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/; let f = Foo { x }; } """) fun `test function call`() = checkByText( """ fn f(arg: u8) -> u8 { arg } fn main() { f(/*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/); } """) fun `test function call many arguments`() = checkByText( """ fn f(arg1: u16, arg2: u8) -> u8 { arg } fn main() { f(256, /*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/); } """) fun `test function call indirect`() = checkByText( """ fn f(arg: u8) -> u8 { arg } fn main() { let a = /*error descr="The literal `256` does not fit into the type `u8`"*/256/*error**/; f(a); } """) }
1,841
Kotlin
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
6,434
intellij-rust
MIT License
sample/src/main/java/ro/dobrescuandrei/demonewlibs/restaurant/editor/RestaurantEditorActivity.kt
irfanirawansukirman
171,591,919
false
null
package ro.dobrescuandrei.demonewlibs.restaurant.editor import android.os.Bundle import android.widget.SeekBar import kotlinx.android.synthetic.main.activity_restaurant_editor.* import org.greenrobot.eventbus.Subscribe import ro.dobrescuandrei.demonewlibs.R import ro.dobrescuandrei.demonewlibs.model.Restaurant import ro.dobrescuandrei.demonewlibs.model.utils.OnRestaurantAddedEvent import ro.dobrescuandrei.demonewlibs.model.utils.OnRestaurantChoosedEvent import ro.dobrescuandrei.demonewlibs.model.utils.RefreshRestaurantListCommand import ro.dobrescuandrei.demonewlibs.router.ActivityRouter import ro.dobrescuandrei.demonewlibs.router.ShowDialog import ro.dobrescuandrei.mvvm.utils.BackgroundEventBus import ro.dobrescuandrei.mvvm.utils.OnEditorModel import ro.dobrescuandrei.utils.setOnTextChangedListener import ro.dobrescuandrei.utils.setupBackIcon class RestaurantEditorActivity : RestaurantEditorAdapter() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) toolbar.setupBackIcon() toolbar.setTitle(if (viewModel.addMode()) R.string.add_restaurant else R.string.edit_restaurant) typeButton.setOnClickListener { ShowDialog.withList(context = this, title = R.string.choose_type, onClick = { index, value -> viewModel..{ type=index+1 } }, values = listOf( getString(R.string.normal), getString(R.string.fast_food))) } ratingSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { viewModel..{ rating=progress+1 } } override fun onStartTrackingTouch(seekBar: SeekBar?) { } override fun onStopTrackingTouch(seekBar: SeekBar?) { } }) nameEditText.setOnTextChangedListener { name -> viewModel..{ it.name=name } } setupChooserDemo() } @Subscribe override fun onAdded(event : OnEditorModel.AddedEvent<Restaurant>) { BackgroundEventBus.post(OnRestaurantAddedEvent(restaurant = event.model)) showToast(R.string.restaurant_added) } @Subscribe override fun onEdited(event : OnEditorModel.EditedEvent<Restaurant>) { showToast(R.string.restaurant_edited) } @Subscribe override fun onAddedOrEdited(event: OnEditorModel.AddedOrEditedEvent<Restaurant>) { BackgroundEventBus.post(RefreshRestaurantListCommand()) finish() } //chooser demo zone fun setupChooserDemo() { simpleChooseDemoButton.setOnClickListener { ActivityRouter.startChooseRestaurantActivity(from = it.context) } pagedChooseDemoButton.setOnClickListener { ActivityRouter.startChoosePagedRestaurantActivity(from = it.context) } } @Subscribe fun onRestaurantChoosed(event : OnRestaurantChoosedEvent) { println(event.restaurant.toString()) } }
0
Kotlin
5
1
f940702c98847e42dc0ce230485da8f35bc32e32
3,240
DobDroidMVVM
Apache License 2.0
core/src/main/java/io/github/thibaultbee/streampack/streamers/interfaces/ICameraStreamer.kt
ThibaultBee
262,623,449
false
null
/* * Copyright (C) 2021 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.thibaultbee.streampack.streamers.interfaces import android.Manifest import android.view.Surface import androidx.annotation.RequiresPermission import com.github.thibaultbee.streampack.streamers.bases.BaseStreamer import com.github.thibaultbee.streampack.streamers.interfaces.settings.IBaseCameraStreamerSettings interface ICameraStreamer { /** * Get/Set current camera id. */ var camera: String /** * Access extended camera settings. */ val settings: IBaseCameraStreamerSettings /** * Starts audio and video capture. * [BaseStreamer.configure] must have been called at least once. * * @see [stopPreview] */ @RequiresPermission(allOf = [Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA]) fun startPreview(previewSurface: Surface, cameraId: String = "0") /** * Stops capture. * It also stops stream if the stream is running. * * @see [startPreview] */ fun stopPreview() }
4
Kotlin
17
42
abc4c9316d916b07bbf174fbf27a89e9d49f2fc0
1,602
StreamPack
Apache License 2.0
compiler/testData/diagnostics/tests/modifiers/suspendAnonymousFunction.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FIR_IDENTICAL // ISSUE: KT-57991 fun foo() { suspend fun() { } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
78
kotlin
Apache License 2.0
app/src/main/java/com/lytredrock/emocloudmusic/data/Artist.kt
lytMoon
666,257,860
false
null
package com.lytredrock.emocloudmusic.data data class Artist( val id: Int, val img1v1Url: String, val name: String, val picUrl: String, )
0
Kotlin
0
0
7a5e0c48a96ffa4057ee7bcea94a72a10c2da3c3
157
emoCloud
Apache License 2.0
eCommerceMobile/app/src/main/java/com/example/ecommercemobile/data/network/orders/ApiOrders.kt
Lloansi
716,627,802
false
{"Kotlin": 213931, "Python": 13552}
package com.example.ecommercemobile.data.network.orders import com.example.ecommercemobile.data.model.Cart import com.example.ecommercemobile.data.model.OrderClient import com.example.ecommercemobile.data.model.OrderState import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path interface ApiOrders { @GET("order/{userID}") suspend fun getOrders(@Header("Authorization") token: String, @Path("userID") userID: Int): List<OrderClient> @POST("order/{userID}") suspend fun addOrder(@Header("Authorization") token: String, @Path("userID") userID: Int, @Body orderClient: OrderClient): Boolean @PUT("order/{userID}/{orderID}") suspend fun putOrder(@Header("Authorization") token: String, @Path("userID") userID:Int, @Path("orderID") orderID: Int, @Body state: OrderState): Boolean @GET("cart/{userID}") suspend fun getCart(@Header("Authorization") token: String, @Path("userID") userID: Int): Cart? @POST("cart/{userID}") suspend fun createCart(@Header("Authorization") token: String, @Path("userID") userID: Int, @Body cart: Cart): Boolean @PUT("cart/{userID}") suspend fun updateCart(@Header("Authorization") token: String, @Path("userID") userID: Int, @Body productList: List<String>): Boolean @DELETE("cart/{userID}") suspend fun deleteCart(@Header("Authorization") token: String, @Path("userID") userID: Int): Boolean }
0
Kotlin
0
0
95d2a239c6f562d1e24886500a0d169705ab8127
1,513
eCommerce_app
MIT License
app/src/main/java/hu/tb/minichefy/presentation/screens/storage/storage_list/StorageListViewModel.kt
BTheofil
705,819,849
false
{"Kotlin": 98968}
package hu.tb.minichefy.presentation.screens.storage.storage_list import androidx.lifecycle.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow class StorageListViewModel: ViewModel() { data class UiState( val searchText: String = "", val filterList: List<String> = emptyList(), val foodList: List<String> = emptyList() ) private val _uiState = MutableStateFlow(UiState()) val uiState: StateFlow<UiState> = _uiState }
0
Kotlin
0
0
544bb3d8f068f6d71d3f76d76a8df46a44b5d325
508
MiniChefy
Apache License 2.0
src/main/kotlin/Day1.kt
clechasseur
264,758,910
false
null
object Day1 { private const val input = "29917128875332952564321392569634257121244516819997569284938677239676779378822158323549832814412597817651244117851771257438674567254146559419528411463781241159837576747416543451994579655175322397355255587935456185669334559882554936642122347526466965746273596321419312386992922582836979771421518356285534285825212798113159911272923448284681544657616654285632235958355867722479252256292311384799669645293812691169936746744856227797779513997329663235176153745581296191298956836998758194274865327383988992499115472925731787228592624911829221985925935268785757854569131538763133427434848767475989173579655375125972435359317237712667658828722623837448758528395981635746922144957695238318954845799697142491972626942976788997427135797297649149849739186827185775786254552866371729489943881272817466129271912247236569141713377483469323737384967871876982476485658337183881519295728697121462266226452265259877781881868585356333494916519693683238733823362353424927852348119426673294798416314637799636344448941782774113142925315947664869341363354235389597893211532745789957591898692253157726576488811769461354938575527273474399545366389515353657644736458182565245181653996192644851687269744491856672563885457872883368415631469696994757636288575816146927747179133188841148212825453859269643736199836818121559198563122442483528316837885842696283932779475955796132242682934853291737434482287486978566652161245555856779844813283979453489221189332412315117573259531352875384444264457373153263878999332444178577127433891164266387721116357278222665798584824336957648454426665495982221179382794158366894875864761266695773155813823291684611617853255857774422185987921219618596814446229556938354417164971795294741898631698578989231245376826359179266783767935932788845143542293569863998773276365886375624694329228686284863341465994571635379257258559894197638117333711626435669415976255967412994139131385751822134927578932521461677534945328228131973291962134523589491173343648964449149716696761218423314765168285342711137126239639867897341514131244859826663281981251614843274762372382114258543828157464392" fun part1() = sumOfMatching(1) fun part2() = sumOfMatching(input.length / 2) private fun sumOfMatching(jump: Int) = input.indices.mapNotNull { idx -> if (input.jumpFor(idx, jump) == input[idx]) input[idx].toString().toInt() else null }.sum() private fun String.jumpFor(idx: Int, jump: Int): Char = this[(idx + jump) % length] }
0
Kotlin
0
0
f3e8840700e4c71e59d34fb22850f152f4e6e739
2,485
adventofcode2017
MIT License
src/main/kotlin/com/github/shmvanhouten/adventofcode/day21letterscramble/Size8PasswordLetterDescrambler.kt
SHMvanHouten
109,886,692
false
{"Kotlin": 616528}
package com.github.shmvanhouten.adventofcode.day21letterscramble class Size8PasswordLetterDescrambler(private val instructionBuilder: DescrambleInstructionConverter = DescrambleInstructionConverter()) { fun descramblePassword(rawInstructions: String, password: String): String { val instructions = instructionBuilder.convertRawInstructionToInstructionList(rawInstructions).reversed() return instructions .fold(password.toCharArray()) { scrambledPassword, element -> element.executeInstruction(scrambledPassword) } .joinToString("") } }
0
Kotlin
0
0
a8abc74816edf7cd63aae81cb856feb776452786
595
adventOfCode2016
MIT License
app/src/main/kotlin/fr/ekito/myweatherapp/util/mvp/BasePresenter.kt
KotlinAndroidWorkshops
174,023,444
false
null
package fr.ekito.myweatherapp.util.mvp /** * Presenter */ interface BasePresenter<V> { fun subscribe(view: V) fun unSubscribe() var view : V? }
0
Kotlin
0
7
efdba4e28bee049888aa1110d22a76a6590b6138
162
2019-android-architecture-components-workshop
Creative Commons Attribution 4.0 International
app/src/main/kotlin/fr/ekito/myweatherapp/util/mvp/BasePresenter.kt
KotlinAndroidWorkshops
174,023,444
false
null
package fr.ekito.myweatherapp.util.mvp /** * Presenter */ interface BasePresenter<V> { fun subscribe(view: V) fun unSubscribe() var view : V? }
0
Kotlin
0
7
efdba4e28bee049888aa1110d22a76a6590b6138
162
2019-android-architecture-components-workshop
Creative Commons Attribution 4.0 International