path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/kotlin/com/sungbin/musicinformator/adapter/ArtistPagingAdapter.kt | jisungbin | 283,171,594 | false | null | package com.sungbin.musicinformator.adapter
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.databinding.DataBindingUtil
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.sungbin.musicinformator.R
import com.sungbin.musicinformator.databinding.LayoutArtistItemBinding
import com.sungbin.musicinformator.model.ArtistItem
import com.sungbin.musicinformator.paging.artist.ArtistDiffUtilCallback
/**
* Created by SungBin on 2020-08-01.
*/
class ArtistPagingAdapter : PagedListAdapter<ArtistItem, ArtistPagingAdapter.ViewHolder>(
ArtistDiffUtilCallback()
) {
class ViewHolder(private val artistItemBinding: LayoutArtistItemBinding) :
RecyclerView.ViewHolder(artistItemBinding.root) {
fun bindViewHolder(item: ArtistItem) {
artistItemBinding.tvArtistName.isSelected = true
artistItemBinding.item = item
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int) =
ViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(viewGroup.context),
R.layout.layout_artist_item, viewGroup, false
)
)
override fun onBindViewHolder(@NonNull viewholder: ViewHolder, position: Int) {
getItem(position)?.let {
viewholder.bindViewHolder(it)
}
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() { //아이템 간격
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
if (parent.getChildAdapterPosition(view) != parent.adapter!!.itemCount) {
outRect.set(0, 0, 0, 50)
}
}
})
}
override fun getItemId(position: Int) = position.toLong()
override fun getItemViewType(position: Int) = position
} | 0 | Kotlin | 0 | 5 | 7507d73fc79f9f59913a3a1947f5604ee78f5d8e | 2,167 | MusicInformator | MIT License |
app/src/main/java/org/wikipedia/feed/suggestededits/SuggestedEditsCard.kt | deagudelo | 459,177,548 | true | {"Java": 2771487, "JavaScript": 104383, "Kotlin": 96832, "Python": 20572, "HTML": 3116, "Shell": 1155, "Jinja": 1007} | package org.wikipedia.feed.suggestededits
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.restbase.page.RbPageSummary
import org.wikipedia.feed.model.CardType
import org.wikipedia.feed.model.WikiSiteCard
import org.wikipedia.util.DateUtil
class SuggestedEditsCard(wiki: WikiSite) : WikiSiteCard(wiki) {
var wiki: WikiSite? = null
var age: Int? = null
var isTranslation: Boolean = false
var sourceSummary: RbPageSummary? = null
var targetSummary: RbPageSummary? = null
override fun type(): CardType {
return CardType.SUGGESTED_EDITS
}
constructor(wiki: WikiSite, translation: Boolean, sourceSummary: RbPageSummary?, targetSummary: RbPageSummary?) : this(wiki) {
this.wiki = wiki
this.isTranslation = translation
this.sourceSummary = sourceSummary
this.targetSummary = targetSummary
}
override fun title(): String {
return WikipediaApp.getInstance().getString(R.string.suggested_edits_feed_card_title)
}
override fun subtitle(): String {
return DateUtil.getFeedCardDateString(0)
}
}
| 0 | Java | 0 | 0 | eadbf071a1c2a8f6d4435c23d20d9ccc40bdfe33 | 1,177 | wikipediaAndroidForReport | Apache License 2.0 |
src/main/kotlin/br/com/zup/erp_itau/ErpItauClient.kt | brenohof | 383,853,912 | true | {"Kotlin": 106221, "Smarty": 2032, "Dockerfile": 176} | package br.com.zup.erp_itau
import br.com.zup.TipoDaConta
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.PathVariable
import io.micronaut.http.annotation.QueryValue
import io.micronaut.http.client.annotation.Client
@Client("\${itau.contas.url}/api/v1/")
interface ErpItauClient {
@Get("/clientes/{clienteId}/contas")
fun consultarContaDoCliente(@PathVariable clienteId: String, @QueryValue tipo: String) : HttpResponse<DadosDaContaResponse>
@Get("/clientes/{clienteId}")
fun consultarClientePeloId(@PathVariable clienteId: String) : HttpResponse<DadosDoClienteResponse>
} | 0 | Kotlin | 0 | 0 | 45fac571322e6cd0de7867d076172bccdd800483 | 675 | pix-keymanager-grpc | Apache License 2.0 |
app/src/main/java/com/zeyad/rxredux/AnalyticsTracker.kt | Zeyad-37 | 95,054,413 | false | null | package com.zeyad.rxredux
object AnalyticsTracker {
fun sendEvent(event: Any) {
//do nothing
}
}
| 0 | Kotlin | 6 | 136 | fd054ca15e7827d56fb11e8f763273dbb893fb30 | 115 | RxRedux | Apache License 2.0 |
data/src/main/java/com/dvttest/hiweather/data/api/model/CurrentForecast.kt | zakayothuku | 461,908,095 | false | {"Kotlin": 199596, "Java": 4189, "Shell": 1116} | /*
* Copyright (C) 2022. dvt.co.za
*
* 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.dvttest.hiweather.data.api.model
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
@Keep
data class CurrentForecast(
@SerializedName("city") val city: City = City(),
@SerializedName("cnt") val cnt: Int = 0,
@SerializedName("cod") val cod: String = "",
@SerializedName("list") val days: List<Day> = listOf(),
@SerializedName("message") val message: Int = 0
) {
@Keep
data class City(
@SerializedName("coord") val coord: Coord = Coord(),
@SerializedName("country") val country: String = "",
@SerializedName("id") val id: Int = 0,
@SerializedName("name") val name: String = "",
@SerializedName("sunrise") val sunrise: Int = 0,
@SerializedName("sunset") val sunset: Int = 0,
@SerializedName("timezone") val timezone: Int = 0
) {
@Keep
data class Coord(
@SerializedName("lat") val lat: Double = 0.0,
@SerializedName("lon") val lon: Double = 0.0
)
}
@Keep
data class Day(
@SerializedName("clouds") val clouds: Clouds = Clouds(),
@SerializedName("dt") val dateTimestamp: Int = 0,
@SerializedName("dt_txt") val date: String = "",
@SerializedName("main") val info: Info = Info(),
@SerializedName("pop") val pop: Double = 0.0,
@SerializedName("rain") val rain: Rain = Rain(),
@SerializedName("sys") val sys: Sys = Sys(),
@SerializedName("visibility") val visibility: Int = 0,
@SerializedName("weather") val weather: List<Weather> = listOf(),
@SerializedName("wind") val wind: Wind = Wind()
) {
@Keep
data class Clouds(
@SerializedName("all") val all: Int = 0
)
@Keep
data class Info(
@SerializedName("feels_like") val feelsLike: Double = 0.0,
@SerializedName("grnd_level") val grndLevel: Int = 0,
@SerializedName("humidity") val humidity: Int = 0,
@SerializedName("pressure") val pressure: Int = 0,
@SerializedName("sea_level") val seaLevel: Int = 0,
@SerializedName("temp") val temp: Double = 0.0,
@SerializedName("temp_kf") val tempKf: Double = 0.0,
@SerializedName("temp_max") val tempMax: Double = 0.0,
@SerializedName("temp_min") val tempMin: Double = 0.0
)
@Keep
data class Rain(
@SerializedName("3h") val h: Double = 0.0
)
@Keep
data class Sys(
@SerializedName("pod") val pod: String = ""
)
@Keep
data class Weather(
@SerializedName("description") val description: String = "",
@SerializedName("icon") val icon: String = "",
@SerializedName("id") val id: Int = 0,
@SerializedName("main") val main: String = ""
)
@Keep
data class Wind(
@SerializedName("deg") val deg: Int = 0,
@SerializedName("gust") val gust: Double = 0.0,
@SerializedName("speed") val speed: Double = 0.0
)
}
}
| 0 | Kotlin | 0 | 2 | b52f8a2a1953548625f158c7b9523387313fb35e | 3,735 | dvt-hiweather | Apache License 2.0 |
kotlin-mui/src/main/generated/mui/material/SpeedDial.kt | Pandinosaurus | 126,706,152 | true | {"Kotlin": 1387147, "JavaScript": 528} | // Automatically generated - do not modify!
@file:JsModule("@mui/material/SpeedDial")
@file:JsNonModule
package mui.material
import kotlinext.js.ReadonlyArray
external interface SpeedDialProps : react.PropsWithChildren {
/**
* SpeedDialActions to display when the SpeedDial is `open`.
*/
override var children: ReadonlyArray<react.ReactNode>?
/**
* Override or extend the styles applied to the component.
*/
var classes: SpeedDialClasses
/**
* The aria-label of the button element.
* Also used to provide the `id` for the `SpeedDial` element and its children.
*/
var ariaLabel: String
/**
* The direction the actions open relative to the floating action button.
* @default 'up'
*/
var direction: Union /* 'up' | 'down' | 'left' | 'right' */
/**
* If `true`, the SpeedDial is hidden.
* @default false
*/
var hidden: Boolean
/**
* Props applied to the [`Fab`](/api/fab/) element.
* @default {}
*/
var FabProps: FabProps
/**
* The icon to display in the SpeedDial Fab. The `SpeedDialIcon` component
* provides a default Icon with animation.
*/
var icon: react.ReactNode
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"toggle"`, `"blur"`, `"mouseLeave"`, `"escapeKeyDown"`.
*/
var onClose: (event: react.dom.SyntheticEvent<*, *>, reason: CloseReason) -> Unit
/**
* Callback fired when the component requests to be open.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"toggle"`, `"focus"`, `"mouseEnter"`.
*/
var onOpen: (event: react.dom.SyntheticEvent<*, *>, reason: OpenReason) -> Unit
/**
* If `true`, the component is shown.
*/
var open: Boolean
/**
* The icon to display in the SpeedDial Fab when the SpeedDial is open.
*/
var openIcon: react.ReactNode
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
var sx: SxProps<Theme>
/**
* The component used for the transition.
* [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
* @default Zoom
*/
var TransitionComponent: react.ComponentType<TransitionProps>
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
* @default {
* enter: duration.enteringScreen,
* exit: duration.leavingScreen,
* }
*/
var transitionDuration: dynamic /* TransitionProps['timeout'] */
/**
* Props applied to the transition element.
* By default, the element is based on this [`Transition`](https://reactcommunity.org/react-transition-group/transition) component.
*/
var TransitionProps: TransitionProps
}
/**
*
* Demos:
*
* - [Speed Dial](https://mui.com/components/speed-dial/)
*
* API:
*
* - [SpeedDial API](https://mui.com/api/speed-dial/)
*/
@JsName("default")
external val SpeedDial: react.FC<SpeedDialProps>
| 1 | Kotlin | 0 | 0 | 9baf2b5b00ccf944e847cbea3ab452faf746013c | 3,308 | kotlin-wrappers | Apache License 2.0 |
generators/app/templates/data/src/main/java/com/kristal/generator/data/repository/ExampleDatabaseRepositoryImpl.kt | Cla1ty | 108,220,263 | false | null | package <%= appPackage %>.data.repository
import <%= appPackage %>.data.example.database.db.ExampleTableExternal
import <%= appPackage %>.data.example.file.file.mapper.toExample
import <%= appPackage %>.domain.example.Example
import <%= appPackage %>.domain.example.database.repository.ExampleDatabaseRepository
import io.reactivex.Observable
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by Dwi_Ari on 10/23/17.
*/
@Singleton
class ExampleDatabaseRepositoryImpl
@Inject internal constructor(
private val table: ExampleTableExternal
) : ExampleDatabaseRepository {
override fun examples(search: String): Observable<List<Example>> =
table.search(search).map { it.map { it.toExample() } }
}
| 0 | Kotlin | 1 | 0 | 4133b44eb99c594155111fdb3be0b72730c0d6a2 | 743 | Generator-Kristal | The Unlicense |
app/src/main/java/com/danielpriddle/drpnews/workers/FileClearWorker.kt | DPriddle96 | 529,001,714 | false | {"Kotlin": 83827} | package com.danielpriddle.drpnews.workers
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.bumptech.glide.Glide
import com.danielpriddle.drpnews.utils.Logger
class FileClearWorker(private val context: Context, workerParameters: WorkerParameters) :
Worker(context, workerParameters), Logger {
override fun doWork(): Result {
val root = Glide.getPhotoCacheDir(context)
logDebug("FileClearWorker - Glide Root: $root")
return try {
root?.listFiles()?.forEach { child ->
if (child.isDirectory) {
child.deleteRecursively()
} else {
child.delete()
}
}
Result.success()
} catch (error: Throwable) {
logError("FileClearWorker - Error: ${error.message}")
Result.failure()
}
}
} | 0 | Kotlin | 0 | 0 | 4438f071a550c6acd62ef2af7197331031b2eb83 | 929 | DRPNews | MIT License |
app/src/androidTest/java/com/flexcode/wedatecompose/TestFirebaseModule.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.wedatecompose
import com.flexcode.wedatecompose.di.FirebaseModule
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.ktx.storage
import dagger.Module
import dagger.Provides
import dagger.hilt.components.SingletonComponent
import dagger.hilt.testing.TestInstallIn
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [com.flexcode.wedatecompose.di.FirebaseModule::class]
)
object TestFirebaseModule {
private const val HOST = "10.0.2.2"
private const val AUTH_PORT = 9099
private const val FIRESTORE_PORT = 8080
private const val FIREBASE_STORAGE = 7782
@Provides
fun auth(): FirebaseAuth = Firebase.auth.also { it.useEmulator(HOST, AUTH_PORT) }
@Provides
fun firestore(): FirebaseFirestore = Firebase.firestore.also {
it.useEmulator(
HOST,
FIRESTORE_PORT
)
}
@Provides
fun storage(): FirebaseStorage = Firebase.storage.also {
it.useEmulator(HOST, FIREBASE_STORAGE)
}
}
| 13 | Kotlin | 1 | 10 | 905b628c736584ef594fe06883b81799ffcfb6f0 | 1,889 | Mingle | Apache License 2.0 |
compiler/testData/codegen/box/invokedynamic/sam/specializedGenerics/inheritedWithInt.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM
// JVM_TARGET: 1.8
// SAM_CONVERSIONS: INDY
// CHECK_BYTECODE_TEXT
// JVM_IR_TEMPLATES
// 1 java/lang/invoke/LambdaMetafactory
fun interface GenericToAny<T> {
fun invoke(x: T): Any
}
fun interface GenericIntToAny : GenericToAny<Int>
fun with4(fn: GenericIntToAny) = fn.invoke(4).toString()
fun box(): String =
with4 {
if (it != 4) throw Exception()
"OK"
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 411 | kotlin | Apache License 2.0 |
android/PetAdoptSampleApp/app/src/main/java/laurenyew/petadoptsampleapp/ui/features/search/PetSearchViewModel.kt | laurenyew | 239,209,623 | false | {"Kotlin": 152078, "Swift": 55338, "Objective-C": 581, "Ruby": 424} | package laurenyew.petadoptsampleapp.ui.features.search
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import laurenyew.petadoptsampleapp.database.animal.Animal
import laurenyew.petadoptsampleapp.repository.PetFavoriteRepository
import laurenyew.petadoptsampleapp.repository.PetSearchRepository
import laurenyew.petadoptsampleapp.repository.responses.SearchPetsRepoResponse
import laurenyew.petadoptsampleapp.ui.features.petList.PetListViewModel
import java.util.concurrent.CancellationException
import javax.inject.Inject
@HiltViewModel
class PetSearchViewModel @Inject constructor(
private val searchRepository: PetSearchRepository,
private val favoriteRepository: PetFavoriteRepository,
) : PetListViewModel(favoriteRepository) {
private val _location = MutableStateFlow("")
val location: StateFlow<String> = _location
private var currentSearchLocation = ""
private var currentSearchJob: Job? = null
init {
// Load up list with the results of the last search
viewModelScope.launch {
searchRepository.getLastSearchTerm()?.let { searchTerm ->
_location.value = searchTerm.zipcode
currentSearchLocation = _location.value
val savedAnimalList = searchRepository.getSearchedAnimalList(searchTerm.searchId)
val updatedSavedAnimalListWithFavorites = parseWithFavorites(savedAnimalList)
if (updatedSavedAnimalListWithFavorites != null) {
_animals.value = updatedSavedAnimalListWithFavorites // use saved list
} else {
searchAnimals() // restart search with last search term
}
}
}
}
fun setLocation(location: String) {
_location.value = location
}
fun searchAnimals(forceRefresh: Boolean = false) {
val newLocation = location.value
// Check location
if (newLocation.isBlank()) {
_errorState.value = "No location specified. Please specify a 5 digit zipcode."
return
} else if (newLocation.length != 5) {
_errorState.value = "Invalid zipcode length. Please specify a 5 digit zipcode."
return
}
val isChangedLocation = newLocation != currentSearchLocation
if (isChangedLocation || forceRefresh) {
if (currentSearchJob?.isActive == true) {
currentSearchJob?.cancel(CancellationException("New search started. Cancelling old search."))
}
_isLoading.value = true
if (isChangedLocation) {
_animals.value = emptyList()
}
currentSearchLocation = newLocation
currentSearchJob = viewModelScope.launch {
when (val searchResponse = searchRepository.getNearbyPets(newLocation)) {
is SearchPetsRepoResponse.Success -> {
val searchedAnimals = parseWithFavorites(searchResponse.animals)
_animals.value = searchedAnimals ?: emptyList()
_isError.value = false
searchRepository.saveSearchTerm(newLocation)
}
else -> {
_animals.value = emptyList()
_isError.value = true
}
}
_isLoading.value = false
}
}
}
private suspend fun parseWithFavorites(animals: List<Animal>?): List<Animal>? {
val favorites =
favoriteRepository.favoriteIds()
return animals?.map {
if (favorites.contains(it.animalId)) {
it.copy(true)
} else {
it
}
}
}
} | 0 | Kotlin | 0 | 6 | d558514cabcc1a54a3436726f4493eb33d5952e1 | 3,988 | PetAdoptSampleApp | MIT License |
idea/src/org/jetbrains/kotlin/idea/inspections/KotlinInternalInJavaInspection.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.lexer.KtTokens.INTERNAL_KEYWORD
import org.jetbrains.kotlin.psi.KtModifierListOwner
class KotlinInternalInJavaInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : JavaElementVisitor() {
override fun visitReferenceExpression(expression: PsiReferenceExpression?) {
expression?.checkAndReport(holder)
}
override fun visitReferenceElement(reference: PsiJavaCodeReferenceElement?) {
reference?.checkAndReport(holder)
}
}
}
private fun PsiElement.checkAndReport(holder: ProblemsHolder) {
val lightElement = (this as? PsiReference)?.resolve() as? KtLightElement<*, *> ?: return
val modifierListOwner = lightElement.kotlinOrigin as? KtModifierListOwner ?: return
if (inSameModule(modifierListOwner)) {
return
}
if (modifierListOwner.hasModifier(INTERNAL_KEYWORD)) {
holder.registerProblem(this, KotlinBundle.message("usage.of.kotlin.internal.declaration.from.different.module"))
}
}
private fun PsiElement.inSameModule(element: PsiElement) = module?.equals(element.module) ?: true
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 1,827 | kotlin | Apache License 2.0 |
features/newtoken/newtoken-impl/build.gradle.kts | getspherelabs | 687,455,894 | false | {"Kotlin": 917584, "Ruby": 6814, "Swift": 1128, "Shell": 1048} | @file:Suppress("DSL_SCOPE_VIOLATION")
plugins {
alias(libs.plugins.anypass.presentation)
alias(libs.plugins.anypass.compose)
}
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
api(projects.core.designsystem)
api(projects.resource.images)
implementation(projects.core.common)
implementation(projects.features.newtoken.newtokenApi)
implementation(libs.datetime)
implementation(libs.voyager)
implementation(compose.ui)
implementation(compose.material)
implementation(compose.material3)
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.materialIconsExtended)
@OptIn(org.jetbrains.compose.ExperimentalComposeLibrary::class)
implementation(compose.components.resources)
implementation(projects.resource.fonts)
implementation(projects.resource.icons)
implementation(projects.core.system.foundation)
}
}
}
}
android {
namespace = "io.spherelabs.newtokenimpl"
compileSdk = 33
defaultConfig { minSdk = 24 }
}
| 18 | Kotlin | 24 | 188 | 902a0505c5eaf0f3848a5e06afaec98c1ed35584 | 1,129 | anypass-kmp | Apache License 2.0 |
app/src/androidTest/kotlin/com/github/feed/sample/flow/details/DetailsScreenTest.kt | markspit93 | 105,769,386 | false | null | package com.github.feed.sample.flow.details
import android.support.test.filters.SmallTest
import android.support.test.runner.AndroidJUnit4
import com.github.feed.sample.BaseInstrumentationTest
import com.github.feed.sample.R
import com.github.feed.sample.data.repository.datasource.event.remote.RemoteEventDataSourceBehaviour
import com.github.feed.sample.ui.details.DetailsActivity
import com.github.feed.sample.ui.main.MainActivity
import com.github.feed.sample.util.clickView
import com.github.feed.sample.util.nextOpenActivityIs
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class DetailsScreenTest : BaseInstrumentationTest<MainActivity>(MainActivity::class.java) {
companion object {
@JvmStatic
@BeforeClass
fun setupClass() {
RemoteEventDataSourceBehaviour.eventsConfig = RemoteEventDataSourceBehaviour.EventConfig.SUCCESSFUL
}
}
@Test
fun showEventDetails() {
// Arrange
// Act
clickView(R.id.cardEvent)
// Assert
nextOpenActivityIs<DetailsActivity>()
}
} | 0 | Kotlin | 0 | 0 | f37bbf8656e2e3964212fd12d4ce3864df553590 | 1,152 | Github-Feed-Sample | Apache License 2.0 |
persistence/src/commonMain/kotlin/mqtt/persistence/PlatformDatabase.kt | thebehera | 171,056,445 | false | null | package mqtt.persistence
interface PlatformDatabase {
suspend fun open(tables: Map<String, Row>): Map<String, PlatformTable>
suspend fun dropTable(table: PlatformTable)
}
open class ContextProvider
expect fun getPlatformDatabase(name: String, contextProvider: ContextProvider = ContextProvider()): PlatformDatabase | 2 | Kotlin | 1 | 32 | 2f2d176ca1d042f928fba3a9c49f4bc5ff39495f | 325 | mqtt | Apache License 2.0 |
app/src/main/java/com/tmdb/movie/ui/home/HomeScreen.kt | sqsong66 | 703,818,964 | false | {"Kotlin": 899108} | package com.tmdb.movie.ui.home
import android.util.Log
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SearchBar
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.tmdb.movie.R
import com.tmdb.movie.component.BlurHeaderBgComponent
import com.tmdb.movie.data.ImageSize
import com.tmdb.movie.data.ImageType
import com.tmdb.movie.data.MediaType
import com.tmdb.movie.data.MediaItem
import com.tmdb.movie.data.People
import com.tmdb.movie.data.SearchHistory
import com.tmdb.movie.data.SearchItem
import com.tmdb.movie.ext.pxToDp
import com.tmdb.movie.ui.home.component.HistorySearchComponent
import com.tmdb.movie.ui.home.component.HomeMoviePagerComponent
import com.tmdb.movie.ui.home.component.PopularPeopleComponent
import com.tmdb.movie.ui.home.component.SearchResultComponent
import com.tmdb.movie.ui.home.component.TrendingComponent
import com.tmdb.movie.ui.home.vm.HomeViewModel
import com.tmdb.movie.ui.home.vm.MovieLoadState
import com.tmdb.movie.ui.theme.TMDBMovieTheme
import kotlin.math.roundToInt
@Composable
fun HomeRoute(
onShowBottomBar: (Boolean) -> Unit,
navigateToMovieDetail: (Int, @MediaType Int, Int) -> Unit,
onNavigateToPeopleDetail: (Int, Int) -> Unit,
viewModel: HomeViewModel = hiltViewModel(),
) {
val config by viewModel.configStream.collectAsStateWithLifecycle()
val searchResult = viewModel.searchResult.collectAsLazyPagingItems()
val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()
val tvPopularState by viewModel.tvPopularState.collectAsStateWithLifecycle()
val tvTrendingState by viewModel.tvTrendingState.collectAsStateWithLifecycle()
val tvAirTodayState by viewModel.tvAirTodayState.collectAsStateWithLifecycle()
val recentSearchList by viewModel.recentSearchList.collectAsStateWithLifecycle()
val isSearchBarActive by viewModel.isSearchBarActive.collectAsStateWithLifecycle()
val moviePopularState by viewModel.moviePopularState.collectAsStateWithLifecycle()
val popularPeopleState by viewModel.popularPeopleState.collectAsStateWithLifecycle()
val moviesTrendingState by viewModel.movieTrendingState.collectAsStateWithLifecycle()
val movieNowPlayingState by viewModel.movieNowPlayingState.collectAsStateWithLifecycle()
HomeScreen(
moviesTrendingState = moviesTrendingState,
tvTrendingState = tvTrendingState,
popularPeopleState = popularPeopleState,
movieNowPlayingState = movieNowPlayingState,
tvAirTodayState = tvAirTodayState,
moviePopularState = moviePopularState,
tvPopularState = tvPopularState,
onSearchQueryChanged = viewModel::onSearchQueryChanged,
onSearchTriggered = viewModel::onSearchTriggered,
onRefreshData = viewModel::toggleRefresh,
onActiveStateChanged = {
onShowBottomBar(!it)
viewModel.changeSearchBarActiveState(it)
},
isRefreshing = moviesTrendingState is MovieLoadState.Loading,
onBuildImage = { url, type, size ->
config.buildImageUrl(url, type, size)
},
navigateToMovieDetail = { id, type ->
navigateToMovieDetail(id, type, 0)
},
onNavigateToPeopleDetail = { id ->
onNavigateToPeopleDetail(id, 0)
},
searchQuery = searchQuery,
isSearchBarActive = isSearchBarActive,
recentSearchList = recentSearchList,
searchResult = searchResult,
navigateToDetail = { id, type ->
when (type) {
MediaType.MOVIE, MediaType.TV -> navigateToMovieDetail(id, type, 1)
MediaType.PERSON -> onNavigateToPeopleDetail(id, 1)
}
}
)
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HomeScreen(
moviesTrendingState: MovieLoadState<MediaItem> = MovieLoadState.Loading(),
tvTrendingState: MovieLoadState<MediaItem> = MovieLoadState.Loading(),
popularPeopleState: MovieLoadState<People> = MovieLoadState.Loading(),
movieNowPlayingState: MovieLoadState<MediaItem> = MovieLoadState.Loading(),
tvAirTodayState: MovieLoadState<MediaItem> = MovieLoadState.Loading(),
moviePopularState: MovieLoadState<MediaItem> = MovieLoadState.Loading(),
tvPopularState: MovieLoadState<MediaItem> = MovieLoadState.Loading(),
onSearchQueryChanged: (String) -> Unit = {},
onSearchTriggered: (String) -> Unit = {},
onActiveStateChanged: (Boolean) -> Unit = {},
onRefreshData: () -> Unit = {},
isRefreshing: Boolean = false,
onBuildImage: (String?, @ImageType Int, @ImageSize Int) -> String? = { url, _, _ -> url },
navigateToMovieDetail: (Int, @MediaType Int) -> Unit = { _, _ -> },
onNavigateToPeopleDetail: (Int) -> Unit = {},
searchQuery: String = "",
isSearchBarActive: Boolean,
recentSearchList: List<SearchHistory> = emptyList(),
searchResult: LazyPagingItems<SearchItem>? = null,
navigateToDetail: (Int, @MediaType Int) -> Unit = { _, _ -> },
) {
var imageUrl by remember { mutableStateOf("") }
var searchBarActiveState by remember { mutableStateOf(false) }
// 顶部搜索区域高度
var toolbarHeight by remember { mutableIntStateOf(283) }
// 顶部搜索区域偏移量
val toolbarOffsetHeightPx = remember { mutableFloatStateOf(0f) }
val refreshState = rememberPullRefreshState(isRefreshing, onRefresh = onRefreshData)
LaunchedEffect(key1 = isSearchBarActive, block = {
searchBarActiveState = isSearchBarActive
})
Log.w("sqsong", "HomeScreen: ReCompose")
val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (searchBarActiveState) return Offset.Zero
val newOffset = toolbarOffsetHeightPx.floatValue + available.y
val offset = newOffset.coerceIn(-toolbarHeight.toFloat(), 0f)
toolbarOffsetHeightPx.floatValue = if (refreshState.progress == 0f) offset else 0f
return Offset.Zero
}
}
}
Box(
modifier = Modifier
.fillMaxSize()
.pullRefresh(state = refreshState)
.nestedScroll(nestedScrollConnection),
) {
if (imageUrl.isNotEmpty()) BlurHeaderBgComponent(imageUrl = imageUrl, useBlur = true)
Column(
modifier = Modifier
.fillMaxSize()
.navigationBarsPadding()
.verticalScroll(rememberScrollState())
) {
Spacer(modifier = Modifier.height(toolbarHeight.pxToDp()))
HomeMoviePagerComponent(
modifier = Modifier.padding(top = 16.dp),
moviePopularState = moviePopularState,
onBuildImage = onBuildImage,
navigateToMovieDetail = navigateToMovieDetail,
onPageChanged = { imagePath ->
imageUrl = imagePath
}
)
PopularPeopleComponent(
title = stringResource(R.string.key_popular_people),
trendingState = popularPeopleState,
onBuildImage = { url, type ->
onBuildImage(url, type, ImageSize.MEDIUM)
},
onNavigateToPeopleDetail = onNavigateToPeopleDetail
)
TrendingComponent(
title = stringResource(R.string.key_popular_tv),
mediaType = MediaType.TV,
modifier = Modifier.padding(top = 8.dp, bottom = 16.dp),
trendingState = tvPopularState,
onBuildImage = { url, type ->
onBuildImage(url, type, ImageSize.MEDIUM)
},
navigateToMovieDetail = navigateToMovieDetail
)
TrendingComponent(
title = stringResource(R.string.key_movies_trending),
mediaType = MediaType.MOVIE,
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp),
trendingState = moviesTrendingState,
onBuildImage = { url, type ->
onBuildImage(url, type, ImageSize.MEDIUM)
},
navigateToMovieDetail = navigateToMovieDetail
)
TrendingComponent(
title = stringResource(R.string.key_tv_trending),
mediaType = MediaType.TV,
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp),
trendingState = tvTrendingState,
onBuildImage = { url, type ->
onBuildImage(url, type, ImageSize.MEDIUM)
},
navigateToMovieDetail = navigateToMovieDetail
)
TrendingComponent(
title = stringResource(R.string.key_movies_now_playing),
mediaType = MediaType.MOVIE,
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp),
trendingState = movieNowPlayingState,
onBuildImage = { url, type ->
onBuildImage(url, type, ImageSize.MEDIUM)
},
navigateToMovieDetail = navigateToMovieDetail
)
TrendingComponent(
title = stringResource(R.string.key_tv_air_today),
mediaType = MediaType.TV,
modifier = Modifier.padding(top = 8.dp, bottom = 16.dp),
trendingState = tvAirTodayState,
onBuildImage = { url, type ->
onBuildImage(url, type, ImageSize.MEDIUM)
},
navigateToMovieDetail = navigateToMovieDetail
)
Spacer(modifier = Modifier.height(80.dp))
}
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
TopSearchBar(
modifier = Modifier
.background(Color.Transparent)
.onGloballyPositioned {
toolbarHeight = it.size.height
}
.offset { IntOffset(x = 0, y = toolbarOffsetHeightPx.floatValue.roundToInt()) },
onSearchQueryChanged = onSearchQueryChanged,
onSearchTriggered = onSearchTriggered,
onActiveStateChanged = onActiveStateChanged,
searchQuery = searchQuery,
isSearchBarActive = isSearchBarActive,
recentSearchList = recentSearchList,
searchResult = searchResult,
onBuildImage = { url, type ->
onBuildImage(url, type, ImageSize.MEDIUM)
},
navigateToDetail = navigateToDetail
)
PullRefreshIndicator(
isRefreshing,
refreshState,
contentColor = MaterialTheme.colorScheme.primary,
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopSearchBar(
modifier: Modifier,
onSearchQueryChanged: (String) -> Unit = {},
onSearchTriggered: (String) -> Unit = {},
onActiveStateChanged: (Boolean) -> Unit = {},
searchQuery: String = "",
isSearchBarActive: Boolean = false,
recentSearchList: List<SearchHistory> = emptyList(),
searchResult: LazyPagingItems<SearchItem>? = null,
onBuildImage: (String?, @ImageType Int) -> String? = { url, _ -> url },
navigateToDetail: (Int, @MediaType Int) -> Unit = { _, _ -> },
) {
val focusRequester = remember { FocusRequester() }
val keyboardController = LocalSoftwareKeyboardController.current
val isSearchEmpty by remember(searchQuery) { derivedStateOf { searchQuery.isEmpty() } }
val avatarAlpha = animateFloatAsState(
targetValue = if (isSearchBarActive) 0f else 1f,
label = "",
animationSpec = tween(300, easing = LinearEasing)
)
val horizontalPadding: Dp by animateDpAsState(
targetValue = if (isSearchBarActive) 0.dp else 16.dp,
label = "",
animationSpec = tween(300, easing = LinearEasing)
)
val bottomPadding: Dp by animateDpAsState(
targetValue = if (isSearchBarActive) 0.dp else 8.dp,
label = "",
animationSpec = tween(300, easing = LinearEasing)
)
SearchBar(
modifier = modifier
.padding(
start = horizontalPadding,
end = horizontalPadding,
bottom = bottomPadding
)
.focusRequester(focusRequester),
query = searchQuery,
tonalElevation = 8.dp,
onQueryChange = onSearchQueryChanged,
onSearch = {
onSearchTriggered(it)
keyboardController?.hide()
},
active = isSearchBarActive,
onActiveChange = {
Log.w("sqsong", "TopSearchBar onActiveChange: $it")
onActiveStateChanged(it)
},
leadingIcon = {
AnimatedContent(targetState = isSearchBarActive,
label = "",
transitionSpec = {
if (targetState) {
fadeIn().togetherWith(fadeOut())
} else {
fadeIn() togetherWith fadeOut()
}
}) {
IconButton(onClick = {
if (isSearchBarActive) {
focusRequester.requestFocus()
}
onActiveStateChanged(!isSearchBarActive)
}) {
Icon(
modifier = Modifier,
painter = painterResource(id = if (it) R.drawable.baseline_arrow_back_24 else R.drawable.baseline_search_24),
contentDescription = "Search"
)
}
}
},
trailingIcon = {
if (isSearchBarActive) {
if (!isSearchEmpty) {
IconButton(onClick = {
onSearchQueryChanged("")
}) {
Icon(
modifier = Modifier,
painter = painterResource(id = R.drawable.baseline_close_24),
contentDescription = "Close"
)
}
}
} else {
Image(
modifier = Modifier.clip(CircleShape),
painter = painterResource(id = R.drawable.avatar),
contentDescription = "Avatar",
alpha = avatarAlpha.value
)
}
},
placeholder = {
Text(
modifier = Modifier.padding(start = 8.dp),
text = stringResource(id = R.string.key_search_movie),
style = MaterialTheme.typography.bodyLarge.copy(
color = MaterialTheme.colorScheme.onSurface.copy(
0.6f
)
),
)
},
) {
Column(
modifier = Modifier
.fillMaxSize()
.navigationBarsPadding()
.background(color = MaterialTheme.colorScheme.surface),
horizontalAlignment = Alignment.CenterHorizontally
) {
if (isSearchEmpty) {
if (recentSearchList.isNotEmpty()) HistorySearchComponent(
modifier = Modifier.fillMaxWidth(),
searchList = recentSearchList.map { it.query },
onSearch = {
onSearchQueryChanged(it)
onSearchTriggered(it)
}
)
} else {
SearchResultComponent(
searchQuery = searchQuery,
searchResult = searchResult,
onBuildImage = onBuildImage,
navigateToDetail = navigateToDetail
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun HomeScreenPreview() {
TMDBMovieTheme {
HomeScreen(
moviesTrendingState = MovieLoadState.Loading(),
tvTrendingState = MovieLoadState.Loading(),
popularPeopleState = MovieLoadState.Loading(),
movieNowPlayingState = MovieLoadState.Loading(),
tvAirTodayState = MovieLoadState.Loading(),
isSearchBarActive = false,
)
}
} | 0 | Kotlin | 7 | 15 | 7dfc6aa197d1646773967f06eeef5a998bcda5a3 | 19,569 | TMDB-Movie | Apache License 2.0 |
settings.gradle.kts | eManPrague | 189,150,450 | false | {"Kotlin": 130007, "Java": 794} | rootProject.buildFileName = "build.gradle.kts"
include(
":app",
// ":presentation",
":domain",
":data",
":infrastructure"
)
| 1 | Kotlin | 3 | 6 | 2f3464f4d466e4d6ea6a29fb8bdfbf6f73b5c544 | 165 | kaal-sample | MIT License |
src/main/kotlin/se/svt/oss/mediaanalyzer/file/SubtitleFile.kt | svt | 285,523,429 | false | {"Kotlin": 47704} | // SPDX-FileCopyrightText: 2020 Sveriges Television AB
//
// SPDX-License-Identifier: Apache-2.0
package se.svt.oss.mediaanalyzer.file
import com.fasterxml.jackson.annotation.JsonTypeName
@JsonTypeName("SubtitleFile")
data class SubtitleFile(
override val file: String,
override val fileSize: Long,
override val format: String
) : MediaFile {
override val type: String
get() = "SubtitleFile"
}
| 1 | Kotlin | 2 | 16 | db2df5d7bc692f74a2d3b61320f2cd785723bfa9 | 421 | media-analyzer | Apache License 2.0 |
src/main/kotlin/no/skatteetaten/aurora/gobo/AuroraIntegration.kt | Skatteetaten | 135,263,220 | false | {"Kotlin": 729888, "HTML": 1433, "Shell": 426} | package no.skatteetaten.aurora.gobo
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component
@ConfigurationProperties("integrations")
@Component
class AuroraIntegration(val docker: Map<String, DockerRegistry>) {
enum class AuthType {
None, Basic, Bearer
}
class DockerRegistry {
var url: String? = null
var guiUrlPattern: String? = null
var auth = AuthType.None
var isHttps = true
var isReadOnly = true
var isEnabled = true
}
}
| 0 | Kotlin | 0 | 3 | 9a28e1d711756479696672f139568fdeadb74ac1 | 570 | gobo | Apache License 2.0 |
app/src/main/java/com/dkmkknub/villtech/utils/PermissionablePage.kt | fahmigutawan | 510,392,118 | false | {"Kotlin": 197257} | package com.dkmkknub.villtech.utils
import androidx.compose.runtime.Composable
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionState
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun PermissionablePage(
permissionState: PermissionState,
contentPermissionDeniedFirstTime: @Composable () -> Unit,
contentPermissionDeniedForever: @Composable () -> Unit,
contentPermissionNotRequested: @Composable () -> Unit,
successContent: @Composable () -> Unit
) {
} | 0 | Kotlin | 0 | 0 | 899205eef1d12aa40a04a0603d4b4af0540e2673 | 554 | Jetpack-VillTech | MIT License |
plugins/base/src/test/kotlin/expect/ExpectTest.kt | Mu-L | 406,989,990 | true | {"Kotlin": 3712559, "CSS": 63401, "JavaScript": 33594, "TypeScript": 13611, "HTML": 6976, "FreeMarker": 4120, "Java": 3923, "SCSS": 2794, "Shell": 970} | /*
* Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package expect
import org.junit.jupiter.api.DynamicTest.dynamicTest
import org.junit.jupiter.api.TestFactory
import kotlin.test.Ignore
class ExpectTest : AbstractExpectTest() {
private val ignores: List<String> = listOf(
"images",
"scripts",
"images",
"styles",
"*.js",
"*.css",
"*.svg",
"*.map"
)
@Ignore
@TestFactory
fun expectTest() = testDir?.dirsWithFormats(formats).orEmpty().map { (p, f) ->
dynamicTest("${p.fileName}-$f") { testOutputWithExcludes(p, f, ignores) }
}
}
| 1 | Kotlin | 0 | 0 | a1c3b89871a3a4f90d6441db356685d48a84ab63 | 690 | dokka | Apache License 2.0 |
PRACTICE_JETPACK/app/src/main/java/nlab/practice/jetpack/ui/slide/SlidingBindingAdapter.kt | skaengus2012 | 153,380,376 | false | null | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nlab.practice.jetpack.ui.slide
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import jp.wasabeef.glide.transformations.BlurTransformation
import nlab.practice.jetpack.util.GlideApp
/**
* @author Doohyun
*/
private const val PREFIX = "sliding_"
object SlidingBindingAdapter {
@JvmStatic
@BindingAdapter("${PREFIX}imageUrl")
fun setImage(view: ImageView, imgUrl: String?) {
if (imgUrl == null) {
view.setImageDrawable(null)
} else {
GlideApp.with(view.context)
.asBitmap()
.load(imgUrl)
.transform(BlurTransformation(3, 25))
.into(view)
}
}
} | 2 | Kotlin | 0 | 0 | 6c742e0888f5e01e0d7f0f1dd3d57707c62716b0 | 1,335 | Practice-Jetpack | Apache License 2.0 |
Chapter11/Exercise11.01-11.02/app/src/main/java/com/android/testable/repository/db/PostDatabase.kt | PacktPublishing | 310,206,627 | false | {"Kotlin": 583795} | package com.android.testable.repository.db
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [PostEntity::class],
version = 1
)
abstract class PostDatabase : RoomDatabase() {
abstract fun postDao(): PostDao
} | 2 | Kotlin | 67 | 97 | b37be5b81ed1f5fb107733b509bae80e46f92f4a | 259 | How-to-Build-Android-Apps-with-Kotlin | MIT License |
compiler/testData/diagnostics/tests/objects/kt5527.fir.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // !DIAGNOSTICS: -UNUSED_VARIABLE
object Boo {}
class A {
object Boo {}
}
fun foo() {
val i1: Int = <!INITIALIZER_TYPE_MISMATCH!>Boo<!>
val i2: Int = <!INITIALIZER_TYPE_MISMATCH!>A.Boo<!>
useInt(<!ARGUMENT_TYPE_MISMATCH!>Boo<!>)
useInt(<!ARGUMENT_TYPE_MISMATCH!>A.Boo<!>)
}
fun bar() {
val i1: Int = <!INITIALIZER_TYPE_MISMATCH!>Unit<!>
useInt(<!ARGUMENT_TYPE_MISMATCH!>Unit<!>)
}
fun useInt(i: Int) = i
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 435 | kotlin | Apache License 2.0 |
compiler/testData/compileKotlinAgainstCustomBinaries/innerClassPackageConflict/source.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | import test.Foo.Bar
import test.Baz
val f: Bar? = null
val g: Baz? = Baz().apply { bar() }
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 92 | kotlin | Apache License 2.0 |
apps/AndroidDemo/app/src/androidTest/java/com/example/androiddemo/DrawerNavigationTests.kt | dtopuzov | 315,068,528 | false | {"Java": 258136, "Swift": 32609, "Shell": 16984, "Kotlin": 15442, "Python": 7284, "HTML": 3240} | package com.example.androiddemo
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.hamcrest.core.IsInstanceOf
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class DrawerNavigationTests {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun drawerNavigationTests() {
val appCompatImageButton = onView(
allOf(
withContentDescription("Open navigation drawer"),
childAtPosition(
allOf(
withId(R.id.toolbar),
childAtPosition(
withClassName(`is`("com.google.android.material.appbar.AppBarLayout")),
0
)
),
1
),
isDisplayed()
)
)
appCompatImageButton.perform(click())
val navigationMenuItemView = onView(
allOf(
childAtPosition(
allOf(
withId(R.id.design_navigation_view),
childAtPosition(
withId(R.id.nav_view),
0
)
),
3
),
isDisplayed()
)
)
navigationMenuItemView.perform(click())
val textView = onView(
allOf(
withText("Slideshow"),
withParent(
allOf(
withId(R.id.toolbar),
withParent(IsInstanceOf.instanceOf(android.widget.LinearLayout::class.java))
)
),
isDisplayed()
)
)
textView.check(matches(withText("Slideshow")))
val appCompatImageButton2 = onView(
allOf(
withContentDescription("Open navigation drawer"),
childAtPosition(
allOf(
withId(R.id.toolbar),
childAtPosition(
withClassName(`is`("com.google.android.material.appbar.AppBarLayout")),
0
)
),
1
),
isDisplayed()
)
)
appCompatImageButton2.perform(click())
val navigationMenuItemView2 = onView(
allOf(
childAtPosition(
allOf(
withId(R.id.design_navigation_view),
childAtPosition(
withId(R.id.nav_view),
0
)
),
2
),
isDisplayed()
)
)
navigationMenuItemView2.perform(click())
val textView2 = onView(
allOf(
withText("Gallery"),
withParent(
allOf(
withId(R.id.toolbar),
withParent(IsInstanceOf.instanceOf(android.widget.LinearLayout::class.java))
)
),
isDisplayed()
)
)
textView2.check(matches(withText("Gallery")))
val appCompatImageButton3 = onView(
allOf(
withContentDescription("Open navigation drawer"),
childAtPosition(
allOf(
withId(R.id.toolbar),
childAtPosition(
withClassName(`is`("com.google.android.material.appbar.AppBarLayout")),
0
)
),
1
),
isDisplayed()
)
)
appCompatImageButton3.perform(click())
val navigationMenuItemView3 = onView(
allOf(
childAtPosition(
allOf(
withId(R.id.design_navigation_view),
childAtPosition(
withId(R.id.nav_view),
0
)
),
1
),
isDisplayed()
)
)
navigationMenuItemView3.perform(click())
val textView3 = onView(
allOf(
withText("Home"),
withParent(
allOf(
withId(R.id.toolbar),
withParent(IsInstanceOf.instanceOf(android.widget.LinearLayout::class.java))
)
),
isDisplayed()
)
)
textView3.check(matches(withText("Home")))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int
): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
| 0 | Java | 1 | 0 | 47ad647fb3280c504fc4f3c2a4d3c850b8699a7e | 6,195 | pragmatic-mobile-testing | Apache License 2.0 |
Common/src/main/java/cn/githink/common/presenter/fragment/AppMvpFragment.kt | Whale0804 | 158,341,321 | false | {"Kotlin": 76448, "Java": 3303} | package cn.githink.common.presenter.fragment
import android.os.Bundle
import cn.githink.common.App
import cn.githink.common.injection.component.ActivityComponent
import cn.githink.common.injection.component.DaggerActivityComponent
import cn.githink.common.injection.module.ActivityModule
import cn.githink.common.injection.module.LifecycleProviderModule
import cn.githink.common.presenter.AppPresenter
import cn.githink.common.presenter.view.AppView
import com.zyao89.view.zloading.Z_TYPE
import javax.inject.Inject
abstract class AppMvpFragment<T: AppPresenter<*>>: AppFragment(), AppView {
/**
* acitviy 持有presenter
*/
@Inject
lateinit var mPresenter: T
lateinit var activityComponent: ActivityComponent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initFragmentInjection()
injectComponent()
}
/**
* 显示加载框的默认实现
*/
override fun showLoading(TYPE: Z_TYPE) {
}
/**
* 显示加载框的默认实现
*/
override fun hideLoading() {
}
/**
* 显示加载框的默认实现
*/
override fun onError(message: String) {
}
abstract fun injectComponent()
private fun initFragmentInjection() {
activityComponent = DaggerActivityComponent.builder()
.appComponent((activity?.application as App).appComponent)
.activityModule(ActivityModule(this.activity!!))
.lifecycleProviderModule(LifecycleProviderModule(this))
.build()
}
} | 0 | Kotlin | 0 | 4 | 44f90eea53e758720f474da6ce6cf0e0b7dbca6a | 1,583 | KotlinApp | Apache License 2.0 |
app/src/main/java/com/cobaltware/webscraper/datahandling/useCases/ModifyBookDialogUseCase.kt | CobaltGoldCS | 316,583,825 | false | null | package com.cobaltware.webscraper.datahandling.useCases
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.cobaltware.webscraper.datahandling.Book
import com.cobaltware.webscraper.datahandling.BookDatabase
import com.cobaltware.webscraper.datahandling.repositories.BookListRepository
import com.cobaltware.webscraper.datahandling.repositories.BookRepository
import kotlinx.coroutines.launch
class ModifyBookDialogUseCase(context: Context) : AndroidViewModel(Application()) {
private val bookRepository: BookRepository
private val bookListRepository: BookListRepository
init {
val database = BookDatabase.getDatabase(context)
bookRepository = BookRepository(database.bookDao())
bookListRepository = BookListRepository(database.bookListDao())
}
fun deleteBook(book: Book) = viewModelScope.launch {
bookRepository.deleteBook(book)
}
fun updateBook(book: Book) = viewModelScope.launch {
bookRepository.updateBook(book)
}
fun addBook(book: Book) = viewModelScope.launch {
bookRepository.addBook(book)
}
fun readAllLists() = bookListRepository.readAllLists()
} | 0 | Kotlin | 0 | 1 | 83ef97580d6b4cdb85f67187e93a0c5aa3b3fc39 | 1,263 | Spindle | MIT License |
GithubUsers/app/src/main/java/com/andzhv/githubusers/request/cache/Cache.kt | adgvcxz | 404,764,273 | true | {"Kotlin": 54161} | package com.andzhv.githubusers.request.cache
import com.andzhv.githubusers.bean.SimpleUserBean
/**
* @param key Cache directory name
* @param unique Cache identifier
* Created by zhaowei on 2021/9/11.
*/
open class Cache<M : Any>(
private val key: String,
private val unique: String,
private val clazz: Class<M>
) {
fun readList(): List<M>? {
return CacheManager.readFromCacheList(key, unique, clazz)
}
fun write(list: List<M>) {
CacheManager.writeToCache(key, unique, list)
}
}
sealed class SimpleUserCache(unique: String) :
Cache<SimpleUserBean>("SimpleUserBean", unique, SimpleUserBean::class.java) {
class DefaultList : SimpleUserCache("List")
}
| 0 | Kotlin | 0 | 0 | 4754727dc9e38383b45405332b982088549fae04 | 712 | test-mobile | MIT License |
app/src/main/java/com/example/androiddevchallenge/AnimatingFabContent.kt | BegumYazici | 345,144,394 | false | null | package com.example.androiddevchallenge
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.util.lerp
import kotlin.math.roundToInt
@Composable
fun AnimatingFabContent(
icon: @Composable () -> Unit,
text: @Composable () -> Unit,
modifier: Modifier = Modifier,
extended: Boolean = true
) {
val currentState = if (extended) ExpandableFabStates.Extended else ExpandableFabStates.Collapsed
val transition = updateTransition(currentState)
val textOpacity by transition.animateFloat(
transitionSpec = {
if (targetState == ExpandableFabStates.Collapsed) {
tween(
easing = LinearEasing,
durationMillis = (transitionDuration / 12f * 5).roundToInt() // 5 / 12 frames
)
} else {
tween(
easing = LinearEasing,
delayMillis = (transitionDuration / 3f).roundToInt(), // 4 / 12 frames
durationMillis = (transitionDuration / 12f * 5).roundToInt() // 5 / 12 frames
)
}
}
) { progress ->
if (progress == ExpandableFabStates.Collapsed) {
0f
} else {
1f
}
}
val fabWidthFactor by transition.animateFloat(
transitionSpec = {
if (targetState == ExpandableFabStates.Collapsed) {
tween(
easing = FastOutSlowInEasing,
durationMillis = transitionDuration
)
} else {
tween(
easing = FastOutSlowInEasing,
durationMillis = transitionDuration
)
}
}
) { progress ->
if (progress == ExpandableFabStates.Collapsed) {
0f
} else {
1f
}
}
// Using functions instead of Floats here can improve performance, preventing recompositions.
IconAndTextRow(
icon,
text,
{ textOpacity },
{ fabWidthFactor },
modifier = modifier
)
}
@Composable
private fun IconAndTextRow(
icon: @Composable () -> Unit,
text: @Composable () -> Unit,
opacityProgress: () -> Float, // Functions instead of Floats, to slightly improve performance
widthProgress: () -> Float,
modifier: Modifier
) {
Layout(
modifier = modifier,
content = {
icon()
Box(modifier = Modifier.alpha(opacityProgress())) {
text()
}
}
) { measurables, constraints ->
val iconPlaceable = measurables[0].measure(constraints)
val textPlaceable = measurables[1].measure(constraints)
val height = constraints.maxHeight
// FAB has an aspect ratio of 1 so the initial width is the height
val initialWidth = height.toFloat()
// Use it to get the padding
val iconPadding = (initialWidth - iconPlaceable.width) / 2f
// The full width will be : padding + icon + padding + text + padding
val expandedWidth = iconPlaceable.width + textPlaceable.width + iconPadding * 3
// Apply the animation factor to go from initialWidth to fullWidth
val width = lerp(initialWidth, expandedWidth, widthProgress())
layout(width.roundToInt(), height) {
iconPlaceable.place(
iconPadding.roundToInt(),
constraints.maxHeight / 2 - iconPlaceable.height / 2
)
textPlaceable.place(
(iconPlaceable.width + iconPadding * 2).roundToInt(),
constraints.maxHeight / 2 - textPlaceable.height / 2
)
}
}
}
private enum class ExpandableFabStates { Collapsed, Extended }
private const val transitionDuration = 200
| 0 | Kotlin | 2 | 7 | c4536a7afddc39cb58560589471ac5f84b77861b | 4,302 | AndroidComposeDevChallangeWeek2 | Apache License 2.0 |
app/src/main/java/com/tmdb/movie/data/SessionData.kt | sqsong66 | 703,818,964 | false | {"Kotlin": 899108} | package com.tmdb.movie.data
import com.google.gson.annotations.SerializedName
data class SessionData(
@SerializedName("failure")
val failure: Boolean = false,
@SerializedName("status_code")
val statusCode: Int = 0,
@SerializedName("status_message")
val statusMessage: String? = null,
@SerializedName("success")
val success: Boolean = false,
@SerializedName("session_id")
val sessionId: String? = null,
)
data class Session(
@SerializedName("session_id")
val sessionId: String
) | 0 | Kotlin | 7 | 15 | 7dfc6aa197d1646773967f06eeef5a998bcda5a3 | 529 | TMDB-Movie | Apache License 2.0 |
trixnity-client/src/commonMain/kotlin/net/folivo/trixnity/client/store/repository/RoomStateRepository.kt | benkuly | 330,904,570 | false | {"Kotlin": 4132578, "JavaScript": 5352, "TypeScript": 2906, "CSS": 1454, "Dockerfile": 1275} | package net.folivo.trixnity.client.store.repository
import net.folivo.trixnity.core.model.RoomId
import net.folivo.trixnity.core.model.events.ClientEvent.StateBaseEvent
interface RoomStateRepository : DeleteByRoomIdMapRepository<RoomStateRepositoryKey, String, StateBaseEvent<*>> {
override fun serializeKey(firstKey: RoomStateRepositoryKey, secondKey: String): String =
firstKey.roomId.full + firstKey.type + secondKey
suspend fun getByRooms(roomIds: Set<RoomId>, type: String, stateKey: String): List<StateBaseEvent<*>>
}
data class RoomStateRepositoryKey(
val roomId: RoomId,
val type: String
) | 0 | Kotlin | 3 | 27 | 645fc08a4aa5a119ca336678ecde33f4bd7aa3e0 | 626 | trixnity | Apache License 2.0 |
src/main/kotlin/data/db/models/BirthdayEntity.kt | FireZenk | 135,927,218 | false | {"Kotlin": 25908} | package data.db.models
import io.jsondb.annotation.Document
import io.jsondb.annotation.Id
@Document(collection = "birthdays", schemaVersion = "1.0")
class BirthdayEntity @JvmOverloads constructor(@Id var id: Long = 0L, var name: String = "", var month: Int = 1,
var day: Int = 1, var year: Int = 1970) | 0 | Kotlin | 0 | 4 | 0e3afee2f8b576c17dbe0edb414fa9c6da085d6c | 351 | HeyBirthday | MIT License |
shimmer/src/main/java/com/cooltechworks/views/shimmer/ShimmerRecyclerView.kt | alejandrorosas | 129,235,519 | true | {"Java": 19579, "Kotlin": 11530} | /**
*
* Copyright 2019 <NAME>
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cooltechworks.views.shimmer
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class ShimmerRecyclerView : RecyclerView {
/**
* Retrieves the actual adapter that contains the data set or null if no adapter is set.
*
* @return The actual adapter
*/
var actualAdapter: Adapter<*>? = null
private set
private var mShimmerLayoutManager: LayoutManager? = null
private var mActualLayoutManager: LayoutManager? = null
private lateinit var mLayoutMangerType: LayoutMangerType
private var mCanScroll: Boolean = false
private var layoutReference: Int = 0
private var mGridCount: Int = 0
lateinit var shimmerAdapter: ShimmerAdapter
enum class LayoutMangerType {
LINEAR_VERTICAL, LINEAR_HORIZONTAL, GRID
}
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
shimmerAdapter = ShimmerAdapter()
val a = context.obtainStyledAttributes(attrs, R.styleable.ShimmerRecyclerView, 0, 0)
try {
setDemoLayoutReference(a.getResourceId(R.styleable.ShimmerRecyclerView_shimmer_demo_layout, R.layout.layout_sample_view))
setDemoChildCount(a.getInteger(R.styleable.ShimmerRecyclerView_shimmer_demo_child_count, 10))
setGridChildCount(a.getInteger(R.styleable.ShimmerRecyclerView_shimmer_demo_grid_child_count, 2))
when (a.getInteger(R.styleable.ShimmerRecyclerView_shimmer_demo_layout_manager_type, 0)) {
0 -> setDemoLayoutManager(LayoutMangerType.LINEAR_VERTICAL)
1 -> setDemoLayoutManager(LayoutMangerType.LINEAR_HORIZONTAL)
2 -> setDemoLayoutManager(LayoutMangerType.GRID)
else -> throw IllegalArgumentException("This value for layout manager is not valid!")
}
shimmerAdapter.apply {
shimmerAngle = a.getInteger(R.styleable.ShimmerRecyclerView_shimmer_demo_angle, 0)
shimmerColor = a.getColor(R.styleable.ShimmerRecyclerView_shimmer_demo_shimmer_color, getColor(R.color.default_shimmer_color))
maskWidth = a.getFloat(R.styleable.ShimmerRecyclerView_shimmer_demo_mask_width, 0.5f)
shimmerItemBackground = a.getDrawable(R.styleable.ShimmerRecyclerView_shimmer_demo_view_holder_item_background)
shimmerDuration = a.getInteger(R.styleable.ShimmerRecyclerView_shimmer_demo_duration, 1500)
isAnimationReversed = a.getBoolean(R.styleable.ShimmerRecyclerView_shimmer_demo_reverse_animation, false)
}
} finally {
a.recycle()
}
showShimmerAdapter()
}
/**
* Specifies the number of child should exist in any row of the grid layout.
*
* @param count - count specifying the number of child.
*/
fun setGridChildCount(count: Int) {
mGridCount = count
}
/**
* Sets the layout manager for the shimmer adapter.
*
* @param type layout manager reference
*/
fun setDemoLayoutManager(type: LayoutMangerType) {
mLayoutMangerType = type
}
/**
* Sets the number of demo views should be shown in the shimmer adapter.
*
* @param count - number of demo views should be shown.
*/
fun setDemoChildCount(count: Int) {
shimmerAdapter.minItemCount = count
}
/**
* Specifies the animation duration of shimmer layout.
*
* @param duration - count specifying the duration of shimmer in millisecond.
*/
fun setDemoShimmerDuration(duration: Int) {
shimmerAdapter.shimmerDuration = duration
}
/**
* Specifies the the width of the shimmer line.
*
* @param maskWidth - float specifying the width of shimmer line. The value should be from 0 to less or equal to 1.
* The default value is 0.5.
*/
fun setDemoShimmerMaskWidth(maskWidth: Float) {
shimmerAdapter.maskWidth = maskWidth
}
/**
* Sets the shimmer adapter and shows the loading screen.
*/
fun showShimmerAdapter() {
mCanScroll = false
if (mShimmerLayoutManager == null) {
initShimmerManager()
}
layoutManager = mShimmerLayoutManager
adapter = shimmerAdapter
}
/**
* Hides the shimmer adapter
*/
fun hideShimmerAdapter() {
mCanScroll = true
layoutManager = mActualLayoutManager
adapter = actualAdapter
}
override fun setLayoutManager(manager: LayoutManager?) {
if (manager == null) {
mActualLayoutManager = null
} else if (manager !== mShimmerLayoutManager) {
mActualLayoutManager = manager
}
super.setLayoutManager(manager)
}
override fun setAdapter(adapter: Adapter<*>?) {
if (adapter == null) {
actualAdapter = null
} else if (adapter !== shimmerAdapter) {
actualAdapter = adapter
}
super.setAdapter(adapter)
}
/**
* Sets the demo layout reference
*
* @param mLayoutReference layout resource id of the layout which should be shown as demo.
*/
fun setDemoLayoutReference(mLayoutReference: Int) {
layoutReference = mLayoutReference
shimmerAdapter.layoutReference = layoutReference
}
private fun initShimmerManager() {
mShimmerLayoutManager = when (mLayoutMangerType) {
LayoutMangerType.LINEAR_VERTICAL -> object : LinearLayoutManager(context) {
override fun canScrollVertically() = mCanScroll
}
LayoutMangerType.LINEAR_HORIZONTAL -> object : LinearLayoutManager(context, HORIZONTAL, false) {
override fun canScrollHorizontally() = mCanScroll
}
LayoutMangerType.GRID -> object : GridLayoutManager(context, mGridCount) {
override fun canScrollVertically() = mCanScroll
}
}
}
private fun getColor(id: Int): Int =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
context.getColor(id)
} else {
@Suppress("DEPRECATION")
resources.getColor(id)
}
}
| 0 | Java | 2 | 0 | 302e39b44cbd31490c2aa67a74a07b05a4b5bab8 | 7,368 | ShimmerRecyclerView | Apache License 2.0 |
app/src/main/java/com/example/goalapp/ui/home/HomeScreen.kt | soikkea | 511,094,118 | false | {"Kotlin": 92568} | package com.example.goalapp.ui.home
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.goalapp.data.GoalWithProgress
import com.example.goalapp.ui.goallist.GoalList
import com.example.goalapp.ui.theme.GoalAppTheme
import com.example.goalapp.viewmodels.GoalListViewModel
import java.time.LocalDate
@Composable
fun HomeScreen(
onFABClick: () -> Unit = {},
onGoalClick: (Long) -> Unit = {},
scaffoldState: ScaffoldState,
viewModel: GoalListViewModel
) {
val goals by viewModel.allGoalsWithProgress.observeAsState(emptyList())
val today = LocalDate.now()
HomeScreenScaffold(onFABClick, goals, today, onGoalClick, scaffoldState)
}
@Composable
private fun HomeScreenScaffold(
onFABClick: () -> Unit,
goals: List<GoalWithProgress>,
date: LocalDate,
onGoalClick: (Long) -> Unit,
scaffoldState: ScaffoldState = rememberScaffoldState()
) {
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = {
Text(text = "Goals")
}
)
},
floatingActionButton = {
FloatingActionButton(onClick = onFABClick) {
Icon(Icons.Default.Add, contentDescription = "Add new goal")
}
}
) { contentPadding ->
GoalList(
modifier = Modifier.padding(contentPadding),
list = goals,
date = date,
onGoalClicked = onGoalClick
)
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
val date = LocalDate.now()
GoalAppTheme {
HomeScreenScaffold(
{},
emptyList(),
date,
{}
)
}
} | 0 | Kotlin | 0 | 0 | 6608af04e56b6ee5e24152f76d8fdfef66fb9ef3 | 2,099 | goalapp | MIT License |
buildSrc/src/main/kotlin/Config.kt | orange-buffalo | 154,902,725 | false | {"Kotlin": 915625, "TypeScript": 536700, "Vue": 256779, "SCSS": 30586, "JavaScript": 6806, "HTML": 633, "CSS": 10} | class Config {
companion object{
const val JVM_VERSION = 21
}
}
| 67 | Kotlin | 0 | 1 | bec32d609ecb678203f5ab1afecb9b7e627858ef | 80 | simple-accounting | Creative Commons Attribution 3.0 Unported |
AdLib/src/main/java/engineer/trustmeimansoftware/adlib/adactivity/AdFullscreenActivityBuilder.kt | hhnlgoettle | 409,128,868 | false | {"Kotlin": 128042, "HTML": 2907} | package engineer.trustmeimansoftware.adlib.adactivity
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
/**
* creates [AdFullscreenActivity] and received their result
*/
open class AdFullscreenActivityBuilder(activity: AppCompatActivity) : IAdFullscreenActivityBuilder {
init {
initialize(activity)
}
private val TAG = "AdFullscreenActivityBuilder"
/**
* [ActivityResultLauncher] used to launch Activities and receive their result
*/
private var launchActivity: ActivityResultLauncher<Intent>? = null;
/**
* initializes an ActivityResultLauncher for launching activities
*
* call this method with the correct AppCompatActivity
* from which you want to launch the AdActivity
*/
@SuppressLint("LongLogTag")
final override fun initialize(activity: AppCompatActivity) {
launchActivity = activity.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()) {
result ->
Log.d(TAG, "Result received from launched Activity: $result")
}
}
/**
* create an intent used to launch an [AdFullscreenActivity]
*/
override fun buildIntent(activity: AppCompatActivity): Intent {
val intent: Intent = Intent(activity, AdFullscreenActivity::class.java).apply {
}
val bundle = Bundle()
intent.putExtras(bundle)
return intent
}
/**
* launches an [Intent] using [launchActivity]
*/
@SuppressLint("LongLogTag")
override fun launchIntent(intent: Intent) {
Log.d("AdFullscreenActivityBuilder", "launching intent")
if(launchActivity == null) throw Error("launchActivity is null. Did you call AdFullscreenActivityBuilder.initialize()?")
launchActivity?.launch(intent)
}
} | 0 | Kotlin | 0 | 0 | ba83eb0e8e2ba28a4c27ad691ba0dddbc4183fe5 | 2,054 | Android-Ad-Library | MIT License |
uni-core/src/main/kotlin/com/github/cf/discord/uni/music/TrackScheduler.kt | CFTheMaster | 180,089,535 | false | null | /*
* Copyright (C) 2017-2021 computerfreaker
*
* 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.cf.discord.uni.music
import com.github.cf.discord.uni.core.EnvVars
import com.github.cf.discord.uni.database.DatabaseWrapper
import com.github.cf.discord.uni.utils.Http
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer
import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason
import net.dv8tion.jda.api.EmbedBuilder
import org.json.JSONObject
import java.awt.Color
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import kotlin.concurrent.timerTask
class TrackScheduler(private val player: AudioPlayer, private val manager: GuildMusicManager) : AudioEventAdapter() {
val queue = LinkedBlockingQueue<AudioTrack>()
fun add(track: AudioTrack) {
if (!player.startTrack(track, true)) queue.offer(track)
}
fun next() = player.startTrack(queue.poll(), false)
fun shuffle() {
val tracks = queue.shuffled()
queue.clear()
queue += tracks
}
override fun onTrackStart(player: AudioPlayer, track: AudioTrack) {
val nextTrack = queue.peek()
val embed = EmbedBuilder()
embed.setTitle("Now playing: ${track.info.title}")
embed.setColor(Color.CYAN)
if (nextTrack != null) {
embed.setFooter("Next: ${nextTrack.info.title}", null)
}
manager.textChannel.sendMessage(embed.build()).queue()
}
override fun onTrackEnd(player: AudioPlayer, track: AudioTrack, endReason: AudioTrackEndReason) {
if (endReason.mayStartNext) {
val nextTrack = queue.peek()
val embed = EmbedBuilder()
embed.setTitle("Track finished: ${track.info.title}")
embed.setColor(Color.CYAN)
if (nextTrack != null) {
embed.setFooter("Next: ${nextTrack.info.title}", null)
}
if (manager.autoplay && track.info.uri.indexOf("youtube") > -1) {
val qs = "?key=${DatabaseWrapper.getCore().get(10, TimeUnit.SECONDS).googleApiKey}&part=snippet&maxResults=10&type=video&relatedToVideoId=${track.info.identifier}"
Http.get("https://www.googleapis.com/youtube/v3/search$qs").thenAccept { res ->
val id = JSONObject(res.body()!!.string())
.getJSONArray("items")
.getJSONObject(0)
.getJSONObject("id")
.getString("videoId")
MusicManager.playerManager.loadItem("https://youtube.com/watch?v=$id", object : AudioLoadResultHandler {
override fun loadFailed(exception: FriendlyException)
= manager.textChannel.sendMessage("[autoplay] Failed to add song to queue: ${exception.message}").queue()
override fun noMatches() = manager.textChannel.sendMessage("[autoplay] YouTube url is (probably) invalid!").queue()
override fun trackLoaded(track: AudioTrack) = manager.scheduler.add(track)
override fun playlistLoaded(playlist: AudioPlaylist) = trackLoaded(playlist.tracks.first())
})
}
} else {
MusicManager.inactivityScheduler.schedule(timerTask {
if (player.playingTrack != null || !manager.textChannel.guild.audioManager.isConnected) {
return@timerTask
}
manager.textChannel.sendMessage("Left voicechannel because of inactivity").queue()
MusicManager.leave(manager.textChannel.guild.id)
}, 300000L)
}
manager.textChannel.sendMessage(embed.build()).queue()
next()
}
}
override fun onTrackException(player: AudioPlayer, track: AudioTrack, exception: FriendlyException)
= manager.textChannel.sendMessage("Error occurred while playing music: ${exception.message}").queue()
}
| 0 | Kotlin | 0 | 6 | 2991c26ffe416aa48ffd978153c866849c6462a7 | 4,942 | Unibot | Apache License 2.0 |
idea/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/collections/hashCodeWithImport.kt | android | 263,405,600 | true | null | // WITH_RUNTIME
import java.util.Arrays.hashCode
fun test() {
val a = arrayOf(1)
val hash = <caret>hashCode(a)
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 121 | kotlin | Apache License 2.0 |
app/src/main/java/org/simple/clinic/setup/SetupActivityModule.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.setup
import com.f2prateek.rx.preferences2.Preference
import com.f2prateek.rx.preferences2.RxSharedPreferences
import dagger.Module
import dagger.Provides
import org.simple.clinic.main.TypedPreference
import org.simple.clinic.main.TypedPreference.Type.DatabaseMaintenanceRunAt
import org.simple.clinic.util.preference.InstantRxPreferencesConverter
import org.simple.clinic.util.preference.getOptional
import java.time.Instant
import java.util.Optional
@Module(includes = [
SetupActivityConfigModule::class
])
class SetupActivityModule {
@Provides
@TypedPreference(DatabaseMaintenanceRunAt)
fun providesDatabaseMaintenanceRunAt(
rxSharedPreferences: RxSharedPreferences
): Preference<Optional<Instant>> {
return rxSharedPreferences.getOptional("database_maintenance_run_at", InstantRxPreferencesConverter())
}
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 862 | simple-android | MIT License |
code generators/de.fhdo.lemma.model_processing.code_generation.springcloud.cqrs/src/main/kotlin/de/fhdo/lemma/model_processing/code_generation/springcloud/cqrs/validators/ServiceModelSourceValidator.kt | SeelabFhdo | 204,692,764 | false | null | package de.fhdo.lemma.model_processing.code_generation.springcloud.cqrs.validators
import de.fhdo.lemma.model_processing.annotations.Before
import de.fhdo.lemma.model_processing.annotations.SourceModelValidator
import de.fhdo.lemma.model_processing.code_generation.springcloud.cqrs.cqrsAlias
import de.fhdo.lemma.model_processing.languages.convertToAbsoluteFileUrisInPlace
import de.fhdo.lemma.model_processing.phases.validation.AbstractXtextModelValidator
import de.fhdo.lemma.model_processing.utils.getServiceAspect
import de.fhdo.lemma.model_processing.utils.getPropertyValue
import de.fhdo.lemma.model_processing.utils.hasInputParameters
import de.fhdo.lemma.model_processing.utils.hasResultParameters
import de.fhdo.lemma.model_processing.utils.hasServiceAspect
import de.fhdo.lemma.service.Interface
import de.fhdo.lemma.service.Microservice
import de.fhdo.lemma.service.Operation
import de.fhdo.lemma.service.ServiceModel
import de.fhdo.lemma.service.ServicePackage
import de.fhdo.lemma.technology.CommunicationType
import org.eclipse.emf.ecore.EStructuralFeature
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.xtext.validation.Check
/**
* Validator for service source models. We implement the validation as an Xtext source model validator to take advantage
* of LEMMA's Live Validation capabilities.
*
* @author [<NAME>](mailto:<EMAIL>)
*/
@Suppress("unused")
@SourceModelValidator
internal class ServiceModelSourceValidator : AbstractXtextModelValidator() {
override fun getSupportedFileExtensions() = setOf("services")
/**
* Prepare import model paths before validation
*/
@Suppress("unused")
@Before
private fun prepareImportModelPaths(resource: Resource) {
val sm = resource.contents[0] as ServiceModel
sm.imports.convertToAbsoluteFileUrisInPlace(resource)
}
/**
* Check command side microservice
*/
@Suppress("unused")
@Check
private fun checkCommandSide(microservice: Microservice) {
if (!microservice.hasSideAspect("CommandSide"))
return
microservice.checkSideOperations { operationsToCheck ->
val hasAsynchronousOutgoingParameters = operationsToCheck.any {
it.hasResultParameters(CommunicationType.ASYNCHRONOUS)
}
if (!hasAsynchronousOutgoingParameters)
warning("Command side should have operations with asynchronous outgoing parameters that communicate " +
"state changes to query sides", microservice.getTargetLiteralForRequiredMicroservicesIssue())
}
}
/**
* Helper to check that this [Microservice] has an aspect from the CQRS technology model with the given
* [sideAspectName]
*/
private fun Microservice.hasSideAspect(sideAspectName: String) : Boolean {
val cqrsAlias = cqrsAlias() ?: return false
return hasServiceAspect(cqrsAlias, sideAspectName)
}
/**
* Helper to run checks on all operations specified for a given side [Microservice]
*/
private fun Microservice.checkSideOperations(checkOperations: (List<Operation>) -> Unit) {
val operationsToCheck = interfaces.map { it.operations }.flatten()
// Note that by intent we also invoke the check-lambda when the list of operations is empty
checkOperations(operationsToCheck)
}
/**
* Helper to determine the target [EStructuralFeature] for issues related to the specified required microservices
* of this [Microservice]
*/
private fun Microservice.getTargetLiteralForRequiredMicroservicesIssue() : EStructuralFeature {
return if (requiredMicroservices.isNotEmpty())
ServicePackage.Literals.MICROSERVICE__REQUIRED_MICROSERVICES
// In case the microservice does not specify required microservices, use the name of the service as issue
// target
else
ServicePackage.Literals.MICROSERVICE__NAME
}
/**
* Check command side interface
*/
@Suppress("unused")
@Check
private fun checkCommandSide(iface: Interface) {
if (!iface.hasSideAspect("CommandSide"))
return
iface.checkSideOperations("CommandSide") { operations ->
val hasAsynchronousOutgoingParameters = operations.any {
it.hasResultParameters(CommunicationType.ASYNCHRONOUS)
}
if (!hasAsynchronousOutgoingParameters)
warning("Command side should have operations with asynchronous outgoing parameters that communicate " +
"state changes to query sides", ServicePackage.Literals.INTERFACE__NAME)
}
}
/**
* Helper to check that this [Interface] has an aspect from the CQRS technology model with the given
* [sideAspectName]
*/
private fun Interface.hasSideAspect(sideAspectName: String) : Boolean {
val cqrsAlias = microservice.cqrsAlias() ?: return false
return hasServiceAspect(cqrsAlias, sideAspectName)
}
/**
* Helper to run checks on all operations specified for a given side [Interface]
*/
private fun Interface.checkSideOperations(sideAspectName: String, checkOperations: (List<Operation>) -> Unit) {
if (!hasSideAspect(sideAspectName))
return
checkOperations(operations)
}
/**
* Check query side microservice
*/
@Suppress("unused")
@Check
private fun checkQuerySide(microservice: Microservice) {
if (!microservice.hasSideAspect("QuerySide"))
return
microservice.checkSideOperations { operationsToCheck ->
val hasAsynchronousIncomingParameters = operationsToCheck.any {
it.hasInputParameters(CommunicationType.ASYNCHRONOUS)
}
if (!hasAsynchronousIncomingParameters)
warning("Query side should have operations with asynchronous incoming parameters to receive state " +
"changes from command sides", ServicePackage.Literals.MICROSERVICE__NAME)
}
// The query side should require a command side in order to receive updates on domain objects' states
val cqrsAlias = microservice.cqrsAlias()!!
val querySideAspect = microservice.getServiceAspect(cqrsAlias, "QuerySide")!!
val logicalService = querySideAspect.getPropertyValue("logicalService") ?: return
if (!microservice.requiresCommandSide(logicalService))
warning("Command side with matching logical service could not be found in required microservices",
microservice.getTargetLiteralForRequiredMicroservicesIssue())
}
/**
* Helper to check whether this query side [Microservice] requires the command side from the same [logicalService]
*/
private fun Microservice.requiresCommandSide(logicalService: String) : Boolean {
return requiredMicroservices.any {
val cqrsAlias = it.microservice.cqrsAlias()
val commandSideAspect = if (cqrsAlias != null)
it.microservice.getServiceAspect(cqrsAlias, "CommandSide")
else
null
commandSideAspect != null && logicalService == commandSideAspect.getPropertyValue("logicalService")
}
}
/**
* Check query side interface
*/
@Suppress("unused")
@Check
private fun checkQuerySide(iface: Interface) {
if (!iface.hasSideAspect("QuerySide"))
return
iface.checkSideOperations("QuerySide") { operations ->
val hasAsynchronousIncomingParameters = operations.any {
it.hasInputParameters(CommunicationType.ASYNCHRONOUS)
}
if (!hasAsynchronousIncomingParameters)
warning("Query side should have operations with asynchronous incoming parameters to receive state " +
"changes from command sides", ServicePackage.Literals.INTERFACE__NAME)
}
// The query side interface should be part of a microservice with a command side interface in order to receive
// updates on domain objects' states
val microservice = iface.microservice
val cqrsAlias = microservice.cqrsAlias()!!
val hasCommandSide = microservice.interfaces.any { it.hasServiceAspect(cqrsAlias, "CommandSide") }
if (!hasCommandSide)
warning("No corresponding command side interface found in microservice",
ServicePackage.Literals.INTERFACE__NAME)
}
} | 26 | Java | 5 | 27 | 2e9ccc882352116b253a7700b5ecf2c9316a5829 | 8,610 | lemma | MIT License |
src/test/kotlin/net/nprod/konnector/gnfinder/GNFinderClientTest.kt | bjonnh | 278,117,237 | false | null | package net.nprod.konnector.gnfinder
import kotlinx.coroutines.asCoroutineDispatcher
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.condition.EnabledIfSystemProperty
import java.util.concurrent.Executors
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@EnabledIfSystemProperty(named = "gnfinderTest", matches = "true")
internal class GNFinderClientTest {
val dispatcher = Executors.newFixedThreadPool(10).asCoroutineDispatcher()
val client = GNFinderClient("localhost:8778", dispatcher)
@Test
fun ping() {
assert(client.ping() == "pong")
}
@Test
fun ver() {
assert(client.ver().startsWith("v"))
}
@Test
fun findNames() {
assert("Curcuma longa" in client.findNames("The source of the compound, Curcuma longa, is a plant."))
}
@Test
fun findPositions() {
val text = "The source of the compound, Curcuma longa, is a plant."
val species = "Curcuma longa"
val output = client.findNamesToStructured(text, verification = false)
assert(output.names?.first()?.offsetStart == text.indexOf(species))
}
@Test
fun findNamesWithSources() {
assert(
"Plantae|Tracheophyta|Liliopsida|Zingiberales|Zingiberaceae|Curcuma|Curcuma longa" in
client.findNames(
"The source of the compound, Curcuma longa, is a plant.",
sources = (1..182),
verification = true
)
)
}
@AfterAll
internal fun done() {
client.close()
dispatcher.close()
}
}
| 0 | Kotlin | 0 | 0 | ab8e0a0a7e245783e7a1c7ea42f2a5e5b7837aa0 | 1,688 | konnector | MIT License |
widget/src/main/kotlin/com/tasomaniac/devwidget/widget/WidgetViewsService.kt | tasomaniac | 117,675,057 | false | null | package com.tasomaniac.devwidget.widget
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import com.tasomaniac.devwidget.data.Action
import com.tasomaniac.devwidget.data.AppDao
import com.tasomaniac.devwidget.data.FavActionDao
import com.tasomaniac.devwidget.data.findFavActionByWidgetIdSync
import com.tasomaniac.devwidget.settings.Sorting.ALPHABETICALLY_NAMES
import com.tasomaniac.devwidget.settings.Sorting.ALPHABETICALLY_PACKAGES
import com.tasomaniac.devwidget.settings.Sorting.ORDER_ADDED
import com.tasomaniac.devwidget.settings.SortingPreferences
import dagger.android.AndroidInjection
import javax.inject.Inject
internal class WidgetViewsService : RemoteViewsService() {
@Inject lateinit var appDao: AppDao
@Inject lateinit var favActionDao: FavActionDao
@Inject lateinit var applicationInfoResolver: ApplicationInfoResolver
@Inject lateinit var sortingPreferences: SortingPreferences
@Inject lateinit var itemCreator: ItemRemoteViewsCreator
override fun onCreate() {
AndroidInjection.inject(this)
super.onCreate()
}
override fun onGetViewFactory(intent: Intent) = WidgetViewsFactory(intent.appWidgetId, intent.widgetWidth)
inner class WidgetViewsFactory(
private val appWidgetId: Int,
private val widgetWidth: Int
) : RemoteViewsFactory {
private var apps: List<DisplayApplicationInfo> = emptyList()
private var favAction: Action = Action.UNINSTALL
override fun onDataSetChanged() {
val packageNames = appDao.findAppsByWidgetIdSync(appWidgetId)
apps = packageNames.flatMap(applicationInfoResolver::resolve).sort()
favAction = favActionDao.findFavActionByWidgetIdSync(appWidgetId)
}
private fun List<DisplayApplicationInfo>.sort() = when (sortingPreferences.sorting) {
ORDER_ADDED -> asReversed()
ALPHABETICALLY_PACKAGES -> sortedBy { it.packageName }
ALPHABETICALLY_NAMES -> sortedBy { it.label.toString() }
}
override fun getViewAt(position: Int): RemoteViews {
val app = apps[position]
return itemCreator.createViewWith(app, favAction, widgetWidth)
}
override fun getCount() = apps.size
override fun getViewTypeCount() = 1
override fun getItemId(position: Int) = apps[position].packageName.hashCode().toLong()
override fun hasStableIds() = true
override fun getLoadingView(): RemoteViews? = null
override fun onCreate() = Unit
override fun onDestroy() = Unit
}
companion object {
const val WIDGET_WIDTH = "widget_width"
private val Intent.widgetWidth: Int
get() = getIntExtra(WIDGET_WIDTH, Int.MAX_VALUE)
private val Intent.appWidgetId
get() = getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID
)
}
}
| 5 | Kotlin | 5 | 35 | c8f25f18a1b7f86146e21567cbe0aa7847e4451c | 3,056 | DevWidget | Apache License 2.0 |
BaseModule/src/main/java/com/chen/basemodule/mlist/layoutmanager/SkidRightLayoutManager.kt | chen397254698 | 268,411,455 | false | null | package com.chen.basemodule.mlist.layoutmanager
import android.view.View
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Recycler
import java.util.*
/**
* Created by 钉某人
* github: https://github.com/DingMouRen
* email: <EMAIL>
*/
class SkidRightLayoutManager(private val mItemHeightWidthRatio: Float, private val mScale: Float) : RecyclerView.LayoutManager() {
private var mHasChild = false
private var mItemViewWidth = 0
private var mItemViewHeight = 0
private var mScrollOffset = Int.MAX_VALUE
private var mItemCount = 0
private val mSkidRightSnapHelper by lazy { SkidRightSnapHelper() }
/**
* Sets true to scroll layout in left direction.
*/
var isReverseDirection = false
private val verticalSpace: Int
get() = height - paddingTop - paddingBottom
private val horizontalSpace: Int
get() = width - paddingLeft - paddingRight
override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
return RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT,
RecyclerView.LayoutParams.WRAP_CONTENT)
}
override fun onAttachedToWindow(view: RecyclerView) {
super.onAttachedToWindow(view)
mSkidRightSnapHelper.attachToRecyclerView(view)
}
fun getFixedScrollPosition(direction: Int, fixValue: Float): Int {
if (mHasChild) {
if (mScrollOffset % mItemViewWidth == 0) {
return RecyclerView.NO_POSITION
}
val itemPosition = position()
val layoutPosition = (if (direction > 0) itemPosition + fixValue else itemPosition + (1 - fixValue)).toInt() - 1
return convert2AdapterPosition(layoutPosition)
}
return RecyclerView.NO_POSITION
}
override fun onLayoutChildren(recycler: Recycler, state: RecyclerView.State) {
if (state.itemCount == 0 || state.isPreLayout) return
removeAndRecycleAllViews(recycler)
if (!mHasChild) {
mItemViewHeight = verticalSpace
mItemViewWidth = (mItemViewHeight / mItemHeightWidthRatio).toInt()
mHasChild = true
}
mItemCount = itemCount
mScrollOffset = makeScrollOffsetWithinRange(mScrollOffset)
fill(recycler)
}
private fun position(): Float {
return if (isReverseDirection) (mScrollOffset + mItemCount * mItemViewWidth) * 1.0f / mItemViewWidth else mScrollOffset * 1.0f / mItemViewWidth
}
fun fill(recycler: Recycler) {
var bottomItemPosition = Math.floor(position().toDouble()).toInt()
val space = horizontalSpace
val bottomItemVisibleSize = if (isReverseDirection) ((mItemCount - 1) * mItemViewWidth + mScrollOffset) % mItemViewWidth else mScrollOffset % mItemViewWidth
val offsetPercent = bottomItemVisibleSize * 1.0f / mItemViewWidth
var remainSpace = if (isReverseDirection) 0 else space - mItemViewWidth
val baseOffsetSpace = if (isReverseDirection) mItemViewWidth else horizontalSpace - mItemViewWidth
val layoutInfos = ArrayList<ItemViewInfo>()
run {
var i = bottomItemPosition - 1
var j = 1
while (i >= 0) {
val maxOffset = baseOffsetSpace / 2 * Math.pow(mScale.toDouble(), j.toDouble())
val adjustedPercent = if (isReverseDirection) -offsetPercent else +offsetPercent
val start = (remainSpace - adjustedPercent * maxOffset).toInt()
val scaleXY = (Math.pow(mScale.toDouble(), j - 1.toDouble()) * (1 - offsetPercent * (1 - mScale))).toFloat()
val percent = start * 1.0f / space
val info = ItemViewInfo(start, scaleXY, offsetPercent, percent)
layoutInfos.add(0, info)
val delta = if (isReverseDirection) maxOffset else -maxOffset
remainSpace += delta.toInt()
val isOutOfSpace = if (isReverseDirection) remainSpace > horizontalSpace else remainSpace <= 0
if (isOutOfSpace) {
info.top = (remainSpace - delta).toInt()
info.positionOffset = 0f
info.layoutPercent = info.top / space.toFloat()
info.scaleXY = Math.pow(mScale.toDouble(), j - 1.toDouble()).toFloat()
break
}
i--
j++
}
}
if (bottomItemPosition < mItemCount) {
val start = if (isReverseDirection) bottomItemVisibleSize - mItemViewWidth else space - bottomItemVisibleSize
layoutInfos.add(
ItemViewInfo(start,
1.0f,
offsetPercent,
start * 1.0f / space).setIsBottom())
} else {
bottomItemPosition -= 1
}
val layoutCount = layoutInfos.size
val startPos = bottomItemPosition - (layoutCount - 1)
val endPos = bottomItemPosition
val childCount = childCount
for (i in childCount - 1 downTo 0) {
val childView = getChildAt(i)
val pos = convert2LayoutPosition(getPosition(childView!!))
if (pos > endPos || pos < startPos) {
removeAndRecycleView(childView, recycler)
}
}
detachAndScrapAttachedViews(recycler)
for (i in 0 until layoutCount) {
val position = convert2AdapterPosition(startPos + i)
fillChild(recycler.getViewForPosition(position), layoutInfos[i])
}
}
private fun fillChild(view: View, layoutInfo: ItemViewInfo) {
addView(view)
measureChildWithExactlySize(view)
val scaleFix = (mItemViewWidth * (1 - layoutInfo.scaleXY) / 2).toInt()
val left = layoutInfo.top - scaleFix
val top = paddingTop
val right = layoutInfo.top + mItemViewWidth - scaleFix
val bottom = top + mItemViewHeight
layoutDecoratedWithMargins(view, left, top, right, bottom)
ViewCompat.setScaleX(view, layoutInfo.scaleXY)
ViewCompat.setScaleY(view, layoutInfo.scaleXY)
}
private fun measureChildWithExactlySize(child: View) {
val lp = child.layoutParams as RecyclerView.LayoutParams
val widthSpec = View.MeasureSpec.makeMeasureSpec(
mItemViewWidth - lp.leftMargin - lp.rightMargin, View.MeasureSpec.EXACTLY)
val heightSpec = View.MeasureSpec.makeMeasureSpec(
mItemViewHeight - lp.topMargin - lp.bottomMargin, View.MeasureSpec.EXACTLY)
child.measure(widthSpec, heightSpec)
}
private fun makeScrollOffsetWithinRange(scrollOffset: Int): Int {
return if (isReverseDirection) {
Math.max(Math.min(0, scrollOffset), -(mItemCount - 1) * mItemViewWidth)
} else {
Math.min(Math.max(mItemViewWidth, scrollOffset), mItemCount * mItemViewWidth)
}
}
override fun scrollHorizontallyBy(dx: Int, recycler: Recycler, state: RecyclerView.State): Int {
val delta = if (isReverseDirection) -dx else dx
val pendingScrollOffset = mScrollOffset + delta
mScrollOffset = makeScrollOffsetWithinRange(pendingScrollOffset)
fill(recycler)
return mScrollOffset - pendingScrollOffset + delta
}
fun calculateDistanceToPosition(targetPos: Int): Int {
if (isReverseDirection) {
return mItemViewWidth * targetPos + mScrollOffset
}
val pendingScrollOffset = mItemViewWidth * (convert2LayoutPosition(targetPos) + 1)
return pendingScrollOffset - mScrollOffset
}
override fun scrollToPosition(position: Int) {
if (position in 1 until mItemCount) {
mScrollOffset = mItemViewWidth * (convert2LayoutPosition(position) + 1)
requestLayout()
}
}
override fun canScrollHorizontally(): Boolean {
return true
}
fun convert2AdapterPosition(layoutPosition: Int): Int {
return mItemCount - 1 - layoutPosition
}
fun convert2LayoutPosition(adapterPostion: Int): Int {
return mItemCount - 1 - adapterPostion
}
} | 1 | Kotlin | 14 | 47 | 85ffc5e307c6171767e14bbfaf992b8d62ec1cc6 | 8,282 | EasyAndroid | Apache License 2.0 |
src/main/java/ink/anur/core/client/ClientOperateHandler.kt | anurnomeru | 242,305,129 | false | null | package ink.anur.core.client
import ink.anur.common.KanashiRunnable
import ink.anur.common.Shutdownable
import ink.anur.common.struct.KanashiNode
import ink.anur.io.client.ReConnectableClient
import ink.anur.io.common.ShutDownHooker
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
/**
* Created by <NAME> on 2020/2/23
*
* 连接某客户端的 client
*/
class ClientOperateHandler(kanashiNode: KanashiNode,
/**
* 当受到对方的注册回调后,触发此函数,注意 它可能会被多次调用
*/
doAfterConnectToServer: (() -> Unit)? = null,
/**
* 当连接上对方后,如果断开了连接,做什么处理
*
* 返回 true 代表继续重连
* 返回 false 则不再重连
*/
doAfterDisConnectToServer: (() -> Boolean)? = null)
: KanashiRunnable(), Shutdownable {
private val serverShutDownHooker = ShutDownHooker("终止与协调节点 $kanashiNode 的连接")
private var ctx: Channel? = null
private val coordinateClient = ReConnectableClient(kanashiNode, this.serverShutDownHooker, { synchronized(this) { ctx = it } }, doAfterConnectToServer, doAfterDisConnectToServer)
private fun getChannel(): Channel {
synchronized(this) {
return ctx!!
}
}
override fun run() {
if (serverShutDownHooker.isShutDown()) {
println("zzzzzzzz??????????????zzzzzzzzzzzzzzzzzzzzzzzz")
} else {
coordinateClient.start()
}
}
override fun shutDown() {
serverShutDownHooker.shutdown()
}
} | 1 | Kotlin | 1 | 5 | 27db6442ef9d4abc594d7e7719a8c772f03e61b6 | 1,864 | kanashi | MIT License |
src/main/kotlin/jetbrains/buildServer/notification/slackNotifier/healthReport/SlackInvalidBuildFeatureExtension.kt | JetBrains | 294,444,752 | false | {"Kotlin": 247902, "Java": 39261} |
package jetbrains.buildServer.notification.slackNotifier.healthReport
import jetbrains.buildServer.serverSide.BuildTypeNotFoundException
import jetbrains.buildServer.serverSide.ProjectManager
import jetbrains.buildServer.serverSide.SBuildFeatureDescriptor
import jetbrains.buildServer.serverSide.WebLinks
import jetbrains.buildServer.serverSide.auth.Permission
import jetbrains.buildServer.web.openapi.PagePlaces
import jetbrains.buildServer.web.openapi.PluginDescriptor
import jetbrains.buildServer.web.openapi.healthStatus.HealthStatusItemPageExtension
import jetbrains.buildServer.web.util.SessionUser
import org.springframework.stereotype.Service
import javax.servlet.http.HttpServletRequest
@Service
class SlackInvalidBuildFeatureExtension(
pagePlaces: PagePlaces,
pluginDescriptor: PluginDescriptor,
private val webLinks: WebLinks,
private val projectManager: ProjectManager
) : HealthStatusItemPageExtension(SlackBuildFeatureHealthReport.type, pagePlaces) {
init {
includeUrl = pluginDescriptor.getPluginResourcesPath("/healthReport/invalidBuildFeature.jsp")
isVisibleOutsideAdminArea = false
register()
}
override fun isAvailable(request: HttpServletRequest): Boolean {
if (!super.isAvailable(request)) {
return false;
}
val user = SessionUser.getUser(request)
val statusItem = getStatusItem(request)
val data = statusItem.additionalData
val buildTypeId = data["buildTypeId"] as String
val buildType = projectManager.findBuildTypeByExternalId(buildTypeId)
if (buildType != null) {
if (!user.isPermissionGrantedForProject(buildType.projectId, Permission.RUN_BUILD)) {
return false
}
}
return true;
}
override fun fillModel(model: MutableMap<String, Any>, request: HttpServletRequest) {
super.fillModel(model, request)
val statusItem = getStatusItem(request)
val data = statusItem.additionalData
model["reason"] = data["reason"] as String
model["feature"] = data["feature"] as SBuildFeatureDescriptor
val type = data["type"] as String
val id = data["buildTypeId"] as String
if (type == "buildType") {
model["editUrl"] = webLinks.getEditConfigurationPageUrl(id)
val buildType = projectManager.findBuildTypeByExternalId(id)
?: throw BuildTypeNotFoundException("Can't find build type with external id '${id}'")
model["buildTypeName"] = buildType.fullName
} else {
model["editUrl"] = webLinks.getEditTemplatePageUrl(id)
val template = projectManager.findBuildTypeTemplateByExternalId(id)
?: throw BuildTypeNotFoundException("Can't find build template type with external id '${id}'")
model["buildTypeName"] = template.fullName
}
}
} | 2 | Kotlin | 8 | 7 | 629c1bbae964f7106332439e83dd673ce583d917 | 2,924 | teamcity-slack-notifier | Apache License 2.0 |
lib-chain-bitcoin-core/src/main/java/com/smallraw/chain/bitcoincore/transaction/Transaction.kt | QuincySx | 262,699,409 | false | null | package com.smallraw.chain.bitcoincore.transaction
import com.smallraw.chain.bitcoincore.script.Script
import com.smallraw.chain.bitcoincore.transaction.serializers.TransactionSerializer
import com.smallraw.crypto.core.extensions.toHex
import java.util.*
open class Transaction(
var inputs: Array<Input>,
var outputs: Array<Output>,
var version: Int = DEFAULT_TX_VERSION,
var lockTime: Int = DEFAULT_TX_LOCKTIME
) {
fun hasSegwit(): Boolean {
inputs.filter { it.hasWitness() }
.forEach { _ ->
return true
}
return false
}
class InputWitness(pushCount: Int = 0) {
private val stack = ArrayList<ByteArray>(Math.min(pushCount, MAX_INITIAL_ARRAY_LENGTH))
fun stackCount() = stack.size
fun setStack(i: Int, value: ByteArray) {
while (i >= stack.size) {
stack.add(byteArrayOf())
}
stack[i] = value
}
fun addStack(value: Byte) {
addStack(byteArrayOf(value))
}
fun addStack(value: ByteArray) {
stack.add(value)
}
fun iterator(): MutableIterator<ByteArray> {
return stack.iterator()
}
override fun toString(): String {
return printAsJsonArray(stack.toArray())
}
companion object {
@JvmStatic
fun default() = InputWitness()
const val MAX_INITIAL_ARRAY_LENGTH = 20
}
}
class Input(
val outPoint: OutPoint,
var script: Script? = null,
var sequence: Int = DEFAULT_TX_SEQUENCE,
var witness: InputWitness = InputWitness.default()
) {
constructor(
hash: ByteArray,
index: Int,
script: Script? = null,
sequence: Int = DEFAULT_TX_SEQUENCE,
witness: InputWitness = InputWitness.default()
) : this(OutPoint(hash, index), script, sequence, witness)
companion object {
fun default() = Input(OutPoint.default())
}
fun hasWitness(): Boolean {
return witness.stackCount() != 0
}
override fun toString(): String {
return """
{
"outPoint":$outPoint,
"script":"$script",
"sequence":"$sequence",
"witnesses":$witness
}"""
}
}
class OutPoint(
val hash: ByteArray,
val index: Int
) {
companion object {
fun default() = OutPoint(byteArrayOf(), 0)
}
override fun toString(): String {
return """
{
"hash":"${hash.toHex()}",
"index":"$index"
}"""
}
}
class Output(
val value: Long,
val script: Script?
) {
companion object {
fun default() = Output(0L, Script())
}
override fun toString(): String {
return """
{
"value":"${value * 1e-8}",
"script":"$script"
}"""
}
}
override fun toString(): String {
return """
{
"version":"$version",
"lockTime":"$lockTime",
"segwit":"${hasSegwit()}",
"inputs":
${printAsJsonArray(inputs)},
"outputs":
${printAsJsonArray(outputs)},
}
""".trimIndent()
}
/**
* 采用序列化的方式 copy 交易
*/
fun copy(): Transaction =
TransactionSerializer.deserialize(TransactionSerializer.serialize(this))
companion object {
val NEGATIVE_SATOSHI = -1L
val DEFAULT_TX_VERSION = 2
val DEFAULT_TX_LOCKTIME = 0x00000000
val EMPTY_TX_SEQUENCE = 0x00000000
val DEFAULT_TX_SEQUENCE = 0xFFFFFFFF.toInt()
}
}
private fun printAsJsonArray(a: Array<*>): String {
if (a.isEmpty()) {
return "[]"
}
val iMax = a.size - 1
val sb = StringBuilder()
sb.append('[')
var i = 0
while (true) {
sb.append(a[i].toString())
if (i == iMax) return sb.append(']').toString()
sb.append(",\n")
i++
}
} | 1 | C | 6 | 26 | 0beea2170ea56e2dd224fe0e174d5ac2951632ca | 4,304 | ChainWallet | Apache License 2.0 |
backend/src/main/kotlin/eu/yeger/finwa/model/persistence/PersistentUser.kt | DerYeger | 339,876,917 | false | {"TypeScript": 65692, "Kotlin": 37898, "SCSS": 10353, "HTML": 8232, "JavaScript": 2858, "Dockerfile": 543, "Shell": 185} | package eu.yeger.finwa.model.persistence
import eu.yeger.finwa.model.api.ApiUser
import eu.yeger.finwa.model.domain.User
import kotlinx.serialization.Serializable
@Serializable
public data class PersistentUser(
override val id: String,
val name: String,
val password: String
) : Entity
public fun PersistentUser.toUser(): User =
User(
id = id,
name = name,
password = <PASSWORD>
)
public fun PersistentUser.toApiUser(): ApiUser =
ApiUser(
id = id,
name = name
)
| 0 | TypeScript | 0 | 1 | ab3211a39ea82a2d5f402a1ff2450cd2b95db8b8 | 498 | finwa-legacy | MIT License |
src/main/kotlin/tech/michalik/flowriddles/solutions/Riddle6Solution.kt | rozkminiacz | 221,536,359 | false | null | package tech.michalik.flowriddles.solutions
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.zip
object Riddle6Solution {
/**
* Combine two flows - sum corresponding values of [source1] and [source2].
*/
fun solve(source1: Flow<Int>, source2: Flow<Int>): Flow<Int> {
return source1.zip(other = source2, transform = { a, b ->
a + b
})
}
} | 1 | Kotlin | 2 | 32 | f72675059b18872d6c1ec63d2d18cfe92497f2cb | 407 | FlowRiddles | Apache License 2.0 |
app/src/test/java/com/kshitijpatil/tazabazar/fixtures/product/Products.kt | Kshitij09 | 395,308,440 | false | null | package com.kshitijpatil.tazabazar.fixtures.product
import com.kshitijpatil.tazabazar.data.local.entity.InventoryEntity
import com.kshitijpatil.tazabazar.data.local.entity.ProductCategoryEntity
import com.kshitijpatil.tazabazar.data.local.entity.ProductEntity
import com.kshitijpatil.tazabazar.data.local.entity.ProductWithInventories
import org.threeten.bp.OffsetDateTime
val vegetables = ProductCategoryEntity("vegetables", "Vegetables", "vgt")
val leafyVegetables = ProductCategoryEntity("leafy-vegetables", "Leafy Vegetables", "lfvgt")
val fruits = ProductCategoryEntity("fruits", "Fruits", "fru")
val tomatoRed = ProductEntity("vgt-001", "Tomato Red", vegetables.label, "image-uri")
val tomatoRedInv1 = InventoryEntity(1, tomatoRed.sku, 15f, "500 gm", 31, OffsetDateTime.now())
val tomatoRedInv2 = InventoryEntity(2, tomatoRed.sku, 25f, "1 kg", 15, OffsetDateTime.now())
val tomatoGreen = ProductEntity("vgt-002", "Green Tomato", vegetables.label, "image-uri")
val tomatoGreenInv1 = InventoryEntity(3, tomatoGreen.sku, 10f, "300 gm", 10, OffsetDateTime.now())
val sitafal = ProductEntity("fru-001", "Sitafal", fruits.label, "image-uri")
val sitafalInv = InventoryEntity(4, sitafal.sku, 50f, "500 gm", 5, OffsetDateTime.now())
val allProductEntities = listOf(tomatoRed, tomatoGreen, sitafal)
val allCategoryEntities = listOf(vegetables, leafyVegetables, fruits)
val allInventoryEntities = listOf(tomatoRedInv1, tomatoRedInv2, tomatoGreenInv1, sitafalInv)
val tomatoRedProductWithInventories =
ProductWithInventories(tomatoRed, listOf(tomatoRedInv1, tomatoRedInv2))
val tomatoGreenProductWithInventories = ProductWithInventories(tomatoGreen, listOf(tomatoGreenInv1))
val sitafalProductWithInventories = ProductWithInventories(sitafal, listOf(sitafalInv))
val allProductWithInventories = listOf(
tomatoRedProductWithInventories,
tomatoGreenProductWithInventories,
sitafalProductWithInventories
) | 8 | Kotlin | 2 | 1 | d709b26d69cf46c3d6123a217190f098b79a6562 | 1,916 | TazaBazar | Apache License 2.0 |
app/src/main/java/com/hari/notty/ui/auth/SignInScreen.kt | Ekta-jain | 514,001,210 | false | {"Kotlin": 83145} | package com.hari.notty.ui.auth
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusState
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import com.google.accompanist.insets.systemBarsPadding
import com.hari.notty.R
import com.hari.notty.ui.components.NottyTextField
import com.hari.notty.ui.theme.Blue
import com.hari.notty.ui.theme.Facebook
import com.hari.notty.ui.theme.Google
import com.hari.notty.ui.theme.NottyGray
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
@Destination()
@Composable
fun SignInScreen(
navigator: DestinationsNavigator
) {
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var emailLeadingIconTint by remember { mutableStateOf(NottyGray.copy(alpha = 0.38f)) }
var passwordLeadingIconTint by remember { mutableStateOf(NottyGray.copy(alpha = 0.38f)) }
var passwordVisibility: Boolean by remember { mutableStateOf(false) }
Column(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding()
.padding(vertical = 16.dp)
.verticalScroll(rememberScrollState())
.background(MaterialTheme.colors.surface),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
modifier = Modifier.padding(horizontal = 16.dp).weight(1f),
painter = painterResource(id = R.drawable.ic_notebook),
contentDescription = "Welcome Image"
)
Spacer(modifier = Modifier.height(20.dp))
Text(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp),
text = stringResource(id = R.string.login),
style = MaterialTheme.typography.h4.copy(fontWeight = FontWeight.ExtraBold)
)
Spacer(modifier = Modifier.height(20.dp))
NottyTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
.onFocusChanged { focusState: FocusState ->
emailLeadingIconTint = if (focusState.isFocused) {
Blue
} else {
NottyGray.copy(alpha = .38f)
}
},
value = email,
onValueChange = { email = it },
label = stringResource(R.string.email),
singleLine = true,
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Email),
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.ic_outline_email_24),
contentDescription = "",
tint = emailLeadingIconTint
)
}
)
Spacer(modifier = Modifier.height(8.dp))
NottyTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
.onFocusChanged { focusState: FocusState ->
passwordLeadingIconTint = if (focusState.isFocused) {
Blue
} else {
NottyGray.copy(alpha = .38f)
}
},
value = password,
onValueChange = { password = it },
label = stringResource(R.string.password),
singleLine = true,
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.ic_outline_lock_open_24),
contentDescription = "",
tint = passwordLeadingIconTint
)
},
visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
val image = if (passwordVisibility)
Icons.Filled.Visibility
else Icons.Filled.VisibilityOff
IconButton(onClick = { passwordVisibility = !passwordVisibility }) {
Icon(
imageVector = image,
contentDescription = "",
tint = passwordLeadingIconTint
)
}
},
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Password)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(end = 16.dp),
horizontalArrangement = Arrangement.End
) {
TextButton(onClick = { }) {
Text("Forget Password?", color = Blue)
}
}
Spacer(modifier = Modifier.height(20.dp))
Button(
modifier = Modifier.width(200.dp),
onClick = { },
shape = RoundedCornerShape(50),
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.Blue,
contentColor = Color.White
)
) {
Text(
text = "Login",
modifier = Modifier.padding(vertical = 5.dp),
style = MaterialTheme.typography.button.copy(fontWeight = FontWeight.Bold)
)
}
Spacer(modifier = Modifier.height(40.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
IconButton(
onClick = { },
modifier = Modifier
.then(Modifier.size(50.dp))
.background(Facebook, shape = CircleShape)
) {
Icon(
painter = painterResource(id = R.drawable.ic_facebook),
contentDescription = "Facebook button",
tint = Color.White
)
}
Spacer(modifier = Modifier.size(8.dp))
IconButton(
onClick = { },
modifier = Modifier
.then(Modifier.size(50.dp))
.background(Google, shape = CircleShape)
) {
Icon(
painter = painterResource(id = R.drawable.ic_google),
contentDescription = "Google button",
tint = Color.White
)
}
}
Spacer(modifier = Modifier.height(10.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "New to Notty?",
style = MaterialTheme.typography.body2.copy(color = Color.Gray)
)
TextButton(onClick = { }) {
Text("Signup", color = Blue)
}
}
}
}
| 0 | null | 0 | 0 | 17ed91265c7ea71bcb398948778f2fd82436fbb5 | 8,128 | NottyAndroidApp | MIT License |
compiler/testData/diagnostics/tests/multiplatform/widerVisibility_expectSetterIsEffectivelyFinal_fakeOverride.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// MODULE: m1-common
// FILE: common.kt
open class Base {
open var foo: Int = 2
protected set
}
expect class Foo : Base
// MODULE: m2-jvm()()(m1-common)
// FILE: jvm.kt
actual class Foo : Base() {
override var foo: Int = 2
public set
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 280 | kotlin | Apache License 2.0 |
app/src/main/java/com/mcakir/owlchat/entry/entity/User.kt | MuhammetCakir | 380,795,062 | false | null | package com.mcakir.owlchat.entry.entity
data class User(val nickname: String?) {
fun isModelValid(): Boolean = !nickname.isNullOrEmpty()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as User
if (nickname != other.nickname) return false
return true
}
override fun hashCode(): Int {
return nickname?.hashCode() ?: 0
}
}
| 0 | Kotlin | 0 | 0 | 48ff5bbb7354627b7cc79555c5d26c5ff1fe0395 | 476 | owl-chat | Apache License 2.0 |
targets/aws-iot-analytics-target/src/main/kotlin/com/amazonaws/sfc/awsiota/config/AwsIotAnalyticsWriterConfiguration.kt | aws-samples | 700,380,828 | false | {"Kotlin": 2245850, "Python": 6111, "Dockerfile": 4679, "TypeScript": 4547, "JavaScript": 1171} |
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
package com.amazonaws.sfc.awsiota.config
import com.amazonaws.sfc.awsiot.AwsIotCredentialProviderClientConfiguration
import com.amazonaws.sfc.client.AwsServiceTargetsConfig
import com.amazonaws.sfc.config.*
import com.amazonaws.sfc.log.LogLevel
import com.google.gson.annotations.SerializedName
/**
* AWS Iot Analytics target configuration
* @see AwsIotAnalyticsTargetConfiguration
*/
@ConfigurationClass
class AwsIotAnalyticsWriterConfiguration : AwsServiceTargetsConfig<AwsIotAnalyticsTargetConfiguration>, BaseConfigurationWithMetrics(), Validate {
@SerializedName(CONFIG_TARGETS)
private var _targets: Map<String, AwsIotAnalyticsTargetConfiguration> = emptyMap()
/**
* Configured Iot Analytics target streams.
*/
override val targets: Map<String, AwsIotAnalyticsTargetConfiguration>
get() = _targets.filter { (it.value.targetType == AWS_IOT_ANALYTICS) }
/**
* Validates configuration.
* @throws ConfigurationException
*/
override fun validate() {
if (validated) return
super.validate()
targets.forEach {
it.value.validate()
}
validated = true
}
companion object {
const val AWS_IOT_ANALYTICS = "AWS-IOT-ANALYTICS"
private val default = AwsIotAnalyticsWriterConfiguration()
fun create(targets: Map<String, AwsIotAnalyticsTargetConfiguration> = default._targets,
name: String = default._name,
version: String = default._version,
awsVersion: String? = default._awsVersion,
description: String = default._description,
schedules: List<ScheduleConfiguration> = default._schedules,
logLevel: LogLevel? = default._logLevel,
metadata: Map<String, String> = default._metadata,
elementNames: ElementNamesConfiguration = default._elementNames,
targetServers: Map<String, ServerConfiguration> = default._targetServers,
targetTypes: Map<String, InProcessConfiguration> = default._targetTypes,
adapterServers: Map<String, ServerConfiguration> = default._protocolAdapterServers,
adapterTypes: Map<String, InProcessConfiguration> = default._protocolTypes,
awsIotCredentialProviderClients: Map<String, AwsIotCredentialProviderClientConfiguration> = default._awsIoTCredentialProviderClients,
secretsManagerConfiguration: SecretsManagerConfiguration? = default._secretsManagerConfiguration): AwsIotAnalyticsWriterConfiguration {
val instance = createBaseConfiguration<AwsIotAnalyticsWriterConfiguration>(
name = name,
version = version,
awsVersion = awsVersion,
description = description,
schedules = schedules,
logLevel = logLevel,
metadata = metadata,
elementNames = elementNames,
targetServers = targetServers,
targetTypes = targetTypes,
adapterServers = adapterServers,
adapterTypes = adapterTypes,
awsIotCredentialProviderClients = awsIotCredentialProviderClients,
secretsManagerConfiguration = secretsManagerConfiguration)
instance._targets = targets
return instance
}
}
}
| 5 | Kotlin | 2 | 15 | fd38dbb80bf6be06c00261d9992351cc8a103a63 | 3,569 | shopfloor-connectivity | MIT No Attribution |
app/src/main/java/com/tanjiajun/androidgenericframework/data/dao/user/UserDao.kt | GongTommy | 246,767,566 | true | {"Kotlin": 91154} | package com.tanjiajun.androidgenericframework.data.dao.user
import android.content.SharedPreferences
import com.tanjiajun.androidgenericframework.utils.int
import com.tanjiajun.androidgenericframework.utils.string
import com.tencent.mmkv.MMKV
/**
* Created by TanJiaJun on 2019-08-08.
*/
class UserDao(
val mmkv: MMKV
) {
var accessToken by mmkv.string("user_access_token", "")
var userId by mmkv.int("user_id", -1)
var username by mmkv.string("username", "")
var password by mmkv.string("password", "")
var name by mmkv.string("name", "")
var avatarUrl by mmkv.string("avatar_url", "")
private fun SharedPreferences.edit(function: SharedPreferences.Editor.() -> Unit) =
edit().also {
function(it)
it.apply()
}
fun clearUserInfoCache() =
with(mmkv) {
removeValuesForKeys(arrayOf(
"user_access_token",
"user_id",
"username",
"password",
"name",
"avatar_url"
))
}
fun cacheUserId(userId: Int) {
this.userId = userId
}
fun cacheUsername(username: String) {
this.username = username
}
fun cachePassword(password: String) {
this.password = <PASSWORD>
}
fun cacheName(name: String) {
this.name = name
}
fun cacheAvatarUrl(avatarUrl: String) {
this.avatarUrl = avatarUrl
}
} | 0 | null | 0 | 1 | 77f28d7e989dea91afae3f2278fde4325769579e | 1,554 | AndroidGenericFramework | Apache License 2.0 |
backend/src/test/kotlin/com/github/davinkevin/podcastserver/manager/downloader/FfmpegDownloaderTest.kt | davinkevin | 13,350,152 | false | {"HTML": 13847656, "Kotlin": 1179034, "TypeScript": 162710, "JavaScript": 96744, "Java": 22047, "Less": 21773, "SCSS": 5172, "Shell": 2799, "Dockerfile": 2639} | package com.github.davinkevin.podcastserver.manager.downloader
import com.github.davinkevin.podcastserver.download.DownloadRepository
import com.github.davinkevin.podcastserver.download.ItemDownloadManager
import com.github.davinkevin.podcastserver.entity.Status
import com.github.davinkevin.podcastserver.entity.Status.*
import com.github.davinkevin.podcastserver.messaging.MessagingTemplate
import com.github.davinkevin.podcastserver.service.ffmpeg.FfmpegService
import com.github.davinkevin.podcastserver.service.ProcessService
import com.github.davinkevin.podcastserver.service.properties.PodcastServerParameters
import com.github.davinkevin.podcastserver.service.storage.FileMetaData
import com.github.davinkevin.podcastserver.service.storage.FileStorageService
import net.bramp.ffmpeg.builder.FFmpegBuilder
import net.bramp.ffmpeg.progress.Progress
import net.bramp.ffmpeg.progress.ProgressListener
import org.assertj.core.api.Assertions.assertThat
import org.awaitility.Awaitility.await
import org.junit.jupiter.api.*
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import org.mockito.Mock
import org.mockito.Spy
import org.mockito.invocation.InvocationOnMock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.*
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.toMono
import software.amazon.awssdk.services.s3.model.PutObjectResponse
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import java.time.Clock
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.util.*
import java.util.concurrent.TimeUnit.SECONDS
import kotlin.io.path.Path
private val fixedDate = OffsetDateTime.of(2019, 3, 4, 5, 6, 7, 0, ZoneOffset.UTC)
/**
* Created by kevin on 20/02/2016 for Podcast Server
*/
@ExtendWith(MockitoExtension::class)
class FfmpegDownloaderTest {
private val item: DownloadingItem = DownloadingItem (
id = UUID.randomUUID(),
title = "Title",
status = Status.NOT_DOWNLOADED,
url = URI("http://a.fake.url/with/file.mp4?param=1"),
numberOfFail = 0,
progression = 0,
podcast = DownloadingItem.Podcast(
id = UUID.randomUUID(),
title = "A Fake ffmpeg Podcast"
),
cover = DownloadingItem.Cover(
id = UUID.randomUUID(),
url = URI("https://bar/foo/cover.jpg")
)
)
@Nested
inner class DownloaderTest {
@Mock lateinit var downloadRepository: DownloadRepository
@Mock lateinit var podcastServerParameters: PodcastServerParameters
@Mock lateinit var template: MessagingTemplate
@Mock lateinit var file: FileStorageService
@Mock lateinit var itemDownloadManager: ItemDownloadManager
@Mock lateinit var ffmpegService: FfmpegService
@Mock lateinit var processService: ProcessService
@Spy val clock: Clock = Clock.fixed(fixedDate.toInstant(), ZoneId.of("UTC"))
lateinit var downloader: FfmpegDownloader
@BeforeEach
fun beforeEach() {
downloader = FfmpegDownloader(downloadRepository, template, clock, file, ffmpegService, processService)
downloader
.with(DownloadingInformation(item, listOf(item.url, URI.create("http://foo.bar.com/end.mp4")), Path("file.mp4"), "Fake UserAgent"), itemDownloadManager)
}
@Nested
inner class DownloadOperation {
@BeforeEach
fun beforeEach() {
whenever(downloadRepository.updateDownloadItem(any())).thenReturn(Mono.empty())
}
@Test
fun should_download_file() {
/* Given */
whenever(ffmpegService.getDurationOf(any(), any())).thenReturn(500.0)
whenever(ffmpegService.download(any(), any(), any())).then { i ->
writeEmptyFileTo(outputPath(i))
(0..100).map { it * 5L }.forEach { sendProgress(i, it)}
mock<Process>()
}
whenever(processService.waitFor(any())).thenReturn(Result.success(1))
doAnswer { writeEmptyFileTo(it.getArgument<Path>(0).toString()); null
}.whenever(ffmpegService).concat(any(), anyVararg())
whenever(file.upload(eq(item.podcast.title), any()))
.thenReturn(PutObjectResponse.builder().build().toMono())
whenever(file.metadata(eq(item.podcast.title), any()))
.thenReturn(FileMetaData("video/mp4", 123L).toMono())
whenever(downloadRepository.finishDownload(
id = item.id,
length = 123L,
mimeType = "video/mp4",
fileName = Path("file-${item.id}.mp4"),
downloadDate = fixedDate
)).thenReturn(Mono.empty())
/* When */
downloader.run()
/* Then */
assertThat(downloader.downloadingInformation.item.status).isEqualTo(FINISH)
assertThat(downloader.downloadingInformation.item.progression).isEqualTo(100)
}
@Test
fun `should ends on FAILED if one of download failed`() {
/* Given */
whenever(ffmpegService.getDurationOf(any(), any())).thenReturn(500.0)
doAnswer { i -> writeEmptyFileTo(outputPath(i))
(0..100).map { it * 5L }.forEach { sendProgress(i, it)}
mock<Process>()
}.whenever(ffmpegService).download(eq(item.url.toASCIIString()), any(), any())
doAnswer { throw RuntimeException("Error during download of other url") }
.whenever(ffmpegService).download(eq("http://foo.bar.com/end.mp4"), any(), any())
whenever(processService.waitFor(any())).thenReturn(Result.success(1))
/* When */
downloader.run()
/* Then */
assertThat(downloader.downloadingInformation.item.status).isSameAs(FAILED)
}
@Test
@Disabled("to check that, we need to extract the temp file generation")
fun `should delete all files if error occurred during download`() {
/* Given */
whenever(ffmpegService.getDurationOf(any(), any())).thenReturn(500.0)
doAnswer { i -> writeEmptyFileTo(outputPath(i))
(0..100).map { it * 5L }.forEach { sendProgress(i, it)}
mock<Process>()
}
.whenever(ffmpegService).download(eq(item.url.toASCIIString()), any(), any())
doAnswer { throw RuntimeException("Error during download of other url") }
.whenever(ffmpegService).download(eq("http://foo.bar.com/end.mp4"), any(), any())
whenever(processService.waitFor(any())).thenReturn(Result.success(1))
/* When */
downloader.run()
/* Then */
}
@Test
@Disabled("to check that, we need to extract the temp file generation")
fun `should delete all files if error occurred during concat`() {
/* Given */
whenever(ffmpegService.getDurationOf(any(), any())).thenReturn(500.0)
doAnswer { i -> writeEmptyFileTo(outputPath(i))
(0..100).map { it * 5L }.forEach { sendProgress(i, it)}
mock<Process>()
}
.whenever(ffmpegService).download(any(), any(), any())
whenever(processService.waitFor(any())).thenReturn(Result.success(1))
whenever(ffmpegService.concat(any(), anyVararg())).then {
throw RuntimeException("Error during concat operation")
}
/* When */
downloader.run()
/* Then */
}
private fun outputPath(i: InvocationOnMock) = i.getArgument<FFmpegBuilder>(1).build().last()!!
private fun sendProgress(i: InvocationOnMock, outTimeMs: Long) =
i.getArgument<ProgressListener>(2).progress(Progress().apply { out_time_ns = outTimeMs })
private fun writeEmptyFileTo(location: String): Path =
Files.write(Paths.get(location), "".toByteArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)
private fun numberOfChildrenFiles(location: Path) = Files
.newDirectoryStream(location)
.map { it }
.size
}
@Nested
inner class DuringDownloadOperation {
@Test
fun should_stop_a_download() {
/* Given */
downloader.downloadingInformation = downloader.downloadingInformation.status(STARTED)
downloader.process = mock()
whenever(downloadRepository.updateDownloadItem(any())).thenReturn(Mono.empty())
/* When */
downloader.stopDownload()
/* Then */
await().atMost(5, SECONDS).untilAsserted {
assertThat(downloader.downloadingInformation.item.status).isEqualTo(STOPPED)
verify(downloader.process).destroy()
}
}
@Test
fun should_failed_to_stop_a_download() {
/* Given */
downloader.downloadingInformation = downloader.downloadingInformation.status(STARTED)
downloader.process = mock()
doAnswer { throw RuntimeException("Error when executing process") }
.whenever(downloader.process).destroy()
whenever(downloadRepository.updateDownloadItem(any())).thenReturn(Mono.empty())
/* When */
downloader.stopDownload()
/* Then */
await().atMost(5, SECONDS).untilAsserted {
assertThat(downloader.downloadingInformation.item.status).isEqualTo(FAILED)
}
}
}
}
@Nested
inner class CompatibilityTest {
@Mock lateinit var downloadRepository: DownloadRepository
@Mock lateinit var podcastServerParameters: PodcastServerParameters
@Mock lateinit var template: MessagingTemplate
@Mock lateinit var file: FileStorageService
@Mock lateinit var itemDownloadManager: ItemDownloadManager
@Mock lateinit var ffmpegService: FfmpegService
@Mock lateinit var processService: ProcessService
@Spy val clock: Clock = Clock.fixed(fixedDate.toInstant(), ZoneId.of("UTC"))
lateinit var downloader: FfmpegDownloader
@BeforeEach
fun beforeEach() {
downloader = FfmpegDownloader(
downloadRepository,
template,
clock,
file,
ffmpegService,
processService
)
}
@Test
fun `should be compatible with multiple urls ending with M3U8 and MP4`() {
/* Given */
val di = DownloadingInformation(item, listOf("http://foo.bar.com/end.M3U8", "http://foo.bar.com/end.mp4").map(URI::create), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(10)
}
@Test
fun `should be compatible with only urls ending with M3U8`() {
/* Given */
val di = DownloadingInformation(item, listOf("http://foo.bar.com/end.m3u8", "http://foo.bar.com/end.M3U8").map(URI::create), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(10)
}
@Test
fun `should be compatible with only urls ending with mp4`() {
/* Given */
val di = DownloadingInformation(item, listOf("http://foo.bar.com/end.MP4", "http://foo.bar.com/end.mp4").map(URI::create), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(10)
}
@DisplayName("should be compatible with only one url with extension")
@ParameterizedTest(name = "{arguments}")
@ValueSource(strings = ["m3u8", "mp4"])
fun `should be compatible with only one url with extension`(ext: String) {
/* Given */
val di = DownloadingInformation(item, listOf(URI.create("http://foo.bar.com/end.$ext")), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(10)
}
@DisplayName("should not be compatible with")
@ParameterizedTest(name = "{arguments}")
@ValueSource(strings = ["http://foo.bar.com/end.webm", "http://foo.bar.com/end.manifest"])
fun `should not be compatible with`(url: String) {
/* Given */
val di = DownloadingInformation(item, listOf(URI.create(url)), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(Integer.MAX_VALUE)
}
}
}
| 0 | HTML | 43 | 183 | 35cbef91622d71262852a0a0683f339f6571a8c8 | 13,932 | Podcast-Server | Apache License 2.0 |
library/src/main/java/com/trifork/timencryptedstorage/shared/extensions/TIMKeyModelExtensions.kt | trifork | 399,111,594 | false | null | package com.trifork.timencryptedstorage.shared.extensions
import android.util.Base64
import com.trifork.timencryptedstorage.models.TIMESEncryptionMethod
import com.trifork.timencryptedstorage.models.TIMResult
import com.trifork.timencryptedstorage.models.errors.TIMEncryptedStorageError
import com.trifork.timencryptedstorage.models.keyservice.response.TIMKeyModel
import com.trifork.timencryptedstorage.models.toTIMFailure
import com.trifork.timencryptedstorage.models.toTIMSuccess
import com.trifork.timencryptedstorage.shared.CipherConstants
import com.trifork.timencryptedstorage.shared.GCMCipherHelper
import java.security.Key
import javax.crypto.spec.SecretKeySpec
fun TIMKeyModel.encrypt(data: ByteArray, encryptionMethod: TIMESEncryptionMethod): TIMResult<ByteArray, TIMEncryptedStorageError> {
return try {
val secretKeyResult = getAesKey()
when (encryptionMethod) {
TIMESEncryptionMethod.AesGcm -> GCMCipherHelper.encrypt(
secretKeyResult,
data
).toTIMSuccess()
}
} catch (e: Throwable) {
TIMEncryptedStorageError.FailedToEncryptData(e).toTIMFailure()
}
}
fun TIMKeyModel.decrypt(data: ByteArray, encryptionMethod: TIMESEncryptionMethod): TIMResult<ByteArray, TIMEncryptedStorageError> {
return try {
val secretKeyResult = getAesKey()
when (encryptionMethod) {
TIMESEncryptionMethod.AesGcm -> GCMCipherHelper.decrypt(
secretKeyResult,
data
).toTIMSuccess()
}
} catch (e: Exception) {
TIMEncryptedStorageError.FailedToDecryptData(e).toTIMFailure()
}
}
@Throws(IllegalArgumentException::class, IllegalArgumentException::class)
internal fun TIMKeyModel.getAesKey(): Key {
val decodedKey = Base64.decode(key, Base64.DEFAULT)
return SecretKeySpec(decodedKey, CipherConstants.cipherAlgorithm)
} | 0 | Kotlin | 1 | 2 | 537ff553eeceab824d5ff6b7bda9395f0d78639f | 1,911 | TIMEncryptedStorage-Android | MIT License |
adshelper/src/main/java/com/example/app/adshelper/NativeAdvancedModelHelper.kt | vickypathak123 | 423,788,882 | false | {"Java": 486597, "Kotlin": 215177, "Assembly": 5} | package com.example.app.adshelper
import android.annotation.SuppressLint
import android.content.Context
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.*
import androidx.annotation.NonNull
import androidx.constraintlayout.widget.ConstraintLayout
import com.example.app.adshelper.widgets.BlurDrawable
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdView
/**
* @author <NAME>
* @since 24 Nov 2021
*
* NativeAdvancedModel.kt - Simple class which has load and handle your multiple size Native Advanced AD data
* @param mContext this is a reference to your activity or fragment context
*/
class NativeAdvancedModelHelper(private val mContext: Context) : AdMobAdsListener {
private val TAG = "Admob_" + javaClass.simpleName
companion object {
val getNativeAd: NativeAd?
get() {
return NativeAdvancedHelper.mNativeAd
}
fun destroy() {
NativeAdvancedHelper.destroy()
}
}
private var mCloseTimer: AdsCloseTimer? = null
private var isAdClicked: Boolean = false
private var isAdOwnerPause: Boolean = false
private var mSize: NativeAdsSize = NativeAdsSize.Medium
private var mLayout: FrameLayout = FrameLayout(mContext)
private var mIsNeedLayoutShow: Boolean = true
private var mIsAddVideoOptions: Boolean = false
private var mIsAdLoaded: (isNeedToRemoveCloseButton: Boolean) -> Unit = {}
private var mOnClickAdClose: () -> Unit = {}
/**
* Call this method when you need to load your Native Advanced AD
* you need to call this method only once in any activity or fragment
*
* this method will load your Native Advanced AD with 4 different size like [NativeAdsSize.Medium], [NativeAdsSize.Big], [NativeAdsSize.FullScreen]
* for Native Advanced AD Size @see [NativeAdsSize] once
*
* @param fSize it indicate your Ad Size
* @param fLayout FrameLayout for add NativeAd View
* @param isNeedLayoutShow [by Default value = true] pass false if you do not need to show AD at a time when it's loaded successfully
* @param isAddVideoOptions [by Default value = false] pass true if you need to add video option
* @param isAdLoaded lambda function call when ad isLoaded
* @param onClickAdClose lambda function call when user click close button of ad
*/
fun loadNativeAdvancedAd(
@NonNull fSize: NativeAdsSize,
@NonNull fLayout: FrameLayout,
isNeedLayoutShow: Boolean = true,
isAddVideoOptions: Boolean = false,
isAdLoaded: (isNeedToRemoveCloseButton: Boolean) -> Unit = {},
onClickAdClose: () -> Unit = {}
) {
Log.i(TAG, "loadAd: ")
mSize = fSize
mLayout = fLayout
mIsNeedLayoutShow = isNeedLayoutShow
mIsAddVideoOptions = isAddVideoOptions
mIsAdLoaded = isAdLoaded
mOnClickAdClose = onClickAdClose
mCloseTimer?.cancel()
mCloseTimer = AdsCloseTimer(
millisInFuture = 3000,
countDownInterval = 1000,
onFinish = {
onClickAdClose.invoke()
}
)
mCloseTimer?.start()
NativeAdvancedHelper.loadNativeAdvancedAd(
fContext = mContext,
isAddVideoOptions = isAddVideoOptions,
fListener = this,
)
}
@SuppressLint("InflateParams")
private fun loadAdWithPerfectLayout(
@NonNull fSize: NativeAdsSize,
@NonNull fLayout: FrameLayout,
@NonNull nativeAd: NativeAd,
isNeedLayoutShow: Boolean = true,
isAdLoaded: (isNeedToRemoveCloseButton: Boolean) -> Unit = {},
onClickAdClose: () -> Unit
) {
mCloseTimer?.cancel()
val adView = when (fSize) {
NativeAdsSize.Big -> {
mContext.inflater.inflate(
R.layout.layout_google_native_ad_big,
null
) as NativeAdView
}
NativeAdsSize.Medium -> {
mContext.inflater.inflate(
R.layout.layout_google_native_ad_medium,
null
) as NativeAdView
}
NativeAdsSize.FullScreen -> {
if (nativeAd.starRating != null && nativeAd.price != null && nativeAd.store != null) {
mContext.inflater.inflate(
R.layout.layout_google_native_ad_exit_full_screen_app_store,
null
) as ConstraintLayout
} else {
mContext.inflater.inflate(
R.layout.layout_google_native_ad_exit_full_screen_website,
null
) as NativeAdView
}
}
}
when (fSize) {
NativeAdsSize.FullScreen -> {
populateFullScreenNativeAdView(
nativeAd,
adView.findViewById(R.id.native_ad_view),
onClickAdClose
)
}
else -> {
populateNativeAdView(nativeAd, adView as NativeAdView)
}
}
fLayout.removeAllViews()
fLayout.addView(adView)
if (isNeedLayoutShow) {
fLayout.visibility = View.VISIBLE
if (fSize == NativeAdsSize.FullScreen && nativeAd.starRating != null && nativeAd.price != null && nativeAd.store != null) {
isAdLoaded.invoke(true)
} else {
isAdLoaded.invoke(false)
}
} else {
fLayout.visibility = View.GONE
}
}
private fun populateFullScreenNativeAdView(
nativeAd: NativeAd,
adView: NativeAdView,
onClickAdClose: () -> Unit
) {
adView.headlineView = adView.findViewById(R.id.ad_headline)
adView.mediaView = adView.findViewById(R.id.ad_media)
adView.imageView = adView.findViewById(R.id.iv_bg_main_image)
adView.bodyView = adView.findViewById(R.id.ad_body)
adView.iconView = adView.findViewById(R.id.ad_app_icon)
adView.starRatingView = adView.findViewById(R.id.ad_stars)
adView.storeView = adView.findViewById(R.id.ad_store)
adView.priceView = adView.findViewById(R.id.ad_price)
adView.advertiserView = adView.findViewById(R.id.ad_advertiser)
adView.callToActionView = adView.findViewById(R.id.ad_call_to_action)
(adView.headlineView as TextView).text = nativeAd.headline
if (nativeAd.mediaContent != null && adView.mediaView != null) {
nativeAd.mediaContent?.let { mediaContent ->
adView.mediaView?.setMediaContent(mediaContent)
}
} else {
populateFullScreenNativeAdView(getNativeAd!!, adView, onClickAdClose)
}
if (nativeAd.images.size > 0) {
if (nativeAd.images[0] != null && adView.imageView != null) {
(adView.imageView as ImageView).setImageDrawable(nativeAd.images[0].drawable!!)
val blurView: View = adView.findViewById(R.id.blur_view)
val blurDrawable = BlurDrawable(adView.imageView, 15)
blurView.background = blurDrawable
}
}
if (nativeAd.body == null && adView.bodyView != null) {
adView.bodyView?.visibility = View.GONE
} else if (adView.bodyView != null) {
adView.bodyView?.visibility = View.VISIBLE
(adView.bodyView as TextView).text = nativeAd.body
}
if (nativeAd.icon == null && adView.iconView != null) {
adView.iconView?.visibility = View.GONE
} else if (adView.iconView != null) {
(adView.iconView as ImageView).setImageDrawable(
nativeAd.icon?.drawable
)
adView.iconView?.visibility = View.VISIBLE
}
if (nativeAd.starRating == null && adView.starRatingView != null) {
adView.starRatingView?.visibility = View.GONE
(adView.findViewById(R.id.txt_rating) as TextView?)?.visibility = View.GONE
} else if (adView.starRatingView != null) {
(adView.findViewById(R.id.txt_rating) as TextView?)?.text =
nativeAd.starRating!!.toFloat().toString()
(adView.starRatingView as RatingBar).rating = nativeAd.starRating!!.toFloat()
adView.starRatingView?.visibility = View.VISIBLE
(adView.findViewById(R.id.txt_rating) as TextView?)?.visibility = View.VISIBLE
}
if (nativeAd.callToAction == null && adView.callToActionView != null) {
adView.callToActionView?.visibility = View.GONE
} else if (adView.callToActionView != null) {
adView.callToActionView?.visibility = View.VISIBLE
(adView.callToActionView as Button).isSelected = true
nativeAd.callToAction?.let {
(adView.callToActionView as Button).text = getCamelCaseString(it)
}
}
if (nativeAd.store == null && adView.storeView != null) {
adView.storeView?.visibility = View.GONE
} else if (adView.storeView != null) {
(adView.storeView as TextView).isSelected = true
adView.storeView?.visibility = View.VISIBLE
nativeAd.store?.let {
(adView.storeView as TextView).text = it
if (it.equals("Google Play", false)) {
(adView.findViewById(R.id.iv_play_logo) as View?)?.visibility = View.VISIBLE
} else {
(adView.findViewById(R.id.iv_play_logo) as View?)?.visibility = View.GONE
}
}
}
if (nativeAd.price == null && adView.priceView != null) {
adView.priceView?.visibility = View.GONE
} else if (adView.priceView != null) {
adView.priceView?.visibility = View.VISIBLE
(adView.priceView as TextView).text = nativeAd.price
}
if (nativeAd.advertiser == null && adView.advertiserView != null) {
adView.advertiserView?.visibility = View.GONE
} else if (adView.advertiserView != null) {
adView.advertiserView?.visibility = View.VISIBLE
(adView.advertiserView as TextView).text = nativeAd.advertiser
}
if (adView.storeView?.visibility == View.GONE && adView.priceView?.visibility == View.GONE) {
(adView.findViewById(R.id.cl_ad_price_store) as View?)?.visibility = View.GONE
}
(adView.findViewById(R.id.ad_call_to_close) as Button?)?.let {
it.setOnClickListener {
onClickAdClose.invoke()
}
}
adView.setNativeAd(nativeAd)
}
private fun populateNativeAdView(nativeAd: NativeAd, adView: NativeAdView) {
Log.i(TAG, Throwable().stackTrace[0].methodName)
adView.mediaView = adView.findViewById(R.id.ad_media)
adView.headlineView = adView.findViewById(R.id.ad_headline)
adView.bodyView = adView.findViewById(R.id.ad_body)
adView.callToActionView = adView.findViewById(R.id.ad_call_to_action)
adView.iconView = adView.findViewById(R.id.ad_app_icon)
adView.priceView = adView.findViewById(R.id.ad_price)
adView.starRatingView = adView.findViewById(R.id.ad_stars)
adView.storeView = adView.findViewById(R.id.ad_store)
adView.advertiserView = adView.findViewById(R.id.ad_advertiser)
(adView.headlineView as TextView).text = nativeAd.headline
if (nativeAd.mediaContent != null) {
if (adView.mediaView != null) {
adView.mediaView!!.setMediaContent(nativeAd.mediaContent!!)
}
} else {
populateNativeAdView(getNativeAd!!, adView)
}
if (nativeAd.body == null && adView.bodyView != null) {
adView.bodyView!!.visibility = View.GONE
} else if (adView.bodyView != null) {
adView.bodyView!!.visibility = View.VISIBLE
(adView.bodyView as TextView).text = nativeAd.body
}
if (nativeAd.callToAction == null && adView.callToActionView != null) {
adView.callToActionView!!.visibility = View.INVISIBLE
} else if (adView.callToActionView != null) {
adView.callToActionView!!.visibility = View.VISIBLE
(adView.callToActionView as Button).text = nativeAd.callToAction
}
if (nativeAd.icon != null && adView.iconView != null) {
(adView.iconView as ImageView).setImageDrawable(
nativeAd.icon!!.drawable
)
adView.iconView!!.visibility = View.VISIBLE
} else if (adView.iconView != null) {
if (nativeAd.images.size > 0) {
if (nativeAd.images[0] != null && nativeAd.images[0].drawable != null) {
(adView.iconView as ImageView).setImageDrawable(nativeAd.images[0].drawable!!)
adView.iconView!!.visibility = View.VISIBLE
} else {
adView.iconView!!.visibility = View.GONE
}
} else {
adView.iconView!!.visibility = View.GONE
}
} else {
adView.iconView!!.visibility = View.GONE
}
if (nativeAd.price == null && adView.priceView != null) {
adView.priceView!!.visibility = View.INVISIBLE
} else if (adView.priceView != null) {
adView.priceView!!.visibility = View.VISIBLE
(adView.priceView as TextView).text = nativeAd.price
}
if (nativeAd.store == null && adView.storeView != null) {
adView.storeView!!.visibility = View.INVISIBLE
} else if (adView.storeView != null) {
adView.storeView!!.visibility = View.VISIBLE
(adView.storeView as TextView).text = nativeAd.store
}
if (adView.priceView != null) {
adView.priceView!!.visibility = View.GONE
}
if (adView.storeView != null) {
adView.storeView!!.visibility = View.GONE
}
if (nativeAd.starRating == null && adView.starRatingView != null) {
adView.starRatingView!!.visibility = View.GONE
} else if (adView.starRatingView != null) {
(adView.starRatingView as RatingBar).rating = nativeAd.starRating!!.toFloat()
adView.starRatingView!!.visibility = View.VISIBLE
}
if (nativeAd.advertiser == null && adView.advertiserView != null) {
adView.advertiserView!!.visibility = View.GONE
} else if (adView.advertiserView != null) {
(adView.advertiserView as TextView).text = nativeAd.advertiser
adView.advertiserView!!.visibility = View.VISIBLE
}
adView.setNativeAd(nativeAd)
}
private fun getCamelCaseString(text: String): String {
val words: Array<String> = text.split(" ").toTypedArray()
val builder = StringBuilder()
for (i in words.indices) {
var word: String = words[i]
word = if (word.isEmpty()) word else Character.toUpperCase(word[0])
.toString() + word.substring(1).lowercase()
builder.append(word)
if (i != (words.size - 1)) {
builder.append(" ")
}
}
return builder.toString()
}
override fun onAdClosed(isShowFullScreenAd: Boolean) {
super.onAdClosed(isShowFullScreenAd)
Log.i(TAG, "onAdClosed: ")
isAdClicked = true
if (!isAdOwnerPause) {
mLayout.removeAllViews()
loadNativeAdvancedAd(
fSize = mSize,
fLayout = mLayout,
isNeedLayoutShow = mIsNeedLayoutShow,
isAddVideoOptions = mIsAddVideoOptions,
isAdLoaded = mIsAdLoaded,
onClickAdClose = mOnClickAdClose
)
}
}
override fun onNativeAdLoaded(nativeAd: NativeAd) {
super.onNativeAdLoaded(nativeAd)
isAdClicked = false
loadAdWithPerfectLayout(
fSize = mSize,
fLayout = mLayout,
nativeAd = nativeAd,
isNeedLayoutShow = mIsNeedLayoutShow,
isAdLoaded = mIsAdLoaded,
onClickAdClose = mOnClickAdClose
)
}
inner class AdsCloseTimer(
private val millisInFuture: Long,
countDownInterval: Long,
private val onFinish: () -> Unit
) : CountDownTimer(millisInFuture, countDownInterval) {
override fun onTick(millisUntilFinished: Long) {
Log.e(TAG, "onTick: Time::${(((millisInFuture - millisUntilFinished) / 1000) + 1)}")
}
override fun onFinish() {
onFinish.invoke()
}
}
} | 0 | Java | 1 | 0 | aa966b83f6dca0aa08261b8810a778e40d909d4b | 17,004 | AndroidAppCenter | MIT License |
compiler/testData/diagnostics/tests/multiplatform/topLevelFun/simpleHeaderFun.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// MODULE: m1-common
// FILE: common.kt
expect fun foo()
// MODULE: m2-jvm()()(m1-common)
// FILE: jvm.kt
actual fun foo() {}
// MODULE: m3-js()()(m1-common)
// FILE: js.kt
actual fun foo() {}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 212 | kotlin | Apache License 2.0 |
nitrozen-android-lib/src/main/java/com/fynd/nitrozen/components/selector/NitrozenSelector.kt | gofynd | 238,860,720 | false | null | package com.fynd.nitrozen.components.selector
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.fynd.nitrozen.theme.NitrozenTheme
import com.fynd.nitrozen.R
import com.fynd.nitrozen.utils.DisplayMetrics
@Preview
@Composable
fun NitrozenSelector_Text() {
val selectedItemIndex = remember {
mutableStateOf(2)
}
NitrozenTheme {
NitrozenSelector(
items = listOf(
NitrozenSelectorItem.Text("Item 1"),
NitrozenSelectorItem.Text("Item 2"),
NitrozenSelectorItem.Text("Item 3"),
),
selectedItemIndex = selectedItemIndex.value,
onItemClick = {
selectedItemIndex.value = it
},
modifier = Modifier.width(300.dp)
)
}
}
@Preview
@Composable
fun NitrozenSelector_Icon() {
val selectedItemIndex = remember {
mutableStateOf(0)
}
NitrozenTheme {
NitrozenSelector(
items = listOf(
NitrozenSelectorItem.Icon(R.drawable.ic_chevron_down),
NitrozenSelectorItem.Icon(R.drawable.ic_chevron_down),
NitrozenSelectorItem.Icon(R.drawable.ic_chevron_down),
),
selectedItemIndex = selectedItemIndex.value,
onItemClick = {
selectedItemIndex.value = it
},
modifier = Modifier.fillMaxWidth()
)
}
}
@Preview
@Composable
fun NitrozenSelector_IconText_Horizontal() {
val selectedItemIndex = remember {
mutableStateOf(0)
}
NitrozenTheme {
NitrozenSelector(
items = listOf(
NitrozenSelectorItem.IconText("Item", R.drawable.ic_chevron_down),
NitrozenSelectorItem.IconText("Item", R.drawable.ic_chevron_down),
NitrozenSelectorItem.IconText("Item", R.drawable.ic_chevron_down),
),
selectedItemIndex = selectedItemIndex.value,
onItemClick = {
selectedItemIndex.value = it
},
modifier = Modifier.fillMaxWidth()
)
}
}
@Preview
@Composable
fun NitrozenSelector_IconText_Vertical() {
val selectedItemIndex = remember {
mutableStateOf(0)
}
NitrozenTheme {
NitrozenSelector(
items = listOf(
NitrozenSelectorItem.IconText("Item", R.drawable.ic_chevron_down),
NitrozenSelectorItem.IconText("Item", R.drawable.ic_chevron_down),
NitrozenSelectorItem.IconText("Item", R.drawable.ic_chevron_down),
),
selectedItemIndex = selectedItemIndex.value,
isItemDirectionVertical = true,
onItemClick = {
selectedItemIndex.value = it
},
modifier = Modifier.fillMaxWidth()
)
}
}
@Composable
fun NitrozenSelector(
modifier: Modifier = Modifier,
items: List<NitrozenSelectorItem>,
onItemClick: (index: Int) -> Unit,
selectedItemIndex: Int = 0,
isItemDirectionVertical: Boolean = false,
style: NitrozenSelectorStyle = NitrozenSelectorStyle.Default,
configuration: NitrozenSelectorConfiguration = NitrozenSelectorConfiguration.Default,
) {
Box(
modifier = modifier
.clip(NitrozenTheme.shapes.pill)
.background(
color = style.backgroundColor,
shape = NitrozenTheme.shapes.pill
)
.padding(configuration.contentPadding),
contentAlignment = Alignment.CenterStart
) {
val doAnimate = remember {
mutableStateOf(false)
}
val selectorWidth = remember {
mutableStateOf(0.dp)
}
val selectorHeight = remember {
mutableStateOf(0.dp)
}
val selectorTranslationTarget = remember {
mutableStateOf(0F)
}
val selectorTranslationX = remember {
Animatable(0f)
}
LaunchedEffect(
key1 = selectedItemIndex,
key2 = selectorWidth.value,
key3 = selectorHeight.value,
){
selectorTranslationTarget.value = (selectedItemIndex * DisplayMetrics.convertDpToPixel(selectorWidth.value.value)) +
(selectedItemIndex * DisplayMetrics.convertDpToPixel(configuration.spaceBetweenItems.value))
if(doAnimate.value) {
selectorTranslationX.animateTo(selectorTranslationTarget.value)
}else{
selectorTranslationX.snapTo(selectorTranslationTarget.value)
}
}
Box(
modifier = Modifier
.graphicsLayer(
translationX = if (configuration.allowAnimation)
selectorTranslationX.value
else
selectorTranslationTarget.value
)
.size(width = selectorWidth.value, height = selectorHeight.value)
.background(
color = style.selectedBackgroundColor,
shape = NitrozenTheme.shapes.pill
)
)
Row(
horizontalArrangement = Arrangement.spacedBy(
space = configuration.spaceBetweenItems,
alignment = Alignment.CenterHorizontally
),
) {
items.forEachIndexed { index, item ->
val selected = index == selectedItemIndex
NitrozenSelectorPill(
item = item,
selected = selected,
onClick = {
onItemClick(index)
doAnimate.value = true
},
modifier = Modifier
.weight(1F)
.onSizeChanged {
selectorWidth.value =
DisplayMetrics.convertPixelsToDp(it.width.toFloat()).dp
selectorHeight.value =
DisplayMetrics.convertPixelsToDp(it.height.toFloat()).dp
},
isItemDirectionVertical = isItemDirectionVertical
)
}
}
}
} | 1 | Kotlin | 4 | 5 | 2e0506c5ddd9bd0ebd45814ca1c8fef232db336f | 6,847 | nitrozen-android | MIT License |
fluent-icons-generator/src/jvmMain/kotlin/androidx/compose/material/icons/generator/vector/Vector.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11029508, "Java": 256912} | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.icons.generator.vector
/**
* Simplified representation of a vector, with root [nodes].
*
* [nodes] may either be a singleton list of the root group, or a list of root paths / groups if
* there are multiple top level declaration.
*/
class Vector(val nodes: List<VectorNode>)
/**
* Simplified vector node representation, as the total set of properties we need to care about
* for Material icons is very limited.
*/
sealed class VectorNode {
class Group(val paths: MutableList<Path> = mutableListOf()) : VectorNode()
class Path(
val strokeAlpha: Float,
val fillAlpha: Float,
val fillType: FillType,
val nodes: List<PathNode>
) : VectorNode()
}
| 12 | Kotlin | 16 | 155 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 1,346 | compose-fluent-ui | Apache License 2.0 |
src/main/kotlin/us/timinc/mc/cobblemon/unimplementeditems/items/PostBattleItem.kt | timinc-cobble | 669,249,509 | false | {"Kotlin": 20737, "Java": 1329} | package us.timinc.mc.cobblemon.unimplementeditems.items
import com.cobblemon.mod.common.api.events.battles.BattleVictoryEvent
import com.cobblemon.mod.common.pokemon.Pokemon
import net.minecraft.item.ItemStack
interface PostBattleItem {
fun doPostBattle(itemStack: ItemStack, pokemon: Pokemon, event: BattleVictoryEvent)
} | 8 | Kotlin | 0 | 1 | 18678b071c7620589d6527d5a2cbb0974add939e | 328 | cobblemon-unimplemented-items-1.4-fabric | MIT License |
app/src/main/java/com/example/affirmations/ui/components/DetailComponent.kt | IvanRellanSan | 603,903,090 | false | null | package com.example.affirmations.ui.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Phone
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.affirmations.data.Datasource
import com.example.affirmations.model.Affirmation
import com.example.affirmations.navigation.DetailNavigator
import com.example.affirmations.ui.theme.Typography
@Composable
fun DetailComponent(modifier: Modifier = Modifier, affirmation: Affirmation) {
val context = LocalContext.current
val navigator = DetailNavigator()
Column(
modifier = modifier
.fillMaxHeight()
) {
Image(
painter = painterResource(id = affirmation.imageResourceId),
contentDescription = stringResource(id = affirmation.stringResourceId),
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = 22.dp)
)
Text(text = stringResource(id = affirmation.stringResourceId),
style= Typography.h4,
modifier = Modifier
.align(Alignment.CenterHorizontally)
// .weight(1f)
)
Text(text = stringResource(id = affirmation.descriptionResourceId),
style= Typography.body2,
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(start = 32.dp, end = 32.dp, bottom = 10.dp)
// .weight(1f)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(end = 32.dp, start = 32.dp),
horizontalArrangement = Arrangement.End
){
IconButton(onClick = { navigator.sendEmail(context, affirmation.email, "Hola camarón con cola") }) {
Icon(
imageVector = Icons.Filled.Email,
contentDescription = "Email button"
)
}
IconButton(onClick = { navigator.dial(context, affirmation.phone) }) {
Icon(
imageVector = Icons.Filled.Phone,
contentDescription = "Email button"
)
}
}
}
}
@Preview
@Composable
fun DetailComponentPreview() {
val affirmations = Datasource().loadAffirmations()
DetailComponent(affirmation = affirmations[0])
} | 0 | Kotlin | 0 | 0 | 613b4a253a0fc1f9db65655613729b6c599030cd | 2,943 | ComposeTrainingAffirmations | Apache License 2.0 |
app/src/main/java/com/ancientlore/memento/extensions/AlarmManager.kt | ancientloregames | 141,873,659 | false | null | package com.ancientlore.memento.extensions
import android.app.AlarmManager
import android.app.PendingIntent
import android.os.Build
fun AlarmManager.schedule(type: Int, time: Long, operation: PendingIntent) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
set(type, time, operation)
else
setExact(type, time, operation)
} | 0 | Kotlin | 0 | 0 | 71cf765639d164a6e782183627d705ba7c50a1a2 | 338 | Memento | MIT License |
src/main/kotlin/fp/kotlin/example/chapter05/exercise/5-23-toString.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter05.exercise
import fp.kotlin.example.chapter05.FunList
import fp.kotlin.example.chapter05.funListOf
/**
*
* 연습문제 5-23
*
* FunList에 toString 함수를 추가해보자.
*
* 힌트: 함수의 선언 타입은 아래와 같다.
*
*/
fun main() {
require(funListOf(1, 2, 3, 4, 5).toString("") == "[1, 2, 3, 4, 5]")
}
tailrec fun <T> FunList<T>.toString(acc: String): String = TODO() | 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 436 | fp-kotlin-example | MIT License |
samples/GenerateWrappers.kt | typesafegithub | 647,220,195 | false | null | package expected
import io.github.typesafegithub.workflows.domain.RunnerType
import io.github.typesafegithub.workflows.domain.Workflow
import io.github.typesafegithub.workflows.domain.actions.CustomAction
import io.github.typesafegithub.workflows.domain.triggers.Push
import io.github.typesafegithub.workflows.dsl.expressions.expr
import io.github.typesafegithub.workflows.dsl.workflow
import io.github.typesafegithub.workflows.yaml.toYaml
import io.github.typesafegithub.workflows.yaml.writeToFile
import java.nio.`file`.Paths
import kotlin.collections.listOf
import kotlin.collections.mapOf
public val workflowGeneratewrappers: Workflow = workflow(
name = "Generate wrappers",
on = listOf(
Push(
branchesIgnore = listOf("main"),
),
),
sourceFile = Paths.get(".github/workflows/generatewrappers.main.kts"),
) {
job(
id = "check_yaml_consistency",
name = "Check YAML consistency",
runsOn = RunnerType.UbuntuLatest,
) {
uses(
name = "Check out",
action = CustomAction(
actionOwner = "actions",
actionName = "checkout",
actionVersion = "v3",
inputs = emptyMap()),
)
run(
name = "Install Kotlin",
command = "sudo snap install --classic kotlin",
)
run(
name = "Consistency check",
command =
"diff -u '.github/workflows/generate-wrappers.yaml' <('.github/workflows/generate-wrappers.main.kts')",
)
}
job(
id = "generate-wrappers",
runsOn = RunnerType.UbuntuLatest,
_customArguments = mapOf(
"needs" to listOf("check_yaml_consistency"),
)
) {
uses(
name = "Checkout",
action = CustomAction(
actionOwner = "actions",
actionName = "checkout",
actionVersion = "v3",
inputs = emptyMap()),
)
uses(
name = "Set up JDK",
action = CustomAction(
actionOwner = "actions",
actionName = "setup-java",
actionVersion = "v3",
inputs = mapOf(
"java-version" to "11",
"distribution" to "adopt",
)
),
)
uses(
name = "Generate wrappers",
action = CustomAction(
actionOwner = "gradle",
actionName = "gradle-build-action",
actionVersion = "v1",
inputs = mapOf(
"arguments" to ":wrapper-generator:run",
)
),
)
uses(
name = "Check that the library builds fine with newly generated wrappers",
action = CustomAction(
actionOwner = "gradle",
actionName = "gradle-build-action",
actionVersion = "v2",
inputs = mapOf(
"arguments" to "build",
)
),
)
run(
name = "Commit and push",
command = """
|git config --global user.email "<>"
|git config --global user.name "GitHub Actions Bot"
|git add .
|git commit --allow-empty -m "Regenerate wrappers (${'$'}GITHUB_SHA)" # an empty commit explicitly shows that the wrappers are up-to-date
|git push
|""".trimMargin(),
)
}
} | 8 | Kotlin | 2 | 2 | 54a0e8e9dedd516d76c0e697cb1899f5c90b8c6b | 3,587 | yaml2kotlin | Apache License 2.0 |
app/src/main/java/com/faridrama123/app/data/remote/network/ApiService.kt | faridrama123 | 373,119,158 | false | null | package com.faridrama123.app.data.remote.network
import com.faridrama123.app.data.remote.response.DetailResponse
import com.faridrama123.app.data.remote.response.FollowersResponse
import com.faridrama123.app.data.remote.response.FollowingResponse
import com.faridrama123.app.data.remote.response.SearchResponse
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface ApiService {
@GET("search/users")
fun searchUser (
@Query("q") q : String
): Call <SearchResponse>
@GET("users/{username}")
fun detailUser (
@Path("username") username : String
) :Call<DetailResponse>
@GET("users/{username}/followers")
fun listFollower (
@Path("username") username : String
) : Call<List<FollowersResponse>>
@GET("users/{username}/following")
fun listFollowing (
@Path("username") username : String
) : Call <List<FollowingResponse>>
} | 0 | Kotlin | 0 | 0 | d30ac497ce67f897ee4bab1eef1956dd9144a448 | 964 | GithubAppMVVM | Apache License 2.0 |
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/expressions/impl/IrErrorCallExpressionImpl.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2016 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.ir.expressions.impl
import org.jetbrains.kotlin.ir.expressions.IrErrorCallExpression
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.visitors.IrElementTransformer
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.utils.SmartList
class IrErrorCallExpressionImpl(
startOffset: Int,
endOffset: Int,
type: IrType,
override val description: String
) :
IrExpressionBase(startOffset, endOffset, type),
IrErrorCallExpression {
override var explicitReceiver: IrExpression? = null
override val arguments: MutableList<IrExpression> = SmartList()
fun addArgument(argument: IrExpression) {
arguments.add(argument)
}
override fun <R, D> accept(visitor: IrElementVisitor<R, D>, data: D): R {
return visitor.visitErrorCallExpression(this, data)
}
override fun <D> acceptChildren(visitor: IrElementVisitor<Unit, D>, data: D) {
explicitReceiver?.accept(visitor, data)
arguments.forEach { it.accept(visitor, data) }
}
override fun <D> transformChildren(transformer: IrElementTransformer<D>, data: D) {
explicitReceiver = explicitReceiver?.transform(transformer, data)
arguments.forEachIndexed { i, irExpression ->
arguments[i] = irExpression.transform(transformer, data)
}
}
} | 34 | Kotlin | 49 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 2,045 | kotlin | Apache License 2.0 |
generator/src/main/kotlin/de/qhun/declaration_provider/generator/typescript/render/TypescriptConstantRenderer.kt | wartoshika | 319,145,505 | false | null | package de.qhun.declaration_provider.generator.typescript.render
import de.qhun.declaration_provider.domain.ConstantDeclaration
import de.qhun.declaration_provider.generator.DeclarationGeneratorOptions
object TypescriptConstantRenderer {
fun ConstantDeclaration.render(options: DeclarationGeneratorOptions, enumContext: Boolean = false, namespaceContext: Boolean = false): List<String> {
val data = mutableListOf(
listOfNotNull(
TypescriptCommentRenderer.renderComment(
listOfNotNull(
documentation?.text,
documentation?.url?.let { "@url $it" },
documentation?.since?.let { "@since ${it.full()}" }
),
options
)
).joinToString(""),
).filter { it.isNotBlank() }.toMutableList()
if (enumContext) {
data.add("$name = ${numberOrString(value)}")
} else {
data.add("${if (namespaceContext) "" else "declare "}const $name = ${numberOrString(value)}")
}
return data
}
private fun numberOrString(value: Any): Any {
return try {
("" + value).toDouble()
value
} catch (e: Throwable) {
"\"$value\""
}
}
}
| 0 | Kotlin | 0 | 0 | bc26206f36ae06bdc9cb3e206b4baa22e8bcaf82 | 1,335 | wow-declaration-provider | MIT License |
src/main/kotlin/com/radhe/grpcdemo/client/CalculatorClient.kt | RadheshyamSingh | 227,973,118 | false | {"Kotlin": 10996, "Shell": 1840} | package com.radhe.grpcdemo.client
import com.proto.calculator.*
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import io.grpc.StatusRuntimeException
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder
import io.grpc.stub.StreamObserver
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
object CalculatorClient {
@JvmStatic
fun main(args: Array<String>) {
println("Welcome to grpc client")
// plain text channel
val channel = ManagedChannelBuilder
.forAddress("localhost", 7777)
.usePlaintext()
.build()
// secure channel
val secureChannel = NettyChannelBuilder
.forAddress("localhost", 7777)
.sslContext(GrpcSslContexts.forClient().trustManager(File("ssl/ca.crt")).build())
.build()
//doUnieryOperation(channel)
//doServerStreaming(channel)
//doClientStreaming(channel)
//doBothSideStreaming(channel)
//doErrorHandling(channel)
//doDeadlineHandling(channel)
// do secure operation
doUnieryOperation(secureChannel)
println("Shutting down channel")
channel.shutdown()
}
private fun doDeadlineHandling(channel: ManagedChannel?) {
val asyncStub = CalculatorServiceGrpc.newBlockingStub(channel)
val req = HeavyTaskRequest.newBuilder().setTask("Long task").build()
try {
val resp = asyncStub.withDeadlineAfter(1, TimeUnit.SECONDS).performHeavyTask(req)
println("Response received is as -> ${resp.status}")
} catch (ex: StatusRuntimeException) {
println("Received exception as -> ")
ex.printStackTrace()
}
}
private fun doErrorHandling(channel: ManagedChannel?) {
val number = -4
val asyncStub = CalculatorServiceGrpc.newBlockingStub(channel)
val request = SquareRootRequest.newBuilder().setNumber(number).build()
try {
val resp = asyncStub.getSquareRoot(request)
val root = resp.sqRoot
println("Sq root for the number $number is $root")
} catch (ex: StatusRuntimeException) {
println("Exception occurred !!")
println("status -> ${ex.status}")
ex.printStackTrace()
}
}
private fun doBothSideStreaming(channel: ManagedChannel) {
println("creating server stub")
val asyncStub = CalculatorServiceGrpc.newStub(channel)
val latch = CountDownLatch(1)
val requestObserver = asyncStub.getSquareNumber(object : StreamObserver<SquareNumberResponse> {
override fun onNext(value: SquareNumberResponse) {
println("Received square is -> ${value.number}")
}
override fun onError(t: Throwable?) {
println("Error received from server")
latch.countDown()
}
override fun onCompleted() {
println("onCompleted received from server")
latch.countDown()
}
})
// send number to get square from server
listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).forEach { num ->
println("Get square of -> $num")
val req = SquareNumberRequest.newBuilder().setNumber(num).build()
requestObserver.onNext(req)
Thread.sleep(1000)
}
// send completed to server
requestObserver.onCompleted()
latch.await(3, TimeUnit.SECONDS)
}
private fun doClientStreaming(channel: ManagedChannel?) {
println("creating server stream stub")
val asyncClient = CalculatorServiceGrpc.newStub(channel)
val latch = CountDownLatch(1)
val requestStreamObserver = asyncClient.getMaximumNumber(object : StreamObserver<MaxNumberResponse> {
override fun onNext(value: MaxNumberResponse) {
println("Received response from server")
println("Maximum number is -> ${value.maxNumber}")
latch.countDown()
}
override fun onError(t: Throwable?) {
latch.countDown()
}
override fun onCompleted() {
latch.countDown()
}
})
listOf<Int>(10, 20, 30, 5, 6, 7, 91, 3, 45).forEach { num ->
val req = MaxNumberRequest.newBuilder().setNumber(num).build()
requestStreamObserver.onNext(req)
Thread.sleep(1000)
}
requestStreamObserver.onCompleted()
latch.await(3, TimeUnit.SECONDS)
}
private fun doServerStreaming(channel: ManagedChannel) {
println("creating server stream stub")
val asyncClient = CalculatorServiceGrpc.newBlockingStub(channel)
val primeNumRequest = PrimeNumberRequest.newBuilder()
.setStartNumber(1)
.setEndNumber(20)
.build()
val itr = asyncClient.getPrimeNumberStream(primeNumRequest)
itr.forEachRemaining { primeNum ->
println("Next prime number is -> $primeNum")
}
}
private fun doUnieryOperation(channel: ManagedChannel) {
println("creating uniery client stub")
val asyncClient = CalculatorServiceGrpc.newBlockingStub(channel)
val sumRequest = SumRequest.newBuilder()
.setFirstNumber(10)
.setSecondNumber(20)
.build()
val sumResponse = asyncClient.getSum(sumRequest)
println("Sum is as :: ${sumResponse.result}")
}
} | 0 | Kotlin | 0 | 0 | 217971aa53c26e7ce7c07aca78efcff4ad11646f | 5,681 | gRPCExample | Apache License 2.0 |
app/src/main/java/ro/alexmamo/firemag/domain/model/Product.kt | alexmamo | 569,800,514 | false | {"Kotlin": 150879} | package ro.alexmamo.firemag.domain.model
import com.google.firebase.firestore.ServerTimestamp
import java.util.*
data class Product (
val brand: String? = null,
@ServerTimestamp
val creationDate: Date? = null,
val favorites: List<String>? = null,
val id: String? = null,
val image: String? = null,
val name: String? = null,
val popular: Boolean? = null,
val price: Int? = null,
val thumb: String? = null
)
fun Product.toShoppingCartItem() = ShoppingCartItem(
id = id,
name = name,
price = price,
quantity = 1,
thumb = thumb
) | 0 | Kotlin | 4 | 20 | d648c129c9d9f0841b898b6c178170e404f35024 | 589 | FireMag | Apache License 2.0 |
kotlin-native/build-tools/src/main/kotlin/org/jetbrains/kotlin/EndorsedLibraryInfo.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | package org.jetbrains.kotlin
import org.gradle.api.Project
@OptIn(ExperimentalStdlibApi::class)
data class EndorsedLibraryInfo(val project: Project, val name: String) {
val projectName: String
get() = project.name
val taskName: String by lazy {
projectName.split('.').joinToString(separator = "") { name -> name.replaceFirstChar { it.uppercase() } }
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 385 | kotlin | Apache License 2.0 |
subprojects/analysis-kotlin-descriptors/ide/src/main/kotlin/org/jetbrains/dokka/analysis/kotlin/descriptors/ide/IdeKLibService.kt | vmishenev | 406,989,990 | true | {"Kotlin": 3712559, "CSS": 63401, "JavaScript": 33594, "TypeScript": 13611, "HTML": 6976, "FreeMarker": 4120, "Java": 3923, "SCSS": 2794, "Shell": 970} | /*
* Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.dokka.analysis.kotlin.descriptors.ide
import org.jetbrains.dokka.analysis.kotlin.descriptors.compiler.KLibService
import org.jetbrains.kotlin.library.metadata.KlibMetadataModuleDescriptorFactory
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.idea.klib.CachingIdeKlibMetadataLoader
import org.jetbrains.kotlin.idea.klib.compatibilityInfo
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.resolve.CompilerDeserializationConfiguration
import org.jetbrains.kotlin.storage.StorageManager
internal class IdeKLibService : KLibService {
override fun KotlinLibrary.createPackageFragmentProvider(
storageManager: StorageManager,
metadataModuleDescriptorFactory: KlibMetadataModuleDescriptorFactory,
languageVersionSettings: LanguageVersionSettings,
moduleDescriptor: ModuleDescriptor,
lookupTracker: LookupTracker,
): PackageFragmentProvider? {
return this.createKlibPackageFragmentProvider(
storageManager, metadataModuleDescriptorFactory, languageVersionSettings, moduleDescriptor, lookupTracker
)
}
override fun isAnalysisCompatible(kotlinLibrary: KotlinLibrary): Boolean {
return kotlinLibrary.compatibilityInfo.isCompatible
}
}
internal fun KotlinLibrary.createKlibPackageFragmentProvider(
storageManager: StorageManager,
metadataModuleDescriptorFactory: KlibMetadataModuleDescriptorFactory,
languageVersionSettings: LanguageVersionSettings,
moduleDescriptor: ModuleDescriptor,
lookupTracker: LookupTracker
): PackageFragmentProvider? {
if (!compatibilityInfo.isCompatible) return null
val packageFragmentNames = CachingIdeKlibMetadataLoader.loadModuleHeader(this).packageFragmentNameList
return metadataModuleDescriptorFactory.createPackageFragmentProvider(
library = this,
packageAccessHandler = CachingIdeKlibMetadataLoader,
packageFragmentNames = packageFragmentNames,
storageManager = storageManager,
moduleDescriptor = moduleDescriptor,
configuration = CompilerDeserializationConfiguration(languageVersionSettings),
compositePackageFragmentAddend = null,
lookupTracker = lookupTracker
)
}
| 1 | Kotlin | 1 | 0 | a1c3b89871a3a4f90d6441db356685d48a84ab63 | 2,579 | dokka | Apache License 2.0 |
src/commonMain/kotlin/dev/misasi/giancarlo/events/input/window/ResizeEvent.kt | giancarlo-misasi | 507,497,811 | false | {"Kotlin": 353343, "GLSL": 2848} | package dev.misasi.giancarlo.events.input.window
import dev.misasi.giancarlo.events.Event
import dev.misasi.giancarlo.system.System.Companion.getCurrentTimeMs
import dev.misasi.giancarlo.math.Vector2f
data class ResizeEvent(
override val window: Long,
override val time: Long,
override val absolutePosition: Vector2f,
val size: Vector2f
) : Event {
override val id: Int = Event.getNextId()
companion object {
fun valueOf(window: Long, position: Vector2f, x: Int, y: Int): ResizeEvent {
return ResizeEvent(window, getCurrentTimeMs(), position, Vector2f(x.toFloat(), y.toFloat()))
}
}
} | 0 | Kotlin | 1 | 3 | 3bfb9ab27264a40c69f725cb061ccfdd95fcb3ac | 662 | kotlin-game-engine-lib | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/TextAlignRightRotate270.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11029508, "Java": 256912} |
package com.konyaco.fluent.icons.filled
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Filled.TextAlignRightRotate270: ImageVector
get() {
if (_textAlignRightRotate270 != null) {
return _textAlignRightRotate270!!
}
_textAlignRightRotate270 = fluentIcon(name = "Filled.TextAlignRightRotate270") {
fluentPath {
moveTo(6.0f, 19.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f)
lineTo(5.0f, 3.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 2.0f, 0.0f)
verticalLineToRelative(15.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f)
close()
moveTo(18.0f, 15.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f)
lineTo(17.0f, 3.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, 2.0f, 0.0f)
verticalLineToRelative(11.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f)
close()
moveTo(11.0f, 21.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f)
lineTo(13.0f, 3.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f)
verticalLineToRelative(18.0f)
close()
}
}
return _textAlignRightRotate270!!
}
private var _textAlignRightRotate270: ImageVector? = null
| 4 | Kotlin | 4 | 155 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 1,662 | compose-fluent-ui | Apache License 2.0 |
app/src/unitTest/kotlin/batect/config/includes/GitRepositoryCacheNotificationListenerSpec.kt | batect | 102,647,061 | false | {"Kotlin": 2888008, "Python": 42425, "Shell": 33457, "PowerShell": 8340, "Dockerfile": 3386, "Batchfile": 3234, "Java": 1432, "HTML": 345} | /*
Copyright 2017-2022 <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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.config.includes
import batect.testutils.createForEachTest
import batect.testutils.given
import batect.ui.Console
import batect.ui.OutputStyle
import batect.ui.text.Text
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object GitRepositoryCacheNotificationListenerSpec : Spek({
describe("a Git repository cache notification listener") {
val console by createForEachTest { mock<Console>() }
given("quiet output is not being used") {
val outputStyle = OutputStyle.Simple
val listener by createForEachTest { DefaultGitRepositoryCacheNotificationListener(console, outputStyle) }
describe("when a repository is being cloned") {
val repo = GitRepositoryReference("https://myrepo.com/bundles/bundle.git", "v1.2.3")
beforeEachTest { listener.onCloning(repo) }
it("prints a message to the console") {
verify(console).println(Text.white(Text("Cloning ") + Text.bold("https://myrepo.com/bundles/bundle.git") + Text(" ") + Text.bold("v1.2.3") + Text("...")))
}
}
describe("when a repository has been cloned") {
beforeEachTest { listener.onCloneComplete() }
it("prints a blank line to the console to separate any output from Git from any further output from Batect") {
verify(console).println()
}
}
}
given("quiet output is being used") {
val outputStyle = OutputStyle.Quiet
val listener by createForEachTest { DefaultGitRepositoryCacheNotificationListener(console, outputStyle) }
describe("when a repository is being cloned") {
val repo = GitRepositoryReference("https://myrepo.com/bundles/bundle.git", "v1.2.3")
beforeEachTest { listener.onCloning(repo) }
it("does not print anything to the console") {
verifyNoInteractions(console)
}
}
describe("when a repository has been cloned") {
beforeEachTest { listener.onCloneComplete() }
it("prints a blank line to the console to separate any output from Git from any further output from Batect") {
verifyNoInteractions(console)
}
}
}
}
})
| 24 | Kotlin | 49 | 687 | 67c942241c7d52b057c5268278d6252301c48087 | 3,161 | batect | Apache License 2.0 |
Chapter15/Exercise15.04/app/src/main/java/com/example/tipcalculator/MainActivity.kt | PacktPublishing | 310,206,627 | false | {"Kotlin": 583795} | package com.example.tipcalculator
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val amountText: EditText = findViewById(R.id.amount_text)
val percentText: EditText = findViewById(R.id.percent_text)
val computeButton: Button = findViewById(R.id.compute_button)
computeButton.setOnClickListener {
val amount =
if (amountText.text.toString().isNotBlank()) amountText.text.toString() else "0"
val percent =
if (percentText.text.toString().isNotBlank()) percentText.text.toString() else "0"
val intent = Intent(this, OutputActivity::class.java).apply {
putExtra("amount", amount)
putExtra("percent", percent)
}
val image: ImageView = findViewById(R.id.image)
startActivity(
intent,
ActivityOptions.makeSceneTransitionAnimation(this, image, "transition_name")
.toBundle()
)
}
}
}
| 2 | Kotlin | 67 | 97 | b37be5b81ed1f5fb107733b509bae80e46f92f4a | 1,397 | How-to-Build-Android-Apps-with-Kotlin | MIT License |
app/src/main/java/com/padc/mmkunyi/fragments/LoginFragment.kt | thihaphyo | 142,582,453 | false | null | package com.padc.mmkunyi.fragments
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.padc.mmkunyi.R
import com.padc.mmkunyi.activities.UserControlActivity
import com.padc.mmkunyi.utils.AppConstants
import kotlinx.android.synthetic.main.fragment_login.view.*
/**
*
* Created by <NAME> on 8/3/18.
*/
class LoginFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_login, container, false)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.btnSignUp.setOnClickListener {
val intent = Intent(view.context, UserControlActivity::class.java)
intent.putExtra(AppConstants.isLoginView, false)
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | 4fc0c52cba57d75425a64efd0e4d4b820da7c0f1 | 1,039 | MM_KUNYI_PTH | MIT License |
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/nearby/modules/tracing/DefaultTracingStatusTest.kt | si-covid-19 | 286,833,811 | false | null | package de.rki.coronawarnapp.nearby.modules.tracing
import com.google.android.gms.nearby.exposurenotification.ExposureNotificationClient
import io.kotest.matchers.shouldBe
import io.mockk.Called
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import testhelpers.BaseTest
import testhelpers.coroutines.runBlockingTest2
import testhelpers.coroutines.test
import testhelpers.gms.MockGMSTask
class DefaultTracingStatusTest : BaseTest() {
@MockK lateinit var client: ExposureNotificationClient
@BeforeEach
fun setup() {
MockKAnnotations.init(this)
every { client.isEnabled } answers { MockGMSTask.forValue(true) }
}
private fun createInstance(scope: CoroutineScope): DefaultTracingStatus = DefaultTracingStatus(
client = client,
scope = scope
)
@Test
fun `init is sideeffect free and lazy`() = runBlockingTest2(ignoreActive = true) {
createInstance(scope = this)
advanceUntilIdle()
verify { client wasNot Called }
}
@Test
fun `state emission works`() = runBlockingTest2(ignoreActive = true) {
val instance = createInstance(scope = this)
instance.isTracingEnabled.first() shouldBe true
}
@Test
fun `state is updated and polling stops on cancel`() = runBlockingTest2(ignoreActive = true) {
every { client.isEnabled } returnsMany listOf(
true,
false,
true,
false,
true,
false,
true
).map { MockGMSTask.forValue(it) }
val instance = createInstance(scope = this)
instance.isTracingEnabled.take(6).toList() shouldBe listOf(
true,
false,
true,
false,
true,
false
)
verify(exactly = 6) { client.isEnabled }
}
@Test
fun `subscriptions are shared but not cached`() = runBlockingTest2(ignoreActive = true) {
val instance = createInstance(scope = this)
val collector1 = instance.isTracingEnabled.test(tag = "1", startOnScope = this)
val collector2 = instance.isTracingEnabled.test(tag = "2", startOnScope = this)
delay(500)
collector1.latestValue shouldBe true
collector2.latestValue shouldBe true
collector1.cancel()
collector2.cancel()
advanceUntilIdle()
verify(exactly = 1) { client.isEnabled }
every { client.isEnabled } answers { MockGMSTask.forValue(false) }
instance.isTracingEnabled.first() shouldBe false
}
}
| 6 | Kotlin | 8 | 15 | 5a3b4be63b5b030da49216a0132a3979cad89af1 | 2,893 | ostanizdrav-android | Apache License 2.0 |
compiler/testData/diagnostics/testsWithStdLib/annotations/annotationApplicability/jvmNameOnMangledNames.kt | tnorbye | 162,147,688 | true | {"Kotlin": 32763299, "Java": 7651072, "JavaScript": 152998, "HTML": 71905, "Lex": 18278, "IDL": 10641, "ANTLR": 9803, "Shell": 7727, "Groovy": 6091, "Batchfile": 5362, "CSS": 4679, "Scala": 80} | // !LANGUAGE: +InlineClasses
// !DIAGNOSTICS: -UNUSED_PARAMETER
inline class Foo(val x: Int) {
<!INAPPLICABLE_JVM_NAME!>@JvmName("other")<!>
fun simple() {}
}
<!INAPPLICABLE_JVM_NAME!>@JvmName("bad")<!>
fun bar(f: Foo) {}
@JvmName("good")
fun baz(r: Result<Int>) {} | 13 | Kotlin | 2 | 2 | b6be6a4919cd7f37426d1e8780509a22fa49e1b1 | 276 | kotlin | Apache License 2.0 |
core/src/main/java/contacts/core/util/DataRawContact.kt | vestrel00 | 223,332,584 | false | {"Kotlin": 1616347, "Shell": 635} | package contacts.core.util
import contacts.core.Contacts
import contacts.core.entities.ExistingDataEntity
import contacts.core.entities.RawContact
/**
* Returns the [RawContact] with the [ExistingDataEntity.rawContactId].
*
* This may return null if the [RawContact] no longer exists or if permissions are not granted.
*
* Supports profile/non-profile RawContacts with native/custom data.
*
* ## Permissions
*
* The [contacts.core.ContactsPermissions.READ_PERMISSION] is required.
*
* ## Cancellation
*
* To cancel this operation at any time, the [cancel] function should return true.
*
* This is useful when running this function in a background thread or coroutine.
*
* ## Thread Safety
*
* This should be called in a background thread to avoid blocking the UI thread.
*/
// [ANDROID X] @WorkerThread (not using annotation to avoid dependency on androidx.annotation)
@JvmOverloads
fun ExistingDataEntity.rawContact(
contacts: Contacts,
cancel: () -> Boolean = { false }
): RawContact? = contacts.findRawContactWithId(rawContactId, cancel) | 23 | Kotlin | 36 | 555 | 193014a913ad76e2de31d1da1e21f0b475887003 | 1,070 | contacts-android | Apache License 2.0 |
Parent/app/src/main/kotlin/com/github/midros/istheapp/ui/widget/OnScrollListener.kt | mfa237 | 156,900,862 | false | null | package com.github.midros.istheapp.ui.widget
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.GridLayoutManager
import com.github.clans.fab.FloatingActionButton
import com.pawegio.kandroid.show
import com.pawegio.kandroid.hide
/**
* Created by <NAME> on 20/03/18.
*/
class OnScrollListener(private val floating: FloatingActionButton, private val lManager: GridLayoutManager) : RecyclerView.OnScrollListener() {
private var visibleThreshold = 2
private var firstVisibleItem = 0
private var visibleItemCount = 0
private var totalItemCount = 0
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
visibleItemCount = recyclerView.childCount
totalItemCount = lManager.itemCount
firstVisibleItem = lManager.findFirstVisibleItemPosition()
if ((totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) floating.hide()
else floating.show()
}
} | 2 | Kotlin | 10 | 6 | faab27dae4fbf7cb6b341fdd94f670ecb2308742 | 1,027 | Open-source-android-spyware | Apache License 2.0 |
compiler/backend/src/org/jetbrains/kotlin/codegen/range/forLoop/ForInDefinitelySafeSimpleProgressionLoopGenerator.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen.range.forLoop
import org.jetbrains.kotlin.codegen.ExpressionCodegen
import org.jetbrains.kotlin.codegen.StackValue
import org.jetbrains.kotlin.codegen.range.BoundedValue
import org.jetbrains.kotlin.codegen.range.comparison.ComparisonGenerator
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.org.objectweb.asm.Label
/**
* Generates "naive" for loop:
*
* ```
* i = [| startValue |];
* [| if (!isStartInclusive) inc i |];
* end = [| endValue |];
* while ([| cmp(i, end) |]) ... {
* [| body |];
* inc i;
* }
* ```
*
* This generator is suitable for cases where arithmetic overflow is impossible.
*/
class ForInDefinitelySafeSimpleProgressionLoopGenerator(
codegen: ExpressionCodegen,
forExpression: KtForExpression,
private val startValue: StackValue,
private val isStartInclusive: Boolean,
private val endValue: StackValue,
private val isEndInclusive: Boolean,
comparisonGenerator: ComparisonGenerator,
step: Int
) : AbstractForInRangeLoopGenerator(codegen, forExpression, step, comparisonGenerator) {
constructor(
codegen: ExpressionCodegen,
forExpression: KtForExpression,
boundedValue: BoundedValue,
comparisonGenerator: ComparisonGenerator,
step: Int
) : this(
codegen, forExpression,
startValue = if (step == 1) boundedValue.lowBound else boundedValue.highBound,
isStartInclusive = if (step == 1) boundedValue.isLowInclusive else boundedValue.isHighInclusive,
endValue = if (step == 1) boundedValue.highBound else boundedValue.lowBound,
isEndInclusive = if (step == 1) boundedValue.isHighInclusive else boundedValue.isLowInclusive,
comparisonGenerator = comparisonGenerator,
step = step
)
companion object {
fun fromBoundedValueWithStep1(
codegen: ExpressionCodegen,
forExpression: KtForExpression,
boundedValue: BoundedValue,
comparisonGenerator: ComparisonGenerator
) =
ForInDefinitelySafeSimpleProgressionLoopGenerator(codegen, forExpression, boundedValue, comparisonGenerator, 1)
fun fromBoundedValueWithStepMinus1(
codegen: ExpressionCodegen,
forExpression: KtForExpression,
boundedValue: BoundedValue,
comparisonGenerator: ComparisonGenerator
) =
ForInDefinitelySafeSimpleProgressionLoopGenerator(codegen, forExpression, boundedValue, comparisonGenerator, -1)
}
override fun storeRangeStartAndEnd() {
loopParameter().store(startValue, v)
// Skip 1st element if start is not inclusive.
if (!isStartInclusive) incrementLoopVariable()
StackValue.local(endVar, asmElementType).store(endValue, v)
}
override fun checkEmptyLoop(loopExit: Label) {
}
override fun checkPreCondition(loopExit: Label) {
loopParameter().put(asmElementType, elementType, v)
v.load(endVar, asmElementType)
if (step > 0) {
if (isEndInclusive)
comparisonGenerator.jumpIfGreater(v, loopExit)
else
comparisonGenerator.jumpIfGreaterOrEqual(v, loopExit)
} else {
if (isEndInclusive)
comparisonGenerator.jumpIfLess(v, loopExit)
else
comparisonGenerator.jumpIfLessOrEqual(v, loopExit)
}
}
override fun checkPostConditionAndIncrement(loopExit: Label) {
incrementLoopVariable()
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 4,173 | kotlin | Apache License 2.0 |
app/src/main/java/org/biotstoiq/gophercle/SettingsActivity.kt | k1gen | 645,793,214 | false | null | package org.biotstoiq.gophercle
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.NumberPicker
import android.widget.TextView
import androidx.preference.PreferenceManager
class SettingsActivity : Activity() {
var saveBtn: Button? = null
var txtSzeValTV: TextView? = null
var txtSzeNP: NumberPicker? = null
var textSizeLL: LinearLayout? = null
var srchUrlSvdValLL: LinearLayout? = null
var srchUrlSvdValTV: TextView? = null
var srchUrlValET: EditText? = null
var shrdPrfrncs: SharedPreferences? = null
var txtSizInt = 0
var srchUrlStr: String? = null
var alrtDlg: AlertDialog? = null
var dlgBldr: AlertDialog.Builder? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
saveBtn = findViewById(R.id.saveBtn)
textSizeLL = findViewById(R.id.txtSzeLL)
txtSzeValTV = findViewById(R.id.txtSzeVal)
srchUrlSvdValTV = findViewById(R.id.srchUrlSvdValTV)
srchUrlSvdValLL = findViewById(R.id.srchUrlSvdValLL)
shrdPrfrncs = PreferenceManager.getDefaultSharedPreferences(this)
txtSizInt = shrdPrfrncs!!.getInt("txt_siz", 14)
srchUrlStr = shrdPrfrncs!!.getString("srch_url", "gopher://gopher.floodgap.com/v2/vs")
val editor = shrdPrfrncs!!.edit()
txtSzeValTV?.text = txtSizInt.toString()
srchUrlSvdValTV?.text = srchUrlStr
saveBtn?.setOnClickListener { v: View? ->
editor.putInt("txt_siz", txtSizInt)
editor.putString("srch_url", srchUrlStr)
editor.apply()
}
textSizeLL?.setOnClickListener { view: View? ->
dlgBldr = AlertDialog.Builder(this)
dlgBldr!!.setTitle(R.string.txt_size)
dlgBldr!!.setView(R.layout.activity_numberpicker)
dlgBldr!!.setNegativeButton(R.string.cncl
) { dialogInterface: DialogInterface, i: Int -> dialogInterface.cancel() }
dlgBldr!!.setPositiveButton(R.string.ok) { dialogInterface: DialogInterface?, i: Int ->
txtSizInt = txtSzeNP!!.value
txtSzeValTV?.text = txtSizInt.toString()
}
alrtDlg = dlgBldr!!.create()
alrtDlg?.show()
txtSzeNP = alrtDlg?.findViewById(R.id.txtSzeNP)
txtSzeNP?.maxValue = 20
txtSzeNP?.minValue = 8
txtSzeNP?.value = txtSizInt
}
srchUrlSvdValLL?.setOnClickListener { view: View? ->
dlgBldr = AlertDialog.Builder(this)
dlgBldr!!.setTitle(R.string.url)
dlgBldr!!.setView(R.layout.alert_dialog_url)
dlgBldr!!.setNegativeButton(R.string.cncl
) { dialogInterface: DialogInterface, i: Int -> dialogInterface.cancel() }
dlgBldr!!.setPositiveButton(R.string.ok) { dialogInterface: DialogInterface?, i: Int ->
srchUrlStr = srchUrlValET!!.text.toString()
srchUrlSvdValTV?.text = srchUrlStr
}
alrtDlg = dlgBldr!!.create()
alrtDlg?.show()
srchUrlValET = alrtDlg?.findViewById(R.id.adrUrlValET)
}
}
}
| 0 | Kotlin | 1 | 0 | 4941091864e41059fb0d9e2a50b96fb9c91fbce2 | 3,449 | gophercle | MIT License |
src/jsMain/kotlin/app/softwork/routingcompose/UUID.kt | DrewCarlson | 378,291,222 | true | {"Kotlin": 44349, "HTML": 290} | package app.softwork.routingcompose
@JsNonModule
@JsModule("uuid")
internal external object UUIDGen {
fun v4(): UUID
fun validate(uuid: UUID): Boolean
}
internal actual fun validateUUID(uuid: UUID): Boolean {
return UUIDGen.validate(uuid)
} | 0 | Kotlin | 0 | 0 | 3029cb48882efd772c8879dd01ccbbcdd6f40c14 | 254 | routing-compose | Apache License 2.0 |
src/main/kotlin/io/github/raipc/chatgpt/entity/Message.kt | raipc | 705,055,554 | false | {"Kotlin": 14365} | package io.github.raipc.chatgpt.entity
internal interface Message {
val id: String
} | 0 | Kotlin | 0 | 0 | 3da7e37a69365011aa08bdcef291b6c2fa122d83 | 89 | chatgpt-kt | Apache License 2.0 |
src/main/kotlin/pl/krakow/riichi/chombot/commands/kcc3client/DateSerializer.kt | Prinnie | 235,475,858 | false | null | package pl.krakow.riichi.chombot.commands.kcc3client
import kotlinx.serialization.*
import kotlinx.serialization.internal.StringDescriptor
import java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME
import java.time.temporal.TemporalAccessor
@Serializer(forClass = TemporalAccessor::class)
object DateSerializer : KSerializer<TemporalAccessor> {
override val descriptor: SerialDescriptor =
StringDescriptor.withName("DateSerializer")
override fun serialize(encoder: Encoder, obj: TemporalAccessor) {
encoder.encodeString(ISO_OFFSET_DATE_TIME.format(obj))
}
override fun deserialize(decoder: Decoder): TemporalAccessor {
return ISO_OFFSET_DATE_TIME.parse(decoder.decodeString())
}
}
| 0 | Kotlin | 0 | 0 | 658e4d53b6cef2a74b53df79ec02f4d7396f0429 | 733 | Mahjong | MIT License |
src/main/kotlin/xyz/nightfury/commands/standard/ColorMeCmd.kt | NightFuryBot | 93,881,665 | false | null | /*
* Copyright 2017-2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.nightfury.commands.standard
import xyz.nightfury.annotations.MustHaveArguments
import xyz.nightfury.entities.promise
import xyz.nightfury.extensions.findRoles
import xyz.nightfury.extensions.multipleRoles
import xyz.nightfury.extensions.noMatch
import net.dv8tion.jda.core.Permission
import xyz.nightfury.Category
import xyz.nightfury.Command
import xyz.nightfury.CommandEvent
import xyz.nightfury.CooldownScope
import xyz.nightfury.annotations.HasDocumentation
import xyz.nightfury.db.SQLColorMe
import java.awt.Color
import kotlin.streams.toList
/**
* @author <NAME>
*/
@HasDocumentation
@MustHaveArguments("Specify a color or hex code!")
class ColorMeCmd : Command() {
companion object {
private val pattern = Regex("#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]").toPattern()
}
init {
this.name = "ColorMe"
this.arguments = "[Color or Hex Code]"
this.help = "Set the color of your highest ColorMe role."
this.cooldown = 20
this.guildOnly = true
this.cooldownScope = CooldownScope.USER_GUILD
this.botPermissions = arrayOf(Permission.MANAGE_ROLES)
this.children = arrayOf(
ColorMeAddCmd(),
ColorMeRemoveCmd()
)
}
override fun execute(event: CommandEvent) {
val allColormes = SQLColorMe.getRoles(event.guild)
if(allColormes.isEmpty())
return event.replyError("**No ColorMe roles on this server!**\n" +
SEE_HELP.format(event.client.prefix, name))
val colormes = event.member.roles.stream().filter { allColormes.contains(it) }.toList()
if(colormes.isEmpty())
return event.replyError("**You do not have any ColorMe roles!**\n" +
SEE_HELP.format(event.client.prefix, name))
val color : Color = if(pattern.matcher(event.args).matches()) {
try {
Color.decode(event.args)
} catch(e: NumberFormatException) {
return event.replyError("${event.args} is not a valid hex!")
}
} else when(event.args.toLowerCase()) {
// Regular Colors
"red" -> Color.RED
"orange" -> Color.ORANGE
"yellow" -> Color.YELLOW
"green" -> Color.GREEN
"cyan" -> Color.CYAN
"blue" -> Color.BLUE
"magenta" -> Color.MAGENTA
"pink" -> Color.PINK
"black" -> Color.decode("#000001")
"purple" -> Color.decode("#800080")
"dark gray", "dark grey" -> Color.DARK_GRAY
"gray", "grey" -> Color.GRAY
"light_gray", "light_grey" -> Color.LIGHT_GRAY
"white" -> Color.WHITE
// Discord Colors
"blurple" -> Color.decode("#7289DA")
"greyple" -> Color.decode("#99AAB5")
"darktheme" -> Color.decode("#2C2F33")
else -> return event.replyError("${event.args} is not a valid color!")
}
val requested = colormes[0]
if(!event.selfMember.canInteract(requested))
return event.replyError("**Cannot interact with your highest ColorMe role!**\n" +
"Try moving my highest role above your highest ColorMe role!")
requested.manager.setColor(color).promise() then {
event.replySuccess("Successfully changed your color to ${event.args}")
event.invokeCooldown()
} catch {
event.replyError("An unexpected error occurred while changing your color!")
}
}
}
@MustHaveArguments("Specify the name of a role to add!")
private class ColorMeAddCmd : Command()
{
init {
this.name = "Add"
this.fullname = "ColorMe Add"
this.arguments = "[Role]"
this.help = "Adds a ColorMe role for the server."
this.cooldown = 30
this.cooldownScope = CooldownScope.GUILD
this.guildOnly = true
this.botPermissions = arrayOf(Permission.MANAGE_ROLES)
this.category = Category.ADMIN
}
override fun execute(event: CommandEvent)
{
val query = event.args
val found = event.guild.findRoles(query)
if(found.isEmpty())
return event.replyError(noMatch("roles", query))
if(found.size>1)
return event.replyError(found.multipleRoles(query))
val requested = found[0]
if(SQLColorMe.isRole(requested))
return event.replyError("The role **${requested.name}** is already a ColorMe role!")
SQLColorMe.addRole(requested)
if(event.selfMember.canInteract(requested))
event.replySuccess("The role **${requested.name}** was added as ColorMe!")
else
event.replyWarning("The role **${requested.name}** was added as ColorMe!\n" +
"Please be aware that due to role hierarchy positioning, I will not be able to give this role to members!\n" +
"To fix this, make sure my I have a role higher than `${requested.name}` on the roles list.")
event.invokeCooldown()
}
}
@MustHaveArguments("Specify the name of a role to remove!")
private class ColorMeRemoveCmd : Command()
{
init {
this.name = "Remove"
this.fullname = "ColorMe Remove"
this.arguments = "[Role]"
this.help = "Removes a ColorMe role for the server."
this.guildOnly = true
this.botPermissions = arrayOf(Permission.MANAGE_ROLES)
this.category = Category.ADMIN
}
override fun execute(event: CommandEvent)
{
val query = event.args
val found = event.guild.findRoles(query).stream().filter { SQLColorMe.isRole(it) }.toList()
if(found.isEmpty())
return event.replyError(noMatch("roles", query))
if(found.size>1)
return event.replyError(found.multipleRoles(query))
SQLColorMe.deleteRole(found[0])
event.replySuccess("The role **${found[0].name}** was removed from ColorMe!")
}
}
| 0 | Kotlin | 0 | 6 | 6644cf54e64ded25f9c5a5ba113b610f3595e251 | 6,945 | NightFury | Apache License 2.0 |
src/main/kotlin/io/kvision/rest/RestClient.kt | tfonrouge | 456,266,511 | true | {"Kotlin": 3516267, "JavaScript": 322238, "CSS": 22113, "HTML": 2425} | /*
* Copyright (c) 2017-present <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.kvision.jquery.rest
import io.kvision.jquery.JQueryAjaxSettings
import io.kvision.jquery.JQueryXHR
import io.kvision.jquery.jQuery
import io.kvision.types.DateSerializer
import io.kvision.utils.Serialization
import io.kvision.utils.obj
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.overwriteWith
import kotlinx.serialization.serializer
import kotlin.js.Date
import kotlin.js.Promise
enum class HttpMethod {
GET,
POST,
PUT,
DELETE,
OPTIONS,
HEAD
}
/**
* A response wrapper
*/
data class Response<T>(val data: T, val textStatus: String, val jqXHR: JQueryXHR)
const val XHR_ERROR: Short = 0
const val HTTP_BAD_REQUEST: Short = 400
const val HTTP_UNAUTHORIZED: Short = 401
const val HTTP_FORBIDDEN: Short = 403
const val HTTP_NOT_FOUND: Short = 404
const val HTTP_NOT_ALLOWED: Short = 405
const val HTTP_SERVER_ERROR: Short = 500
const val HTTP_NOT_IMPLEMENTED: Short = 501
const val HTTP_BAD_GATEWAY: Short = 502
const val HTTP_SERVICE_UNAVAILABLE: Short = 503
open class RemoteRequestException(val code: Short, val url: String, val method: HttpMethod, message: String) :
Exception(message) {
override fun toString(): String = "${this::class.simpleName}($code) [${method.name} $url] $message"
companion object {
fun create(code: Short, url: String, method: HttpMethod, message: String): RemoteRequestException =
when (code) {
XHR_ERROR -> XHRError(url, method, message)
HTTP_BAD_REQUEST -> BadRequest(url, method, message)
HTTP_UNAUTHORIZED -> Unauthorized(url, method, message)
HTTP_FORBIDDEN -> Forbidden(url, method, message)
HTTP_NOT_FOUND -> NotFound(url, method, message)
HTTP_NOT_ALLOWED -> NotAllowed(url, method, message)
HTTP_SERVER_ERROR -> ServerError(url, method, message)
HTTP_NOT_IMPLEMENTED -> NotImplemented(url, method, message)
HTTP_BAD_GATEWAY -> BadGateway(url, method, message)
HTTP_SERVICE_UNAVAILABLE -> ServiceUnavailable(url, method, message)
else -> RemoteRequestException(code, url, method, message)
}
}
}
/**
* Code 0 does not represent any http status, it represent XHR error (e.g. network error, CORS failure).
*/
class XHRError(url: String, method: HttpMethod, message: String) :
RemoteRequestException(XHR_ERROR, url, method, message)
class BadRequest(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_BAD_REQUEST, url, method, message)
class Unauthorized(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_UNAUTHORIZED, url, method, message)
class Forbidden(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_FORBIDDEN, url, method, message)
class NotFound(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_NOT_FOUND, url, method, message)
class NotAllowed(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_NOT_ALLOWED, url, method, message)
class ServerError(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_SERVER_ERROR, url, method, message)
class NotImplemented(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_NOT_IMPLEMENTED, url, method, message)
class BadGateway(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_BAD_GATEWAY, url, method, message)
class ServiceUnavailable(url: String, method: HttpMethod, message: String) :
RemoteRequestException(HTTP_SERVICE_UNAVAILABLE, url, method, message)
/**
* An agent responsible for remote calls.
*/
@Deprecated("Use io.kvision.rest.RestClient instead")
open class LegacyRestClient(protected val module: SerializersModule? = null) {
protected val JsonInstance = Json(from = (Serialization.customConfiguration ?: Json {
ignoreUnknownKeys = true
isLenient = true
})) {
serializersModule = SerializersModule {
contextual(Date::class, DateSerializer)
module?.let { this.include(it) }
}.overwriteWith(serializersModule)
}
/**
* Makes a remote call to the remote server.
* @param url an URL address
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @return a promise of the result
*/
@Suppress("UnsafeCastFromDynamic", "ComplexMethod")
fun remoteCall(
url: String,
data: dynamic = null,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null
): Promise<dynamic> {
return remoteRequest(url, data, method, contentType, beforeSend).then { it.data }
}
/**
* Makes a remote call to the remote server.
* @param url an URL address
* @param data data to be sent
* @param deserializer a deserializer for the result value
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the result
*/
fun <T : Any> remoteCall(
url: String,
data: dynamic = null,
deserializer: DeserializationStrategy<T>,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
transform: ((dynamic) -> dynamic)? = null
): Promise<T> {
return remoteCall(url, data, method, contentType, beforeSend).then { result: dynamic ->
val transformed = if (transform != null) {
transform(result)
} else {
result
}
@Suppress("UnsafeCastFromDynamic")
JsonInstance.decodeFromString(deserializer, JSON.stringify(transformed))
}
}
/**
* Makes a remote call to the remote server.
* @param url an URL address
* @param serializer for the data
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @return a promise of the result
*/
fun <V : Any> remoteCall(
url: String,
serializer: SerializationStrategy<V>,
data: V,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null
): Promise<dynamic> {
val dataSer =
if (method == HttpMethod.GET) data.toObj(serializer) else JsonInstance.encodeToString(serializer, data)
return remoteCall(url, dataSer, method, contentType, beforeSend)
}
/**
* Makes a remote call to the remote server.
* @param url an URL address
* @param serializer for the data
* @param data data to be sent
* @param deserializer a deserializer for the result value
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the result
*/
fun <T : Any, V : Any> remoteCall(
url: String,
serializer: SerializationStrategy<V>,
data: V,
deserializer: DeserializationStrategy<T>,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
transform: ((dynamic) -> dynamic)? = null
): Promise<T> {
val dataSer =
if (method == HttpMethod.GET) data.toObj(serializer) else JsonInstance.encodeToString(serializer, data)
return remoteCall(
url,
dataSer,
method,
contentType,
beforeSend
).then { result: dynamic ->
val transformed = if (transform != null) {
transform(result)
} else {
result
}
@Suppress("UnsafeCastFromDynamic")
JsonInstance.decodeFromString(deserializer, JSON.stringify(transformed))
}
}
/**
* Helper inline function to automatically get deserializer for the result value with dynamic data.
* @param url an URL address
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the result
*/
inline fun <reified T : Any> call(
url: String,
data: dynamic = null,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
noinline transform: ((dynamic) -> dynamic)? = null
): Promise<T> {
return remoteCall(url, data, serializer(), method, contentType, beforeSend, transform)
}
/**
* Helper inline function to automatically get serializer for the data.
* @param url an URL address
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @return a promise of the result
*/
inline fun <reified V : Any> call(
url: String,
data: V,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null
): Promise<dynamic> {
return remoteCall(
url,
serializer(),
data,
method,
contentType,
beforeSend
)
}
/**
* Helper inline function to automatically get serializer for the data.
* @param url an URL address
* @param data data to be sent
* @param deserializer a deserializer for the result value
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the result
*/
inline fun <T : Any, reified V : Any> call(
url: String,
data: V,
deserializer: DeserializationStrategy<T>,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
noinline transform: ((dynamic) -> dynamic)? = null
): Promise<T> {
return remoteCall(
url,
serializer(),
data,
deserializer,
method,
contentType,
beforeSend,
transform
)
}
/**
* Helper inline function to automatically deserializer for the result value with typed data.
* @param url an URL address
* @param serializer for the data
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the result
*/
inline fun <reified T : Any, V : Any> call(
url: String,
serializer: SerializationStrategy<V>,
data: V,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
noinline transform: ((dynamic) -> dynamic)? = null
): Promise<T> {
return remoteCall(
url,
serializer,
data,
serializer(),
method,
contentType,
beforeSend,
transform
)
}
/**
* Helper inline function to automatically get serializer for the data and deserializer for the result value.
* @param url an URL address
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the result
*/
inline fun <reified T : Any, reified V : Any> call(
url: String,
data: V,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
noinline transform: ((dynamic) -> dynamic)? = null
): Promise<T> {
return remoteCall(
url,
serializer(),
data,
serializer(),
method,
contentType,
beforeSend,
transform
)
}
/**
* Makes a remote call to the remote server.
* @param url an URL address
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @return a promise of the response
*/
@Suppress("UnsafeCastFromDynamic", "ComplexMethod")
fun remoteRequest(
url: String,
data: dynamic = null,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null
): Promise<Response<dynamic>> {
return Promise { resolve, reject ->
jQuery.ajax(url, obj {
this.contentType = if (contentType != "multipart/form-data") contentType else false
this.data = data
this.method = method.name
this.processData = if (contentType != "multipart/form-data") undefined else false
this.success =
{ data: dynamic, textStatus: String, jqXHR: JQueryXHR ->
resolve(Response(data, textStatus, jqXHR))
}
this.error =
{ xhr: JQueryXHR, _: String, errorText: String ->
val message = if (xhr.responseJSON != null && xhr.responseJSON != undefined) {
JSON.stringify(xhr.responseJSON)
} else if (xhr.responseText != undefined) {
xhr.responseText
} else {
errorText
}
reject(RemoteRequestException.create(xhr.status, url, method, message))
}
this.beforeSend = beforeSend
})
}
}
/**
* Makes a remote call to the remote server.
* @param url an URL address
* @param data data to be sent
* @param deserializer a deserializer for the result value
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the response
*/
fun <T : Any> remoteRequest(
url: String,
data: dynamic = null,
deserializer: DeserializationStrategy<T>,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
transform: ((dynamic) -> dynamic)? = null
): Promise<Response<T>> {
return remoteRequest(url, data, method, contentType, beforeSend).then { result: Response<dynamic> ->
val transformed = if (transform != null) {
transform(result.data)
} else {
result.data
}
Response(
@Suppress("UnsafeCastFromDynamic")
JsonInstance.decodeFromString(deserializer, JSON.stringify(transformed)),
result.textStatus, result.jqXHR
)
}
}
/**
* Makes a remote call to the remote server.
* @param url an URL address
* @param serializer for the data
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @return a promise of the response
*/
fun <V : Any> remoteRequest(
url: String,
serializer: SerializationStrategy<V>,
data: V,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null
): Promise<Response<dynamic>> {
val dataSer =
if (method == HttpMethod.GET) data.toObj(serializer) else JsonInstance.encodeToString(serializer, data)
return remoteRequest(url, dataSer, method, contentType, beforeSend)
}
/**
* Makes a remote call to the remote server.
* @param url an URL address
* @param serializer for the data
* @param data data to be sent
* @param deserializer a deserializer for the result value
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the response
*/
fun <T : Any, V : Any> remoteRequest(
url: String,
serializer: SerializationStrategy<V>,
data: V,
deserializer: DeserializationStrategy<T>,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
transform: ((dynamic) -> dynamic)? = null
): Promise<Response<T>> {
val dataSer =
if (method == HttpMethod.GET) data.toObj(serializer) else JsonInstance.encodeToString(serializer, data)
return remoteRequest(
url,
dataSer,
method,
contentType,
beforeSend
).then { result: Response<dynamic> ->
val transformed = if (transform != null) {
transform(result.data)
} else {
result.data
}
Response(
@Suppress("UnsafeCastFromDynamic")
JsonInstance.decodeFromString(deserializer, JSON.stringify(transformed)),
result.textStatus, result.jqXHR
)
}
}
/**
* Helper inline function to automatically get deserializer for the result value with dynamic data.
* @param url an URL address
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the response
*/
inline fun <reified T : Any> request(
url: String,
data: dynamic = null,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
noinline transform: ((dynamic) -> dynamic)? = null
): Promise<Response<T>> {
return remoteRequest(url, data, serializer(), method, contentType, beforeSend, transform)
}
/**
* Helper inline function to automatically get serializer for the data.
* @param url an URL address
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @return a promise of the response
*/
inline fun <reified V : Any> request(
url: String,
data: V,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null
): Promise<Response<dynamic>> {
return remoteRequest(
url,
serializer(),
data,
method,
contentType,
beforeSend
)
}
/**
* Helper inline function to automatically get serializer for the data.
* @param url an URL address
* @param data data to be sent
* @param deserializer a deserializer for the result value
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the response
*/
inline fun <T : Any, reified V : Any> request(
url: String,
data: V,
deserializer: DeserializationStrategy<T>,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
noinline transform: ((dynamic) -> dynamic)? = null
): Promise<Response<T>> {
return remoteRequest(
url,
serializer(),
data,
deserializer,
method,
contentType,
beforeSend,
transform
)
}
/**
* Helper inline function to automatically deserializer for the result value with typed data.
* @param url an URL address
* @param serializer for the data
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the response
*/
inline fun <reified T : Any, V : Any> request(
url: String,
serializer: SerializationStrategy<V>,
data: V,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
noinline transform: ((dynamic) -> dynamic)? = null
): Promise<Response<T>> {
return remoteRequest(
url,
serializer,
data,
serializer(),
method,
contentType,
beforeSend,
transform
)
}
/**
* Helper inline function to automatically get serializer for the data and deserializer for the result value.
* @param url an URL address
* @param data data to be sent
* @param method a HTTP method
* @param contentType a content type of the request
* @param beforeSend a function to set request parameters
* @param transform a function to transform the result of the call
* @return a promise of the response
*/
inline fun <reified T : Any, reified V : Any> request(
url: String,
data: V,
method: HttpMethod = HttpMethod.GET,
contentType: String = "application/json",
noinline beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null,
noinline transform: ((dynamic) -> dynamic)? = null
): Promise<Response<T>> {
return remoteRequest(
url,
serializer(),
data,
serializer(),
method,
contentType,
beforeSend,
transform
)
}
/**
* An extension function to convert Serializable object to JS dynamic object
* @param serializer a serializer for T
*/
protected fun <T> T.toObj(serializer: SerializationStrategy<T>): dynamic {
return JSON.parse(JsonInstance.encodeToString(serializer, this))
}
} | 0 | Kotlin | 0 | 0 | ea3b2b1887748599778d5f790b6a1bd353f0e194 | 25,950 | kvision | MIT License |
usvm-jvm/src/test/kotlin/org/usvm/samples/mixed/SerializableExampleTest.kt | UnitTestBot | 586,907,774 | false | {"Kotlin": 2547205, "Java": 471958} | package org.usvm.samples.mixed
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.usvm.samples.JavaMethodTestRunner
import org.usvm.test.util.checkers.eq
internal class SerializableExampleTest : JavaMethodTestRunner() {
@Test
@Disabled("Only 1 execution - NPE")
fun testExample() {
checkDiscoveredPropertiesWithExceptions(
SerializableExample::example,
eq(1),
{ _, r -> r.isSuccess }
)
}
}
| 39 | Kotlin | 0 | 7 | 94c5a49a0812737024dee5be9d642f22baf991a2 | 492 | usvm | Apache License 2.0 |
app/src/main/java/jp/cordea/d7362089/api/response/PhotoResponse.kt | CORDEA | 492,123,031 | false | null | package jp.cordea.d7362089.api.response
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@Serializable
data class PhotoResponse(
val id: String,
val user: User,
@SerialName("created_at")
@Serializable(with = DateTimeSerializer::class)
val createdAt: LocalDateTime,
@SerialName("updated_at")
@Serializable(with = DateTimeSerializer::class)
val updatedAt: LocalDateTime,
val width: Int,
val height: Int,
val color: String,
val views: Int,
val downloads: Int,
val likes: Int,
val description: String?,
@SerialName("alt_description")
val altDescription: String?,
val exif: Exif,
val location: Location,
val urls: Urls,
val links: Links
) {
@Serializable
data class Exif(
val make: String?,
val model: String?
)
@Serializable
data class Location(
val name: String?
)
@Serializable
data class Urls(
val raw: String,
val full: String,
val regular: String,
val thumb: String
)
@Serializable
data class Links(
val html: String
)
@Serializable
data class User(
val id: String,
val name: String,
val links: Links
)
}
class DateTimeSerializer : KSerializer<LocalDateTime> {
private val serializer = String.serializer()
override val descriptor: SerialDescriptor
get() = serializer.descriptor
override fun deserialize(decoder: Decoder): LocalDateTime {
return LocalDateTime.parse(
decoder.decodeString(),
DateTimeFormatter.ISO_OFFSET_DATE_TIME
)
}
override fun serialize(encoder: Encoder, value: LocalDateTime) {
throw NotImplementedError()
}
}
| 0 | Kotlin | 0 | 0 | 7829b3aabdd412d5f85657a0b56ff596e02a2ec5 | 2,099 | d7362089 | Apache License 2.0 |
compiler/testData/codegen/box/bridges/delegationProperty.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // JVM_ABI_K1_K2_DIFF: KT-63828
interface A<T> {
var result: T
}
class B(a: A<String>): A<String> by a
fun box(): String {
val o = object : A<String> {
override var result = "Fail"
}
val b: A<String> = B(o)
b.result = "OK"
if (b.result != "OK") return "Fail"
return b.result
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 315 | kotlin | Apache License 2.0 |
src/main/kotlin/verysecuresystems/Inhabitants.kt | http4k | 91,459,926 | false | {"Kotlin": 43878, "HTML": 4048, "Handlebars": 1903, "CSS": 169, "Shell": 168} | package verysecuresystems
/**
* Simple, in-memory persistence of who is currently inside the building
*/
class Inhabitants : Iterable<Username> {
private val currentUsers = mutableListOf<Username>()
fun add(user: Username) =
when (user) {
in currentUsers -> false
else -> {
currentUsers += user
true
}
}
fun remove(user: Username) =
when (user) {
in currentUsers -> {
currentUsers -= user
true
}
else -> false
}
override fun iterator(): Iterator<Username> = currentUsers.iterator()
} | 2 | Kotlin | 8 | 54 | 4dc46bb9c9075b92aa43e0982f0fbc92a20ae1f0 | 673 | http4k-by-example | Apache License 2.0 |
kt/godot-library/src/main/kotlin/godot/util/ThreadLocalDelegates.kt | utopia-rise | 289,462,532 | false | {"Kotlin": 1464908, "GDScript": 492843, "C++": 484675, "C#": 10278, "C": 8523, "Shell": 8429, "Java": 2136, "CMake": 939, "Python": 75} | package godot.util
import kotlin.reflect.KProperty
internal class ThreadLocalLazyDelegate<T>(private val provider: () -> T) : Lazy<T> {
private val threadLocal = ThreadLocal.withInitial { lazy(LazyThreadSafetyMode.NONE, provider) }
override val value get() = threadLocal.get().value
override fun isInitialized(): Boolean = threadLocal.get().isInitialized()
}
internal class ThreadLocalDelegate<T>(val provider: () -> T) {
private val threadLocal = ThreadLocal.withInitial { provider() }
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = threadLocal.get()
}
internal fun <T> threadLocalLazy(provider: () -> T) = ThreadLocalLazyDelegate(provider)
internal fun <T> threadLocal(provider: () -> T) = ThreadLocalDelegate(provider)
| 61 | Kotlin | 33 | 445 | 1dfa11d5c43fc9f85de2260b8e88f4911afddcb9 | 766 | godot-kotlin-jvm | MIT License |
app/src/main/kotlin/com/lwu/geekhub/helper/InputHelper.kt | leonnnwu | 137,691,501 | false | {"Kotlin": 18468} | package com.lwu.geekhub.helper
import android.support.design.widget.TextInputLayout
/**
* Created by lwu on 6/17/18.
*/
fun TextInputLayout.getText(): String = this.editText?.text?.toString() ?: "" | 0 | Kotlin | 0 | 0 | a2b6c74d62f0cc1a832a3db25174b309ffe1e5f0 | 201 | Geekhub | Apache License 2.0 |
kotlin/src/main/kotlin/net/timafe/angkor/web/UserController.kt | tillkuhn | 219,713,329 | false | {"Kotlin": 357624, "TypeScript": 332971, "Go": 135970, "HCL": 92041, "HTML": 82105, "Makefile": 52663, "Shell": 35372, "SCSS": 31379, "Dockerfile": 4705, "JavaScript": 2537, "PLpgSQL": 2280, "CSS": 1037} | package net.timafe.angkor.web
import net.timafe.angkor.config.Constants
import net.timafe.angkor.domain.User
import net.timafe.angkor.domain.dto.UserSummary
import net.timafe.angkor.repo.UserRepository
import net.timafe.angkor.security.SecurityUtils
import net.timafe.angkor.service.UserService
import net.timafe.angkor.web.vm.AuthenticationVM
import net.timafe.angkor.web.vm.BooleanResult
import org.slf4j.LoggerFactory
import org.springframework.security.authentication.AbstractAuthenticationToken
import org.springframework.security.core.session.SessionRegistry
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.security.Principal
import java.util.stream.Collectors
/**
* REST controller for managing the current user's account.
*/
@RestController
@RequestMapping(Constants.API_LATEST)
class UserController(
private val userService: UserService,
private val userRepository: UserRepository,
private val sessionRegistry: SessionRegistry
) {
internal class AccountResourceException(message: String) : RuntimeException(message)
private val log = LoggerFactory.getLogger(javaClass)
/**
* Can be used by frontend to check if the current user is authenticated
* (Current SecurityContext != AnonymousAuthenticationToken)
*/
@GetMapping("/authenticated")
fun isAuthenticated(): BooleanResult {
return BooleanResult(SecurityUtils.isAuthenticated())
}
@GetMapping("/authentication")
fun getAuthentication(authToken: Principal?): AuthenticationVM {
return if (SecurityUtils.isAuthenticated()) {
if (authToken !is AbstractAuthenticationToken) {
throw IllegalArgumentException("AbstractAuthenticationToken expected, UserController can't handle ${authToken?.javaClass}!")
}
AuthenticationVM(
authenticated = true,
user = getCurrentUser(authToken),
idToken = userService.extractIdTokenFromAuthToken(authToken)
)
} else {
AuthenticationVM(authenticated = false, user = null, idToken = null)
}
}
@GetMapping("/account")
fun getCurrentUser(authToken: Principal?): User {
// Currently, Principal == oauth2 auth token
if (authToken !is AbstractAuthenticationToken) {
throw IllegalArgumentException("AbstractAuthenticationToken expected, UserController can't handle ${authToken?.javaClass}!")
}
val attributes = userService.extractAttributesFromAuthToken(authToken)
val user = userService.findUser(attributes)
log.debug("[User] Account for principal $authToken: user $user")
return user ?: throw AccountResourceException("User not be found for principal=$authToken")
}
@GetMapping("/${Constants.API_PATH_ADMIN}/session-users")
fun getUsersFromSessionRegistry(): List<String?>? {
return sessionRegistry.allPrincipals.stream()
.filter { u -> sessionRegistry.getAllSessions(u, false).isNotEmpty() }
.map { obj: Any -> obj.toString() }
.collect(Collectors.toList())
}
/**
* Get list of user summaries
* filter out root user which is considered internal (any maybe later users in 000000 range)
*/
@GetMapping("/user-summaries")
fun getUserSummaries(): List<UserSummary> {
val items =
userRepository.findAllUserSummaries().filter { user ->
user.id.toString() != Constants.USER_SYSTEM
}
log.debug("[User] getUserSummaries() returned ${items.size} items")
return items
}
/**
* Request removal of user data (if authenticated)
*/
@PostMapping("/remove-me")
fun removeMe(authToken: Principal?): BooleanResult {
log.info("[User] Received request to remove current user")
if (authToken == null) {
throw IllegalStateException("Removal can only be requested from authenticated context")
}
userService.removeMe(getCurrentUser(authToken))
return BooleanResult(true)
}
}
| 28 | Kotlin | 4 | 12 | 8c15fa769ac8fce10226407e6d87e3889d13ab2c | 4,277 | angkor | Apache License 2.0 |
compiler/testData/codegen/box/callableReference/callableReferenceOfCompanionProperty.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} |
import kotlin.reflect.KProperty0
class Sample {
companion object {
const val maxValue = 1
}
}
abstract class Checker {
fun check(): String {
return run(
Sample::maxValue,
{ x -> x == 1 }
)
}
abstract fun <T1> run(method: KProperty0<T1>, fn: (T1) -> Boolean): String
}
fun box(): String {
var result = ( object : Checker() {
override fun <T1> run(method: KProperty0<T1>, fn: (T1) -> Boolean): String {
return "OK"
}
} ).check()
return result
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 556 | kotlin | Apache License 2.0 |
app/src/main/java/com/udeshcoffee/android/data/model/EQPreset.kt | m760622 | 163,887,222 | true | {"Kotlin": 579238, "Java": 35200, "HTML": 12682} | package com.udeshcoffee.android.data.model
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
/**
* Created by Udathari on 9/26/2017.
*/
@Entity(tableName = "equalizer")
data class EQPreset(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "eqid") val id: Int,
@ColumnInfo(name = "eqname") val name: String
) | 0 | Kotlin | 0 | 1 | 928bd65fd6064a26cbb758a0604ed5718a1ea55f | 418 | CoffeeMusicPlayer | Apache License 2.0 |
libraries/stdlib/src/kotlin/coroutines/CoroutineContextImpl.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.coroutines
import kotlin.coroutines.CoroutineContext.Element
import kotlin.coroutines.CoroutineContext.Key
/**
* Base class for [CoroutineContext.Element] implementations.
*/
@SinceKotlin("1.3")
public abstract class AbstractCoroutineContextElement(public override val key: Key<*>) : Element
/**
* Base class for [CoroutineContext.Key] associated with polymorphic [CoroutineContext.Element] implementation.
* Polymorphic element implementation implies delegating its [get][Element.get] and [minusKey][Element.minusKey]
* to [getPolymorphicElement] and [minusPolymorphicKey] respectively.
*
* Polymorphic elements can be extracted from the coroutine context using both element key and its supertype key.
* Example of polymorphic elements:
* ```
* open class BaseElement : CoroutineContext.Element {
* companion object Key : CoroutineContext.Key<BaseElement>
* override val key: CoroutineContext.Key<*> get() = Key
* // It is important to use getPolymorphicKey and minusPolymorphicKey
* override fun <E : CoroutineContext.Element> get(key: CoroutineContext.Key<E>): E? = getPolymorphicElement(key)
* override fun minusKey(key: CoroutineContext.Key<*>): CoroutineContext = minusPolymorphicKey(key)
* }
*
* class DerivedElement : BaseElement() {
* companion object Key : AbstractCoroutineContextKey<BaseElement, DerivedElement>(BaseElement, { it as? DerivedElement })
* }
* // Now it is possible to query both `BaseElement` and `DerivedElement`
* someContext[BaseElement] // Returns BaseElement?, non-null both for BaseElement and DerivedElement instances
* someContext[DerivedElement] // Returns DerivedElement?, non-null only for DerivedElement instance
* ```
* @param B base class of a polymorphic element
* @param baseKey an instance of base key
* @param E element type associated with the current key
* @param safeCast a function that can safely cast abstract [CoroutineContext.Element] to the concrete [E] type
* and return the element if it is a subtype of [E] or `null` otherwise.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public abstract class AbstractCoroutineContextKey<B : Element, E : B>(
baseKey: Key<B>,
private val safeCast: (element: Element) -> E?
) : Key<E> {
private val topmostKey: Key<*> = if (baseKey is AbstractCoroutineContextKey<*, *>) baseKey.topmostKey else baseKey
internal fun tryCast(element: Element): E? = safeCast(element)
internal fun isSubKey(key: Key<*>): Boolean = key === this || topmostKey === key
}
/**
* Returns the current element if it is associated with the given [key] in a polymorphic manner or `null` otherwise.
* This method returns non-null value if either [Element.key] is equal to the given [key] or if the [key] is associated
* with [Element.key] via [AbstractCoroutineContextKey].
* See [AbstractCoroutineContextKey] for the example of usage.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public fun <E : Element> Element.getPolymorphicElement(key: Key<E>): E? {
if (key is AbstractCoroutineContextKey<*, *>) {
@Suppress("UNCHECKED_CAST")
return if (key.isSubKey(this.key)) key.tryCast(this) as? E else null
}
@Suppress("UNCHECKED_CAST")
return if (this.key === key) this as E else null
}
/**
* Returns empty coroutine context if the element is associated with the given [key] in a polymorphic manner
* or `null` otherwise.
* This method returns empty context if either [Element.key] is equal to the given [key] or if the [key] is associated
* with [Element.key] via [AbstractCoroutineContextKey].
* See [AbstractCoroutineContextKey] for the example of usage.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public fun Element.minusPolymorphicKey(key: Key<*>): CoroutineContext {
if (key is AbstractCoroutineContextKey<*, *>) {
return if (key.isSubKey(this.key) && key.tryCast(this) != null) EmptyCoroutineContext else this
}
return if (this.key === key) EmptyCoroutineContext else this
}
/**
* An empty coroutine context.
*/
@SinceKotlin("1.3")
public object EmptyCoroutineContext : CoroutineContext, Serializable {
private const val serialVersionUID: Long = 0
private fun readResolve(): Any = EmptyCoroutineContext
public override fun <E : Element> get(key: Key<E>): E? = null
public override fun <R> fold(initial: R, operation: (R, Element) -> R): R = initial
public override fun plus(context: CoroutineContext): CoroutineContext = context
public override fun minusKey(key: Key<*>): CoroutineContext = this
public override fun hashCode(): Int = 0
public override fun toString(): String = "EmptyCoroutineContext"
}
//--------------------- internal impl ---------------------
// this class is not exposed, but is hidden inside implementations
// this is a left-biased list, so that `plus` works naturally
@SinceKotlin("1.3")
internal class CombinedContext(
private val left: CoroutineContext,
private val element: Element
) : CoroutineContext, Serializable {
override fun <E : Element> get(key: Key<E>): E? {
var cur = this
while (true) {
cur.element[key]?.let { return it }
val next = cur.left
if (next is CombinedContext) {
cur = next
} else {
return next[key]
}
}
}
public override fun <R> fold(initial: R, operation: (R, Element) -> R): R =
operation(left.fold(initial, operation), element)
public override fun minusKey(key: Key<*>): CoroutineContext {
element[key]?.let { return left }
val newLeft = left.minusKey(key)
return when {
newLeft === left -> this
newLeft === EmptyCoroutineContext -> element
else -> CombinedContext(newLeft, element)
}
}
private fun size(): Int {
var cur = this
var size = 2
while (true) {
cur = cur.left as? CombinedContext ?: return size
size++
}
}
private fun contains(element: Element): Boolean =
get(element.key) == element
private fun containsAll(context: CombinedContext): Boolean {
var cur = context
while (true) {
if (!contains(cur.element)) return false
val next = cur.left
if (next is CombinedContext) {
cur = next
} else {
return contains(next as Element)
}
}
}
override fun equals(other: Any?): Boolean =
this === other || other is CombinedContext && other.size() == size() && other.containsAll(this)
override fun hashCode(): Int = left.hashCode() + element.hashCode()
override fun toString(): String =
"[" + fold("") { acc, element ->
if (acc.isEmpty()) element.toString() else "$acc, $element"
} + "]"
private fun writeReplace(): Any {
val n = size()
val elements = arrayOfNulls<CoroutineContext>(n)
var index = 0
fold(Unit) { _, element -> elements[index++] = element }
check(index == n)
@Suppress("UNCHECKED_CAST")
return Serialized(elements as Array<CoroutineContext>)
}
private class Serialized(val elements: Array<CoroutineContext>) : Serializable {
companion object {
private const val serialVersionUID: Long = 0L
}
private fun readResolve(): Any = elements.fold(EmptyCoroutineContext, CoroutineContext::plus)
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 7,731 | kotlin | Apache License 2.0 |
ok-blogs-common-be/src/main/kotlin/ru/otus/kotlin/blogs/common/context/MpBeContext.kt | otuskotlin | 327,215,631 | false | null | package ru.otus.kotlin.blogs.common.context
import ru.otus.kotlin.blogs.common.models.*
data class MpBeContext(
var requestArticleId: MpArticleIdModel = MpArticleIdModel.NONE,
var requestCategoryId: MPCategoryIdModel = MPCategoryIdModel.NONE,
var requestTagId: MpTagIdModel = MpTagIdModel.NONE,
var requestArticle: MpArticleModel = MpArticleModel.NONE,
var requestCategory: MpCategoryModel = MpCategoryModel.NONE,
var requestTag: MpTagModel = MpTagModel.NONE,
var responseArticle: MpArticleModel = MpArticleModel.NONE,
var responseCategory:MpCategoryModel = MpCategoryModel.NONE,
var responseTag: MpTagModel = MpTagModel.NONE,
)
| 1 | Kotlin | 0 | 0 | a23a05a80ee90c6c02a200f4dc6acde31b80bc76 | 668 | otuskotlin-202012-blogs-sa | MIT License |