path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/github/lppedd/cc/lookupElement/TextFieldLookupElementDecorator.kt | lppedd | 208,670,987 | false | {"Kotlin": 415756, "HTML": 49996, "Java": 9014, "Lex": 4027} | package com.github.lppedd.cc.lookupElement
import com.github.lppedd.cc.api.CommitToken
import com.github.lppedd.cc.psiElement.CommitTokenPsiElement
import com.github.lppedd.cc.replaceString
import com.github.lppedd.cc.runInWriteActionIfNeeded
import com.intellij.codeInsight.completion.CodeCompletionHandlerBase.DIRECT_INSERTION
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.AutoCompletionPolicy
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolderBase
/**
* @author <NAME>
*/
internal class TextFieldLookupElementDecorator(private val delegate: CommitTokenLookupElement) :
CommitTokenLookupElement(),
DelegatingLookupElement<CommitTokenLookupElement> {
init {
putUserData(DIRECT_INSERTION, true)
}
override fun getDelegate(): CommitTokenLookupElement =
delegate
override fun handleInsert(context: InsertionContext) {
val editor = context.editor
val document = editor.document
runInWriteActionIfNeeded {
editor.replaceString(0, document.textLength, lookupString, true)
}
}
override fun getToken(): CommitToken =
delegate.getToken()
override fun getPsiElement(): CommitTokenPsiElement =
delegate.psiElement
override fun getLookupString(): String =
delegate.lookupString
override fun getItemText(): String =
delegate.getItemText()
override fun renderElement(presentation: LookupElementPresentation) =
delegate.renderElement(presentation)
override fun requiresCommittedDocuments(): Boolean =
delegate.requiresCommittedDocuments()
override fun isValid(): Boolean =
delegate.isValid
override fun isCaseSensitive(): Boolean =
delegate.isCaseSensitive
override fun getAutoCompletionPolicy(): AutoCompletionPolicy =
delegate.autoCompletionPolicy
override fun getAllLookupStrings(): Set<String> =
delegate.allLookupStrings
override fun isWorthShowingInAutoPopup(): Boolean =
delegate.isWorthShowingInAutoPopup
override fun <T : Any> getUserData(key: Key<T>): T? =
delegate.getUserData(key)
override fun <T : Any> putUserData(key: Key<T>, value: T?) =
delegate.putUserData(key, value)
override fun <T : Any> putUserDataIfAbsent(key: Key<T>, value: T): T =
delegate.putUserDataIfAbsent(key, value)
override fun <T : Any> replace(key: Key<T>, oldValue: T?, newValue: T?): Boolean =
delegate.replace(key, oldValue, newValue)
override fun copyUserDataTo(other: UserDataHolderBase) =
delegate.copyUserDataTo(other)
override fun <T : Any> getCopyableUserData(key: Key<T>): T? =
delegate.getCopyableUserData(key)
override fun <T : Any> putCopyableUserData(key: Key<T>, value: T) =
delegate.putCopyableUserData(key, value)
override fun copyCopyableDataTo(clone: UserDataHolderBase) =
delegate.copyCopyableDataTo(clone)
override fun isUserDataEmpty(): Boolean =
delegate.isUserDataEmpty
override fun toString(): String =
"$delegate"
override fun equals(other: Any?): Boolean =
if (other is TextFieldLookupElementDecorator) {
delegate == other.delegate
} else {
false
}
override fun hashCode(): Int =
delegate.hashCode()
}
| 34 | Kotlin | 19 | 333 | 5d55768a47a31a10147e7d69f2be261d028d1b85 | 3,289 | idea-conventional-commit | MIT License |
app/src/main/java/com/guilhermeholz/whereislunch/network/VotingApi.kt | gholz | 77,409,769 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 43, "XML": 17, "Java": 1} | package com.guilhermeholz.whereislunch.network
import com.guilhermeholz.whereislunch.network.model.votes.Vote
import com.guilhermeholz.whereislunch.network.model.votes.VotesResponse
import retrofit2.http.*
import rx.Observable
interface VotingApi {
@GET("/api/votes.php")
fun getVotes(@Query("date") date: String): Observable<VotesResponse>
@GET("/api/votes.php")
fun getVotesById(@Query("id") id: String, @Query("date") date: String): Observable<Vote>
@FormUrlEncoded
@POST("/api/votes.php")
fun vote(@Field("id") id: String, @Field("date") date: String): Observable<Vote>
@GET("/api/winners.php")
fun getWinner(@Query("date") date: String): Observable<Vote>
@GET("/api/winners.php")
fun getWinners(): Observable<VotesResponse>
} | 1 | null | 1 | 1 | 5a1047e1a64f2666600a51ff47f48faa8cd4c56a | 780 | where-is-lunch | Apache License 2.0 |
example/src/main/java/com/squaredcandy/waypoint/util/DateTimeFormat.kt | squaredcandy | 638,860,321 | false | null | package com.squaredcandy.waypoint.util
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.temporal.ChronoUnit
internal fun ZonedDateTime.formatDate(formatStyle: FormatStyle = FormatStyle.SHORT): String {
val currentDate = ZonedDateTime.now()
return when (ChronoUnit.DAYS.between(currentDate, this)) {
0L -> "Today"
1L -> "Yesterday"
else -> this.format(DateTimeFormatter.ofLocalizedDate(formatStyle))
}
}
| 0 | Kotlin | 0 | 0 | 44a82e42ae841fae201ce7ffbcb10eb20ff786c1 | 518 | waypoint | Apache License 2.0 |
app/src/main/java/com/team28/thehiker/features/sosmessage/SosMessageActivity.kt | sw21-tug | 350,774,901 | false | null | package com.team28.thehiker.features.sosmessage
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.telephony.SmsManager
import android.util.Log
import android.widget.Button
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import com.team28.thehiker.R
import com.team28.thehiker.constants.Constants
import com.team28.thehiker.location.HikerLocationService
class SosMessageActivity : AppCompatActivity(), ServiceConnection {
private val DELAY_MS_3_MINS = 3000000L
private lateinit var numbers : List<String>
private lateinit var wrapper : SMSWrapper
private lateinit var locationService : HikerLocationService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sos_message)
setSupportActionBar(findViewById(R.id.toolbar))
var test = intent.getStringArrayListExtra(Constants.SMSConstants.SOSNUMBERS)
if (test == null)
test = arrayListOf("000555", "555000")
numbers = listOf(test[0], test[1])
bindService(Intent(this, HikerLocationService::class.java), this, Context.BIND_AUTO_CREATE)
val manager : SmsManager = SmsManager.getDefault()
wrapper = SMSWrapper(manager, DELAY_MS_3_MINS, numbers, this)
val button = findViewById<Button>(R.id.stop_sos_btn)
button.setOnClickListener {
wrapper.stop()
finish()
}
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
Log.d("SosMessageActivity", "Service Connected")
locationService = (service as HikerLocationService.HikerLocationBinder).getService()
locationService.addLocationCallback(wrapper)
}
override fun onServiceDisconnected(name: ComponentName?) {
Log.d("SosMessageActivity", "Service Disconnected")
}
fun injectWrapper(wrapper: SMSWrapper){
this.wrapper = wrapper
locationService.addLocationCallback(wrapper)
}
fun getLocationService() : HikerLocationService = locationService
} | 1 | Kotlin | 9 | 7 | eb1bdb8844c55538cac867b4cc987c9d313a081b | 2,347 | Team_28 | MIT License |
app/src/main/java/com/sahu/playground/di/NetworkModule.kt | sahruday | 824,622,867 | false | {"Kotlin": 61507} | package com.sahu.playground.di
import android.content.res.Resources
import com.google.gson.GsonBuilder
import com.sahu.playground.BuildConfig
//import com.sahu.playground.appUtil.unsafeOkHttpClient
import com.sahu.playground.data.remte.api.Api
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideFilmService(client: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl("")//TODO Base url
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.client(client)
.build()
}
@Provides
@Singleton
fun provideApi(retrofit: Retrofit) = retrofit.create(Api::class.java)
@Provides
@Singleton
fun provideOkHttpClient(resources: Resources): OkHttpClient {
// return (if(BuildConfig.DEBUG) unsafeOkHttpClient else OkHttpClient())
return OkHttpClient()
.newBuilder()
.addInterceptor(createAuthInterceptor(resources))
.build()
}
private fun createAuthInterceptor(resources: Resources): Interceptor {
return Interceptor { chain ->
//TODO add token
val updatedUrl = chain.request().url()
// .newBuilder()
// .build()
chain.proceed(
chain.request().newBuilder()
.url(updatedUrl)
//If header add here.
.build()
)
}
}
} | 0 | Kotlin | 0 | 0 | f0a737920b926eca6e452086327df7a23e34b0e4 | 1,796 | playground | MIT License |
composeApp/src/commonMain/kotlin/domain/use_cases/DeleteGroupWithMessageUseCase.kt | Coding-Meet | 740,487,604 | false | {"Kotlin": 107587, "JavaScript": 707, "Swift": 659, "HTML": 401} | package domain.use_cases
import domain.respository.GeminiRepository
import org.koin.core.component.KoinComponent
class DeleteGroupWithMessageUseCase(private val geminiRepository: GeminiRepository) : KoinComponent {
suspend fun deleteGroupWithMessage(
groupId: String
) {
geminiRepository.deleteGroupWithMessage(groupId)
}
} | 0 | Kotlin | 0 | 7 | d1680ef03820bb5e6645ff16c88ad3b0e4a73bc8 | 355 | Gemini-AI-KMP-App | MIT License |
ktor-core/src/org/jetbrains/ktor/nio/AsyncPump.kt | tearsakura | 61,126,592 | true | {"Kotlin": 784184, "FreeMarker": 6356, "CSS": 5404, "HTML": 1964, "JavaScript": 1451} | package org.jetbrains.ktor.nio
import java.nio.*
import java.util.concurrent.*
import java.util.concurrent.atomic.*
private class AsyncPump(val bufferSize: Int = 8192, val from: AsyncReadChannel, val to: AsyncWriteChannel, val completionHandler: CompletableFuture<Long> = CompletableFuture(), val progressListener: ProgressListener<AsyncPump> = object: ProgressListener<AsyncPump> {
override fun progress(source: AsyncPump) {
}
}) {
private val buffer = ByteBuffer.allocate(bufferSize)
@Volatile
private var bufferToWrite = false
val state = AtomicReference(State.PAUSED)
@Volatile
var totalCount = 0L
private set
private val readHandler = object : AsyncHandler {
override fun success(count: Int) {
require(count >= 0)
if (count > 0) {
buffer.flip()
bufferToWrite = true
write()
} else {
read()
}
}
override fun successEnd() {
state.set(State.DONE)
completionHandler.complete(totalCount)
}
override fun failed(cause: Throwable) {
state.set(State.DONE)
completionHandler.completeExceptionally(cause)
}
}
private val writeHandler = object : AsyncHandler {
override fun success(count: Int) {
require(count >= 0)
if (count > 0) {
totalCount += count
progressListener.progress(this@AsyncPump)
buffer.compact()
bufferToWrite = false
read()
} else {
write()
}
}
override fun successEnd() {
}
override fun failed(cause: Throwable) {
state.set(State.DONE)
completionHandler.completeExceptionally(cause)
}
}
fun start() {
resume()
}
fun pause() {
state.compareAndSet(State.RUNNING, State.PAUSED)
}
fun resume() {
if (state.compareAndSet(State.PAUSED, State.RUNNING)) {
if (bufferToWrite) {
write()
} else {
read()
}
}
}
private fun read() {
if (state.get() == State.RUNNING) {
from.read(buffer, readHandler)
}
}
private fun write() {
if (state.get() == State.RUNNING) {
to.write(buffer, writeHandler)
}
}
enum class State {
PAUSED,
RUNNING,
DONE
}
}
fun AsyncReadChannel.copyToAsync(out: AsyncWriteChannel) {
AsyncPump(from = this, to = out).start()
}
fun AsyncReadChannel.copyToAsyncThenComplete(out: AsyncWriteChannel, completableFuture: CompletableFuture<Long>) {
AsyncPump(from = this, to = out, completionHandler = completableFuture).start()
} | 0 | Kotlin | 0 | 0 | f39bcbfa0c496fce2f9795a923b23eddcf952ffa | 2,875 | ktor | Apache License 2.0 |
jps-plugin/src/org/jetbrains/kotlin/jps/incremental/IncrementalCacheImpl.kt | guiping | 50,323,841 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental
import com.google.protobuf.MessageLite
import com.intellij.openapi.util.io.FileUtil.toSystemIndependentName
import com.intellij.util.SmartList
import com.intellij.util.io.BooleanDataDescriptor
import com.intellij.util.io.EnumeratorStringDescriptor
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.builders.storage.BuildDataPaths
import org.jetbrains.jps.incremental.ModuleBuildTarget
import org.jetbrains.jps.incremental.storage.PathStringDescriptor
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.jps.build.GeneratedJvmClass
import org.jetbrains.kotlin.jps.build.KotlinBuilder
import org.jetbrains.kotlin.jps.incremental.storage.*
import org.jetbrains.kotlin.load.kotlin.ModuleMapping
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleClassKind
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleFileFacadeKind
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleMultifileClassKind
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleMultifileClassPartKind
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache
import org.jetbrains.kotlin.load.kotlin.incremental.components.JvmPackagePartProto
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.serialization.ProtoBuf
import org.jetbrains.kotlin.serialization.deserialization.NameResolver
import org.jetbrains.kotlin.serialization.deserialization.TypeTable
import org.jetbrains.kotlin.serialization.deserialization.supertypes
import org.jetbrains.kotlin.serialization.jvm.BitEncoding
import org.jetbrains.kotlin.serialization.jvm.JvmProtoBufUtil
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.FieldVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import java.io.File
import java.security.MessageDigest
import java.util.*
val KOTLIN_CACHE_DIRECTORY_NAME = "kotlin"
open class IncrementalCacheImpl(
private val target: ModuleBuildTarget,
paths: BuildDataPaths
) : BasicMapsOwner(), IncrementalCache {
companion object {
private val PROTO_MAP = "proto"
private val CONSTANTS_MAP = "constants"
private val PACKAGE_PARTS = "package-parts"
private val MULTIFILE_CLASS_FACADES = "multifile-class-facades"
private val MULTIFILE_CLASS_PARTS = "multifile-class-parts"
private val SOURCE_TO_CLASSES = "source-to-classes"
private val DIRTY_OUTPUT_CLASSES = "dirty-output-classes"
private val SUBTYPES = "subtypes"
private val SUPERTYPES = "supertypes"
private val MODULE_MAPPING_FILE_NAME = "." + ModuleMapping.MAPPING_FILE_EXT
}
private val baseDir = File(paths.getTargetDataRoot(target), KOTLIN_CACHE_DIRECTORY_NAME)
private val cacheVersionProvider = CacheVersionProvider(paths)
private val experimentalMaps = arrayListOf<BasicMap<*, *>>()
private fun <K, V, M : BasicMap<K, V>> registerExperimentalMap(map: M): M {
experimentalMaps.add(map)
return registerMap(map)
}
protected val String.storageFile: File
get() = File(baseDir, this + "." + CACHE_EXTENSION)
private val protoMap = registerMap(ProtoMap(PROTO_MAP.storageFile))
private val constantsMap = registerMap(ConstantsMap(CONSTANTS_MAP.storageFile))
private val packagePartMap = registerMap(PackagePartMap(PACKAGE_PARTS.storageFile))
private val multifileClassFacadeMap = registerMap(MultifileClassFacadeMap(MULTIFILE_CLASS_FACADES.storageFile))
private val multifileClassPartMap = registerMap(MultifileClassPartMap(MULTIFILE_CLASS_PARTS.storageFile))
private val sourceToClassesMap = registerMap(SourceToClassesMap(SOURCE_TO_CLASSES.storageFile))
private val dirtyOutputClassesMap = registerMap(DirtyOutputClassesMap(DIRTY_OUTPUT_CLASSES.storageFile))
private val subtypesMap = registerExperimentalMap(SubtypesMap(SUBTYPES.storageFile))
private val supertypesMap = registerExperimentalMap(SupertypesMap(SUPERTYPES.storageFile))
private val dependents = arrayListOf<IncrementalCacheImpl>()
private val outputDir by lazy(LazyThreadSafetyMode.NONE) { requireNotNull(target.outputDir) { "Target is expected to have output directory: $target" } }
protected val dependentsWithThis: Sequence<IncrementalCacheImpl>
get() = sequenceOf(this).plus(dependents.asSequence())
internal val dependentCaches: Iterable<IncrementalCacheImpl>
get() = dependents
override fun registerInline(fromPath: String, jvmSignature: String, toPath: String) {
}
fun addDependentCache(cache: IncrementalCacheImpl) {
dependents.add(cache)
}
fun markOutputClassesDirty(removedAndCompiledSources: List<File>) {
for (sourceFile in removedAndCompiledSources) {
val classes = sourceToClassesMap[sourceFile]
classes.forEach {
dirtyOutputClassesMap.markDirty(it.internalName)
}
sourceToClassesMap.clearOutputsForSource(sourceFile)
}
}
fun getSubtypesOf(className: FqName): Sequence<FqName> =
subtypesMap[className].asSequence()
override fun getClassFilePath(internalClassName: String): String {
return toSystemIndependentName(File(outputDir, "$internalClassName.class").canonicalPath)
}
fun saveModuleMappingToCache(sourceFiles: Collection<File>, file: File): CompilationResult {
val jvmClassName = JvmClassName.byInternalName(MODULE_MAPPING_FILE_NAME)
protoMap.process(jvmClassName, file.readBytes(), emptyArray<String>(), isPackage = false, checkChangesIsOpenPart = false)
dirtyOutputClassesMap.notDirty(MODULE_MAPPING_FILE_NAME)
sourceFiles.forEach { sourceToClassesMap.add(it, jvmClassName) }
return CompilationResult.NO_CHANGES
}
fun saveFileToCache(generatedClass: GeneratedJvmClass): CompilationResult {
val sourceFiles: Collection<File> = generatedClass.sourceFiles
val kotlinClass: LocalFileKotlinClass = generatedClass.outputClass
val className = kotlinClass.className
dirtyOutputClassesMap.notDirty(className.internalName)
sourceFiles.forEach {
sourceToClassesMap.add(it, className)
}
val header = kotlinClass.classHeader
val changesInfo = when {
header.isCompatibleFileFacadeKind() -> {
assert(sourceFiles.size == 1) { "Package part from several source files: $sourceFiles" }
packagePartMap.addPackagePart(className)
protoMap.process(kotlinClass, isPackage = true) +
constantsMap.process(kotlinClass) +
additionalProcessChangedClass(kotlinClass, isPackage = true)
}
header.isCompatibleMultifileClassKind() -> {
val partNames = kotlinClass.classHeader.filePartClassNames?.toList()
?: throw AssertionError("Multifile class has no parts: ${kotlinClass.className}")
multifileClassFacadeMap.add(className, partNames)
// TODO NO_CHANGES? (delegates only)
constantsMap.process(kotlinClass) +
additionalProcessChangedClass(kotlinClass, isPackage = true)
}
header.isCompatibleMultifileClassPartKind() -> {
assert(sourceFiles.size == 1) { "Multifile class part from several source files: $sourceFiles" }
packagePartMap.addPackagePart(className)
multifileClassPartMap.add(className.internalName, header.multifileClassName!!)
protoMap.process(kotlinClass, isPackage = true) +
constantsMap.process(kotlinClass) +
additionalProcessChangedClass(kotlinClass, isPackage = true)
}
header.isCompatibleClassKind() && !header.isLocalClass -> {
addToClassStorage(kotlinClass)
protoMap.process(kotlinClass, isPackage = false) +
constantsMap.process(kotlinClass) +
additionalProcessChangedClass(kotlinClass, isPackage = false)
}
else -> CompilationResult.NO_CHANGES
}
changesInfo.logIfSomethingChanged(className)
return changesInfo
}
protected open fun additionalProcessChangedClass(kotlinClass: LocalFileKotlinClass, isPackage: Boolean) = CompilationResult.NO_CHANGES
private fun CompilationResult.logIfSomethingChanged(className: JvmClassName) {
if (this == CompilationResult.NO_CHANGES) return
KotlinBuilder.LOG.debug("$className is changed: $this")
}
fun clearCacheForRemovedClasses(): CompilationResult {
fun <T> T.getNonPrivateNames(nameResolver: NameResolver, vararg members: T.() -> List<MessageLite>): Set<String> =
members.flatMap { this.it().filterNot { it.isPrivate }.names(nameResolver) }.toSet()
fun createChangeInfo(className: JvmClassName): ChangeInfo? {
if (className.internalName == MODULE_MAPPING_FILE_NAME) return null
val mapValue = protoMap.get(className) ?: return null
return when {
mapValue.isPackageFacade -> {
val packageData = JvmProtoBufUtil.readPackageDataFrom(mapValue.bytes, mapValue.strings)
val memberNames =
packageData.packageProto.getNonPrivateNames(
packageData.nameResolver,
ProtoBuf.Package::getFunctionList,
ProtoBuf.Package::getPropertyList
)
ChangeInfo.Removed(className.packageFqName, memberNames)
}
else -> {
val classData = JvmProtoBufUtil.readClassDataFrom(mapValue.bytes, mapValue.strings)
val memberNames =
classData.classProto.getNonPrivateNames(
classData.nameResolver,
ProtoBuf.Class::getConstructorList,
ProtoBuf.Class::getFunctionList,
ProtoBuf.Class::getPropertyList
) + classData.classProto.enumEntryList.map { classData.nameResolver.getString(it.name) }
ChangeInfo.Removed(className.fqNameForClassNameWithoutDollars, memberNames)
}
}
}
val dirtyClasses = dirtyOutputClassesMap
.getDirtyOutputClasses()
.map(JvmClassName::byInternalName)
.toList()
val changes =
if (IncrementalCompilation.isExperimental())
dirtyClasses.mapNotNull { createChangeInfo(it) }.asSequence()
else
emptySequence<ChangeInfo>()
val changesInfo = dirtyClasses.fold(CompilationResult(changes = changes)) { info, className ->
val newInfo = CompilationResult(protoChanged = className in protoMap,
constantsChanged = className in constantsMap)
newInfo.logIfSomethingChanged(className)
info + newInfo
}
dirtyClasses.forEach {
protoMap.remove(it)
packagePartMap.remove(it)
multifileClassFacadeMap.remove(it)
multifileClassPartMap.remove(it)
constantsMap.remove(it)
}
additionalProcessRemovedClasses(dirtyClasses)
removeAllFromClassStorage(dirtyClasses)
dirtyOutputClassesMap.clean()
return changesInfo
}
protected open fun additionalProcessRemovedClasses(dirtyClasses: List<JvmClassName>) {
}
override fun getObsoletePackageParts(): Collection<String> {
val obsoletePackageParts =
dirtyOutputClassesMap.getDirtyOutputClasses().filter { packagePartMap.isPackagePart(JvmClassName.byInternalName(it)) }
KotlinBuilder.LOG.debug("Obsolete package parts: ${obsoletePackageParts}")
return obsoletePackageParts
}
override fun getPackagePartData(partInternalName: String): JvmPackagePartProto? {
return protoMap[JvmClassName.byInternalName(partInternalName)]?.let { value ->
JvmPackagePartProto(value.bytes, value.strings)
}
}
override fun getObsoleteMultifileClasses(): Collection<String> {
val obsoleteMultifileClasses = linkedSetOf<String>()
for (dirtyClass in dirtyOutputClassesMap.getDirtyOutputClasses()) {
val dirtyFacade = multifileClassPartMap.getFacadeName(dirtyClass) ?: continue
obsoleteMultifileClasses.add(dirtyFacade)
}
KotlinBuilder.LOG.debug("Obsolete multifile class facades: $obsoleteMultifileClasses")
return obsoleteMultifileClasses
}
override fun getStableMultifileFacadeParts(facadeInternalName: String): Collection<String>? {
val partNames = multifileClassFacadeMap.getMultifileClassParts(facadeInternalName) ?: return null
return partNames.filter { !dirtyOutputClassesMap.isDirty(it) }
}
override fun getMultifileFacade(partInternalName: String): String? {
return multifileClassPartMap.getFacadeName(partInternalName)
}
override fun getModuleMappingData(): ByteArray? {
return protoMap[JvmClassName.byInternalName(MODULE_MAPPING_FILE_NAME)]?.bytes
}
override fun clean() {
super.clean()
cacheVersionProvider.normalVersion(target).clean()
cacheVersionProvider.experimentalVersion(target).clean()
}
fun cleanExperimental() {
cacheVersionProvider.experimentalVersion(target).clean()
experimentalMaps.forEach { it.clean() }
}
private inner class ProtoMap(storageFile: File) : BasicStringMap<ProtoMapValue>(storageFile, ProtoMapValueExternalizer) {
fun process(kotlinClass: LocalFileKotlinClass, isPackage: Boolean): CompilationResult {
val header = kotlinClass.classHeader
val bytes = BitEncoding.decodeBytes(header.annotationData!!)
return put(kotlinClass.className, bytes, header.strings!!, isPackage, checkChangesIsOpenPart = true)
}
fun process(className: JvmClassName, data: ByteArray, strings: Array<String>, isPackage: Boolean, checkChangesIsOpenPart: Boolean): CompilationResult {
return put(className, data, strings, isPackage, checkChangesIsOpenPart)
}
private fun put(
className: JvmClassName, bytes: ByteArray, strings: Array<String>, isPackage: Boolean, checkChangesIsOpenPart: Boolean
): CompilationResult {
val key = className.internalName
val oldData = storage[key]
val data = ProtoMapValue(isPackage, bytes, strings)
if (oldData == null ||
!Arrays.equals(bytes, oldData.bytes) ||
!Arrays.equals(strings, oldData.strings) ||
isPackage != oldData.isPackageFacade
) {
storage[key] = data
}
if (oldData == null || !checkChangesIsOpenPart) return CompilationResult(protoChanged = true)
val difference = difference(oldData, data)
val fqName = if (isPackage) className.packageFqName else className.fqNameForClassNameWithoutDollars
val changeList = SmartList<ChangeInfo>()
if (difference.isClassSignatureChanged) {
changeList.add(ChangeInfo.SignatureChanged(fqName))
}
if (difference.changedMembersNames.isNotEmpty()) {
changeList.add(ChangeInfo.MembersChanged(fqName, difference.changedMembersNames))
}
return CompilationResult(protoChanged = changeList.isNotEmpty(), changes = changeList.asSequence())
}
operator fun contains(className: JvmClassName): Boolean =
className.internalName in storage
operator fun get(className: JvmClassName): ProtoMapValue? =
storage[className.internalName]
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
override fun dumpValue(value: ProtoMapValue): String {
return (if (value.isPackageFacade) "1" else "0") + java.lang.Long.toHexString(value.bytes.md5())
}
}
private inner class ConstantsMap(storageFile: File) : BasicStringMap<Map<String, Any>>(storageFile, ConstantsMapExternalizer) {
private fun getConstantsMap(bytes: ByteArray): Map<String, Any>? {
val result = HashMap<String, Any>()
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.ASM5) {
override fun visitField(access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor? {
val staticFinal = Opcodes.ACC_STATIC or Opcodes.ACC_FINAL or Opcodes.ACC_PRIVATE
if (value != null && access and staticFinal == Opcodes.ACC_STATIC or Opcodes.ACC_FINAL) {
result[name] = value
}
return null
}
}, ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES)
return if (result.isEmpty()) null else result
}
operator fun contains(className: JvmClassName): Boolean =
className.internalName in storage
fun process(kotlinClass: LocalFileKotlinClass): CompilationResult {
return put(kotlinClass.className, getConstantsMap(kotlinClass.fileContents))
}
private fun put(className: JvmClassName, constantsMap: Map<String, Any>?): CompilationResult {
val key = className.internalName
val oldMap = storage[key]
if (oldMap == constantsMap) return CompilationResult.NO_CHANGES
if (constantsMap != null) {
storage[key] = constantsMap
}
else {
storage.remove(key)
}
return CompilationResult(constantsChanged = true)
}
fun remove(className: JvmClassName) {
put(className, null)
}
override fun dumpValue(value: Map<String, Any>): String =
value.dumpMap(Any::toString)
}
private inner class PackagePartMap(storageFile: File) : BasicStringMap<Boolean>(storageFile, BooleanDataDescriptor.INSTANCE) {
fun addPackagePart(className: JvmClassName) {
storage[className.internalName] = true
}
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
fun isPackagePart(className: JvmClassName): Boolean =
className.internalName in storage
override fun dumpValue(value: Boolean) = ""
}
private inner class MultifileClassFacadeMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, StringCollectionExternalizer) {
fun add(facadeName: JvmClassName, partNames: Collection<String>) {
storage[facadeName.internalName] = partNames
}
fun getMultifileClassParts(facadeName: String): Collection<String>? = storage[facadeName]
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
override fun dumpValue(value: Collection<String>): String = value.dumpCollection()
}
private inner class MultifileClassPartMap(storageFile: File) : BasicStringMap<String>(storageFile, EnumeratorStringDescriptor.INSTANCE) {
fun add(partName: String, facadeName: String) {
storage[partName] = facadeName
}
fun getFacadeName(partName: String): String? {
return storage.get(partName)
}
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
override fun dumpValue(value: String): String = value
}
private inner class SourceToClassesMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor.INSTANCE, StringCollectionExternalizer) {
fun clearOutputsForSource(sourceFile: File) {
remove(sourceFile.absolutePath)
}
fun add(sourceFile: File, className: JvmClassName) {
storage.append(sourceFile.absolutePath, className.internalName)
}
operator fun get(sourceFile: File): Collection<JvmClassName> =
storage[sourceFile.absolutePath].orEmpty().map { JvmClassName.byInternalName(it) }
override fun dumpValue(value: Collection<String>) = value.dumpCollection()
override fun clean() {
storage.keys.forEach { remove(it) }
}
private fun remove(path: String) {
storage.remove(path)
}
}
private fun addToClassStorage(kotlinClass: LocalFileKotlinClass) {
if (!IncrementalCompilation.isExperimental()) return
val classData = JvmProtoBufUtil.readClassDataFrom(kotlinClass.classHeader.annotationData!!, kotlinClass.classHeader.strings!!)
val supertypes = classData.classProto.supertypes(TypeTable(classData.classProto.typeTable))
val parents = supertypes.map { classData.nameResolver.getClassId(it.className).asSingleFqName() }
.filter { it.asString() != "kotlin.Any" }
.toSet()
val child = kotlinClass.classId.asSingleFqName()
parents.forEach { subtypesMap.add(it, child) }
val removedSupertypes = supertypesMap[child].filter { it !in parents }
removedSupertypes.forEach { subtypesMap.removeValues(it, setOf(child)) }
supertypesMap[child] = parents
}
private fun removeAllFromClassStorage(removedClasses: Collection<JvmClassName>) {
if (!IncrementalCompilation.isExperimental() || removedClasses.isEmpty()) return
val removedFqNames = removedClasses.map { it.fqNameForClassNameWithoutDollars }.toSet()
for (cache in dependentsWithThis) {
val parentsFqNames = hashSetOf<FqName>()
val childrenFqNames = hashSetOf<FqName>()
for (removedFqName in removedFqNames) {
parentsFqNames.addAll(cache.supertypesMap[removedFqName])
childrenFqNames.addAll(cache.subtypesMap[removedFqName])
cache.supertypesMap.remove(removedFqName)
cache.subtypesMap.remove(removedFqName)
}
for (child in childrenFqNames) {
cache.supertypesMap.removeValues(child, removedFqNames)
}
for (parent in parentsFqNames) {
cache.subtypesMap.removeValues(parent, removedFqNames)
}
}
}
private inner class DirtyOutputClassesMap(storageFile: File) : BasicStringMap<Boolean>(storageFile, BooleanDataDescriptor.INSTANCE) {
fun markDirty(className: String) {
storage[className] = true
}
fun notDirty(className: String) {
storage.remove(className)
}
fun getDirtyOutputClasses(): Collection<String> =
storage.keys
fun isDirty(className: String): Boolean =
storage.contains(className)
override fun dumpValue(value: Boolean) = ""
}
}
sealed class ChangeInfo(val fqName: FqName) {
open class MembersChanged(fqName: FqName, val names: Collection<String>) : ChangeInfo(fqName) {
override fun toStringProperties(): String = super.toStringProperties() + ", names = $names"
}
class Removed(fqName: FqName, names: Collection<String>) : MembersChanged(fqName, names)
class SignatureChanged(fqName: FqName) : ChangeInfo(fqName)
protected open fun toStringProperties(): String = "fqName = $fqName"
override fun toString(): String {
return this.javaClass.simpleName + "(${toStringProperties()})"
}
}
data class CompilationResult(
val protoChanged: Boolean = false,
val constantsChanged: Boolean = false,
val inlineChanged: Boolean = false,
val inlineAdded: Boolean = false,
val changes: Sequence<ChangeInfo> = emptySequence()
) {
companion object {
val NO_CHANGES: CompilationResult = CompilationResult()
}
operator fun plus(other: CompilationResult): CompilationResult =
CompilationResult(protoChanged || other.protoChanged,
constantsChanged || other.constantsChanged,
inlineChanged || other.inlineChanged,
inlineAdded || other.inlineAdded,
changes + other.changes)
}
fun ByteArray.md5(): Long {
val d = MessageDigest.getInstance("MD5").digest(this)!!
return ((d[0].toLong() and 0xFFL)
or ((d[1].toLong() and 0xFFL) shl 8)
or ((d[2].toLong() and 0xFFL) shl 16)
or ((d[3].toLong() and 0xFFL) shl 24)
or ((d[4].toLong() and 0xFFL) shl 32)
or ((d[5].toLong() and 0xFFL) shl 40)
or ((d[6].toLong() and 0xFFL) shl 48)
or ((d[7].toLong() and 0xFFL) shl 56)
)
}
@TestOnly
fun <K : Comparable<K>, V> Map<K, V>.dumpMap(dumpValue: (V)->String): String =
buildString {
append("{")
for (key in keys.sorted()) {
if (length != 1) {
append(", ")
}
val value = get(key)?.let(dumpValue) ?: "null"
append("$key -> $value")
}
append("}")
}
@TestOnly fun <T : Comparable<T>> Collection<T>.dumpCollection(): String =
"[${sorted().joinToString(", ", transform = Any::toString)}]"
| 0 | null | 1 | 1 | aca19ed27a751d7d6b0d276e7d2cfbf579fe1f87 | 26,632 | kotlin | Apache License 2.0 |
common/src/main/kotlin/tech/cuda/woden/common/service/dto/CommitmentDTO.kt | cuda-tech | 234,125,581 | false | {"Kotlin": 532433, "JavaScript": 97771, "Vue": 95927, "CSS": 10200, "Dockerfile": 267, "HTML": 208} | /*
* 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 tech.cuda.woden.common.service.dto
import tech.cuda.woden.annotation.pojo.DTO
import tech.cuda.woden.common.service.po.CommitmentPO
import tech.cuda.woden.common.service.po.ContainerPO
import java.time.LocalDateTime
/**
* @author <NAME> <<EMAIL>>
* @since 0.1.0
*/
@DTO(CommitmentPO::class)
data class CommitmentDTO(
val id: Int,
val nodeId: Int,
val content: String,
val message: String,
val createTime: LocalDateTime,
val updateTime: LocalDateTime
) | 0 | Kotlin | 0 | 0 | 2efc2de1cad2646ea129637752b15d868ca13c7d | 1,050 | woden-deprecated | Apache License 2.0 |
compiler/src/test/kotlin/edu/cornell/cs/apl/viaduct/syntax/intermediate/PrettyPrintingTest.kt | apl-cornell | 169,159,978 | false | null | package edu.cornell.cs.apl.viaduct.syntax.intermediate
import edu.cornell.cs.apl.viaduct.PositiveTestProgramProvider
import edu.cornell.cs.apl.viaduct.passes.elaborated
import edu.cornell.cs.apl.viaduct.syntax.surface.ProgramNode
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
internal class PrettyPrintingTest {
@ParameterizedTest
@ArgumentsSource(PositiveTestProgramProvider::class)
fun `intermediate nodes can be printed`(program: ProgramNode) {
program.elaborated().toDocument().print()
}
}
| 26 | Kotlin | 4 | 11 | 14dc0b17e0eb73599f961b3cb3bad35e7007c067 | 581 | viaduct | MIT License |
platform/credential-store/src/macOsKeychainLibrary.kt | androidports | 115,100,208 | false | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ArrayUtilRt
import com.intellij.util.text.nullize
import com.sun.jna.*
import com.sun.jna.ptr.IntByReference
import com.sun.jna.ptr.PointerByReference
import it.unimi.dsi.fastutil.ints.Int2ObjectMap
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
val isMacOsCredentialStoreSupported: Boolean
get() = SystemInfo.isMac && SystemInfo.isIntel64
private const val errSecSuccess = 0
private const val errSecItemNotFound = -25300
private const val errSecInvalidRecord = -67701
// or if Deny clicked on access dialog
private const val errUserNameNotCorrect = -25293
// https://developer.apple.com/documentation/security/1542001-security_framework_result_codes/errsecusercanceled?language=objc
private const val errSecUserCanceled = -128
private const val kSecFormatUnknown = 0
private const val kSecAccountItemAttr = (('a'.toInt() shl 8 or 'c'.toInt()) shl 8 or 'c'.toInt()) shl 8 or 't'.toInt()
internal class KeyChainCredentialStore : CredentialStore {
companion object {
private val library = Native.load("Security", MacOsKeychainLibrary::class.java)
private fun findGenericPassword(serviceName: ByteArray, accountName: String?): Credentials? {
val accountNameBytes = accountName?.toByteArray()
val passwordSize = IntArray(1)
val passwordRef = PointerByReference()
val itemRef = PointerByReference()
val errorCode = checkForError("find", library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes?.size ?: 0, accountNameBytes, passwordSize, passwordRef, itemRef))
if (errorCode == errSecUserCanceled) {
return ACCESS_TO_KEY_CHAIN_DENIED
}
if (errorCode == errUserNameNotCorrect) {
return CANNOT_UNLOCK_KEYCHAIN
}
val pointer = passwordRef.value ?: return null
val password = OneTimeString(pointer.getByteArray(0, passwordSize.get(0)))
library.SecKeychainItemFreeContent(null, pointer)
var effectiveAccountName = accountName
if (effectiveAccountName == null) {
val attributes = PointerByReference()
checkForError("SecKeychainItemCopyAttributesAndData", library.SecKeychainItemCopyAttributesAndData(itemRef.value!!, SecKeychainAttributeInfo(kSecAccountItemAttr), null, attributes, null, null))
val attributeList = SecKeychainAttributeList(attributes.value)
try {
attributeList.read()
effectiveAccountName = readAttributes(attributeList).get(kSecAccountItemAttr)
}
finally {
library.SecKeychainItemFreeAttributesAndData(attributeList, null)
}
}
return Credentials(effectiveAccountName, password)
}
private fun checkForError(message: String, code: Int): Int {
if (code == errSecSuccess || code == errSecItemNotFound) {
return code
}
val translated = library.SecCopyErrorMessageString(code, null)
val builder = StringBuilder(message).append(": ")
if (translated == null) {
builder.append(code)
}
else {
val buf = CharArray(library.CFStringGetLength(translated).toInt())
for (i in buf.indices) {
buf[i] = library.CFStringGetCharacterAtIndex(translated, i.toLong())
}
library.CFRelease(translated)
builder.append(buf).append(" (").append(code).append(')')
}
if (code == errUserNameNotCorrect || code == errSecUserCanceled || code == -25299 /* The specified item already exists in the keychain */) {
LOG.warn(builder.toString())
}
else {
LOG.error(builder.toString())
}
return code
}
}
override fun get(attributes: CredentialAttributes): Credentials? {
return findGenericPassword(attributes.serviceName.toByteArray(), attributes.userName.nullize())
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
val serviceName = attributes.serviceName.toByteArray()
if (credentials.isEmpty()) {
val itemRef = PointerByReference()
val userName = attributes.userName.nullize()?.toByteArray()
val code = library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, null, null, itemRef)
if (code == errSecItemNotFound || code == errSecInvalidRecord) {
return
}
checkForError("find (for delete)", code)
itemRef.value?.let {
checkForError("delete", library.SecKeychainItemDelete(it))
library.CFRelease(it)
}
return
}
val userName = (attributes.userName.nullize() ?: credentials!!.userName)?.toByteArray()
val searchUserName = if (attributes.serviceName == SERVICE_NAME_PREFIX) userName else null
val itemRef = PointerByReference()
val library = library
checkForError("find (for save)", library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, searchUserName?.size ?: 0, searchUserName, null, null, itemRef))
val password = if (attributes.isPasswordMemoryOnly || credentials!!.password == null) null else credentials.password!!.toByteArray(false)
val pointer = itemRef.value
if (pointer == null) {
checkForError("save (new)", library.SecKeychainAddGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, password?.size ?: 0, password))
}
else {
val attribute = SecKeychainAttribute()
attribute.tag = kSecAccountItemAttr
attribute.length = userName?.size ?: 0
if (userName != null && userName.isNotEmpty()) {
val userNamePointer = Memory(userName.size.toLong())
userNamePointer.write(0, userName, 0, userName.size)
attribute.data = userNamePointer
}
val attributeList = SecKeychainAttributeList()
attributeList.count = 1
attribute.write()
attributeList.attr = attribute.pointer
checkForError("save (update)", library.SecKeychainItemModifyContent(pointer, attributeList, password?.size ?: 0, password ?: ArrayUtilRt.EMPTY_BYTE_ARRAY))
library.CFRelease(pointer)
}
password?.fill(0)
}
}
// https://developer.apple.com/library/mac/documentation/Security/Reference/keychainservices/index.html
// It is very, very important to use CFRelease/SecKeychainItemFreeContent You must do it, otherwise you can get "An invalid record was encountered."
@Suppress("FunctionName")
private interface MacOsKeychainLibrary : Library {
fun SecKeychainAddGenericPassword(keychain: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray?, passwordLength: Int, passwordData: ByteArray?, itemRef: Pointer? = null): Int
fun SecKeychainItemModifyContent(itemRef: Pointer, /*SecKeychainAttributeList**/ attrList: Any?, length: Int, data: ByteArray?): Int
fun SecKeychainFindGenericPassword(keychainOrArray: Pointer?,
serviceNameLength: Int,
serviceName: ByteArray,
accountNameLength: Int,
accountName: ByteArray?,
passwordLength: IntArray?,
passwordData: PointerByReference?,
itemRef: PointerByReference?): Int
fun SecKeychainItemCopyAttributesAndData(itemRef: Pointer,
info: SecKeychainAttributeInfo,
itemClass: IntByReference?,
attrList: PointerByReference,
length: IntByReference?,
outData: PointerByReference?): Int
fun SecKeychainItemFreeAttributesAndData(attrList: SecKeychainAttributeList, data: Pointer?): Int
fun SecKeychainItemDelete(itemRef: Pointer): Int
fun /*CFString*/ SecCopyErrorMessageString(status: Int, reserved: Pointer?): Pointer?
// http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html
fun /*CFIndex*/ CFStringGetLength(/*CFStringRef*/ theString: Pointer): Long
fun /*UniChar*/ CFStringGetCharacterAtIndex(/*CFStringRef*/ theString: Pointer, /*CFIndex*/ idx: Long): Char
fun CFRelease(/*CFTypeRef*/ cf: Pointer)
fun SecKeychainItemFreeContent(/*SecKeychainAttributeList*/attrList: Pointer?, data: Pointer?)
}
// must be not private
@Structure.FieldOrder("count", "tag", "format")
internal class SecKeychainAttributeInfo : Structure() {
@JvmField var count: Int = 0
@JvmField var tag: Pointer? = null
@JvmField var format: Pointer? = null
}
@Suppress("FunctionName")
private fun SecKeychainAttributeInfo(vararg ids: Int): SecKeychainAttributeInfo {
val info = SecKeychainAttributeInfo()
val length = ids.size
info.count = length
val size = length shl 2
val tag = Memory((size shl 1).toLong())
val format = tag.share(size.toLong(), size.toLong())
info.tag = tag
info.format = format
var offset = 0
for (id in ids) {
tag.setInt(offset.toLong(), id)
format.setInt(offset.toLong(), kSecFormatUnknown)
offset += 4
}
return info
}
// must be not private
@Structure.FieldOrder("count", "attr")
internal class SecKeychainAttributeList : Structure {
@JvmField var count = 0
@JvmField var attr: Pointer? = null
constructor(p: Pointer) : super(p)
constructor() : super()
}
// must be not private
@Structure.FieldOrder("tag", "length", "data")
internal class SecKeychainAttribute : Structure, Structure.ByReference {
@JvmField var tag = 0
@JvmField var length = 0
@JvmField var data: Pointer? = null
internal constructor(p: Pointer) : super(p)
internal constructor() : super()
}
private fun readAttributes(list: SecKeychainAttributeList): Int2ObjectMap<String> {
val map = Int2ObjectOpenHashMap<String>()
val attrList = SecKeychainAttribute(list.attr!!)
attrList.read()
@Suppress("UNCHECKED_CAST")
for (attr in attrList.toArray(list.count) as Array<SecKeychainAttribute>) {
val data = attr.data ?: continue
map.put(attr.tag, String(data.getByteArray(0, attr.length)))
}
return map
}
| 6 | null | 5162 | 4 | 6e4f7135c5843ed93c15a9782f29e4400df8b068 | 10,412 | intellij-community | Apache License 2.0 |
compiler/backend/src/org/jetbrains/kotlin/codegen/PropertyReferenceCodegen.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.ReflectionTypes
import org.jetbrains.kotlin.codegen.AsmUtil.method
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.context.ClassContext
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.PropertyImportedFromObject
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.isUnderlyingPropertyOfInlineClass
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.*
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.sure
import org.jetbrains.org.objectweb.asm.Opcodes.*
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.commons.Method
class PropertyReferenceCodegen(
state: GenerationState,
parentCodegen: MemberCodegen<*>,
context: ClassContext,
expression: KtElement,
classBuilder: ClassBuilder,
private val localVariableDescriptorForReference: VariableDescriptor,
private val target: VariableDescriptor,
private val boundReceiverJvmKotlinType: JvmKotlinType?
) : MemberCodegen<KtElement>(state, parentCodegen, context, expression, classBuilder) {
private val boundReceiverType = boundReceiverJvmKotlinType?.type
private val classDescriptor = context.contextDescriptor
private val asmType = typeMapper.mapClass(classDescriptor)
// e.g. MutablePropertyReference0
private val superAsmType = typeMapper.mapClass(classDescriptor.getSuperClassNotAny().sure { "No super class for $classDescriptor" })
private val isLocalDelegatedProperty = target is LocalVariableDescriptor
private val getFunction =
if (isLocalDelegatedProperty)
(localVariableDescriptorForReference as VariableDescriptorWithAccessors).getter!!
else
findGetFunction(localVariableDescriptorForReference).original
// e.g. mutableProperty0(Lkotlin/jvm/internal/MutablePropertyReference0;)Lkotlin/reflect/KMutableProperty0;
private val wrapperMethod = getWrapperMethodForPropertyReference(target, getFunction.valueParameters.size)
private val closure = bindingContext.get(CodegenBinding.CLOSURE, classDescriptor)!!.apply {
assert((capturedReceiverFromOuterContext != null) == (boundReceiverType != null)) {
"Bound property reference can only be generated with the type of the receiver. " +
"Captured type = $capturedReceiverFromOuterContext, actual type = $boundReceiverType"
}
}
private val constructorArgs =
ClosureCodegen.calculateConstructorParameters(typeMapper, state.languageVersionSettings, closure, asmType).apply {
assert(size <= 1) { "Bound property reference should capture only one value: $this" }
}
private val constructor = method("<init>", Type.VOID_TYPE, *constructorArgs.map { it.fieldType }.toTypedArray())
override fun generateDeclaration() {
v.defineClass(
element,
state.classFileVersion,
ACC_FINAL or ACC_SUPER or
DescriptorAsmUtil.getVisibilityAccessFlagForClass(classDescriptor) or
DescriptorAsmUtil.getSyntheticAccessFlagForLambdaClass(classDescriptor),
asmType.internalName,
null,
superAsmType.internalName,
emptyArray()
)
v.visitSource(element.containingFile.name, null)
}
// TODO: ImplementationBodyCodegen.markLineNumberForSyntheticFunction?
override fun generateBody() {
if (JvmCodegenUtil.isConst(closure)) {
generateConstInstance(asmType, wrapperMethod.returnType)
} else {
DescriptorAsmUtil.genClosureFields(closure, v, typeMapper, state.languageVersionSettings)
}
generateConstructor()
if (!isOptimizedPropertyReferenceSupertype(superAsmType)) {
generateMethod("property reference getName", ACC_PUBLIC, method("getName", JAVA_STRING_TYPE)) {
aconst(target.name.asString())
}
generateMethod("property reference getSignature", ACC_PUBLIC, method("getSignature", JAVA_STRING_TYPE)) {
generatePropertyReferenceSignature(this, target, state)
}
generateMethod("property reference getOwner", ACC_PUBLIC, method("getOwner", K_DECLARATION_CONTAINER_TYPE)) {
generateCallableReferenceDeclarationContainer(this, target, state)
}
}
if (!isLocalDelegatedProperty) {
generateAccessors()
}
}
private fun generateConstructor() {
generateMethod("property reference init", 0, constructor) {
val shouldHaveBoundReferenceReceiver = closure.isForBoundCallableReference()
val receiverIndexAndFieldInfo = generateClosureFieldsInitializationFromParameters(closure, constructorArgs)
load(0, OBJECT_TYPE)
val superCtorArgTypes = mutableListOf<Type>()
if (receiverIndexAndFieldInfo != null) {
val (receiverIndex, receiverFieldInfo) = receiverIndexAndFieldInfo
loadBoundReferenceReceiverParameter(receiverIndex, receiverFieldInfo.fieldType, receiverFieldInfo.fieldKotlinType)
superCtorArgTypes.add(OBJECT_TYPE)
} else {
assert(!shouldHaveBoundReferenceReceiver) { "No bound reference receiver in constructor parameters: $constructorArgs" }
}
if (isOptimizedPropertyReferenceSupertype(superAsmType)) {
generateCallableReferenceDeclarationContainerClass(this, target, state)
aconst(target.name.asString())
generatePropertyReferenceSignature(this, target, state)
aconst(getCallableReferenceTopLevelFlag(target))
superCtorArgTypes.add(JAVA_CLASS_TYPE)
superCtorArgTypes.add(JAVA_STRING_TYPE)
superCtorArgTypes.add(JAVA_STRING_TYPE)
superCtorArgTypes.add(Type.INT_TYPE)
}
invokespecial(
superAsmType.internalName, "<init>",
Type.getMethodDescriptor(Type.VOID_TYPE, *superCtorArgTypes.toTypedArray()), false
)
}
}
private fun generateAccessors() {
val getFunction = findGetFunction(localVariableDescriptorForReference)
val getImpl = createFakeOpenDescriptor(getFunction, classDescriptor)
functionCodegen.generateMethod(
JvmDeclarationOrigin.NO_ORIGIN,
getImpl,
PropertyReferenceGenerationStrategy(
true,
getFunction,
target,
asmType,
boundReceiverJvmKotlinType,
element,
state,
false
)
)
if (!ReflectionTypes.isNumberedKMutablePropertyType(localVariableDescriptorForReference.type)) return
val setFunction = localVariableDescriptorForReference.type.memberScope.getContributedFunctions(
OperatorNameConventions.SET,
NoLookupLocation.FROM_BACKEND
).single()
val setImpl = createFakeOpenDescriptor(setFunction, classDescriptor)
functionCodegen.generateMethod(
JvmDeclarationOrigin.NO_ORIGIN,
setImpl,
PropertyReferenceGenerationStrategy(
false,
setFunction,
target,
asmType,
boundReceiverJvmKotlinType,
element,
state,
false
)
)
}
private fun generateMethod(debugString: String, access: Int, method: Method, generate: InstructionAdapter.() -> Unit) {
v.generateMethod(debugString, access, method, element, JvmDeclarationOrigin.NO_ORIGIN, state, generate)
}
override fun generateKotlinMetadataAnnotation() {
writeSyntheticClassMetadata(v, state)
}
fun putInstanceOnStack(receiverValue: StackValue?): StackValue {
return StackValue.operation(wrapperMethod.returnType) { iv ->
if (JvmCodegenUtil.isConst(closure)) {
assert(receiverValue == null) { "No receiver expected for unbound property reference: $classDescriptor" }
iv.getstatic(asmType.internalName, JvmAbi.INSTANCE_FIELD, wrapperMethod.returnType.descriptor)
} else {
assert(receiverValue != null) { "Receiver expected for bound property reference: $classDescriptor" }
iv.anew(asmType)
iv.dup()
receiverValue!!.put(receiverValue.type, receiverValue.kotlinType, iv)
iv.invokespecial(asmType.internalName, "<init>", constructor.descriptor, false)
}
}
}
companion object {
@JvmField
val ANY_SUBSTITUTOR = TypeSubstitutor.create(object : TypeSubstitution() {
override fun get(key: KotlinType): TypeProjection? {
if (KotlinBuiltIns.isUnit(key)) {
return TypeProjectionImpl(key)
}
return TypeProjectionImpl(key.builtIns.nullableAnyType)
}
})
@JvmStatic
fun getWrapperMethodForPropertyReference(property: VariableDescriptor, receiverCount: Int): Method {
return when (receiverCount) {
2 -> when {
property.isVar -> method("mutableProperty2", K_MUTABLE_PROPERTY2_TYPE, MUTABLE_PROPERTY_REFERENCE2)
else -> method("property2", K_PROPERTY2_TYPE, PROPERTY_REFERENCE2)
}
1 -> when {
property.isVar -> method("mutableProperty1", K_MUTABLE_PROPERTY1_TYPE, MUTABLE_PROPERTY_REFERENCE1)
else -> method("property1", K_PROPERTY1_TYPE, PROPERTY_REFERENCE1)
}
else -> when {
property.isVar -> method("mutableProperty0", K_MUTABLE_PROPERTY0_TYPE, MUTABLE_PROPERTY_REFERENCE0)
else -> method("property0", K_PROPERTY0_TYPE, PROPERTY_REFERENCE0)
}
}
}
@JvmStatic
fun createFakeOpenDescriptor(getFunction: FunctionDescriptor, classDescriptor: ClassDescriptor): FunctionDescriptor {
val copy = getFunction.original.copy(classDescriptor, Modality.OPEN, getFunction.visibility, getFunction.kind, false)
return copy.substitute(ANY_SUBSTITUTOR)!!
}
@JvmStatic
fun findGetFunction(localVariableDescriptorForReference: VariableDescriptor) =
localVariableDescriptorForReference.type.memberScope.getContributedFunctions(
OperatorNameConventions.GET,
NoLookupLocation.FROM_BACKEND
).single()
}
class PropertyReferenceGenerationStrategy(
private val isGetter: Boolean,
private val originalFunctionDesc: FunctionDescriptor,
private val target: VariableDescriptor,
private val asmType: Type,
boundReceiverJvmKotlinType: JvmKotlinType?,
private val expression: KtElement,
state: GenerationState,
private val isInliningStrategy: Boolean
) :
FunctionGenerationStrategy.CodegenBased(state) {
private val boundReceiverType = boundReceiverJvmKotlinType?.type
private val boundReceiverKotlinType = boundReceiverJvmKotlinType?.kotlinType
private val expectedReceiverKotlinType =
target.extensionReceiverParameter?.type
?: (target.containingDeclaration as? ClassDescriptor)?.defaultType
private val expectedReceiverType =
if (expectedReceiverKotlinType != null)
state.typeMapper.mapType(expectedReceiverKotlinType)
else {
assert(boundReceiverType == null) {
"$target: no expected receiver, boundReceiverType is $boundReceiverType"
}
null
}
override fun doGenerateBody(codegen: ExpressionCodegen, signature: JvmMethodSignature) {
val v = codegen.v
val typeMapper = state.typeMapper
val targetKotlinType = target.type
if (target is PropertyImportedFromObject) {
val containingObject = target.containingObject
StackValue
.singleton(containingObject, typeMapper)
.put(typeMapper.mapClass(containingObject), containingObject.defaultType, v)
}
if (boundReceiverType != null) {
capturedBoundReferenceReceiver(asmType, boundReceiverType, boundReceiverKotlinType, isInliningStrategy)
.put(expectedReceiverType!!, expectedReceiverKotlinType, v)
} else {
val receivers = originalFunctionDesc.valueParameters.dropLast(if (isGetter) 0 else 1)
receivers.forEachIndexed { i, valueParameterDescriptor ->
val nullableAny = valueParameterDescriptor.builtIns.nullableAnyType
StackValue.local(i + 1, OBJECT_TYPE, nullableAny)
.put(typeMapper.mapType(valueParameterDescriptor), valueParameterDescriptor.type, v)
}
}
val value = when {
target is LocalVariableDescriptor -> codegen.findLocalOrCapturedValue(target)!!
target.isUnderlyingPropertyOfInlineClass() -> {
if (expectedReceiverType == null)
throw AssertionError("$target: boundReceiverType=$boundReceiverType, expectedReceiverType is null")
val receiver =
if (boundReceiverType != null)
StackValue.onStack(expectedReceiverType, expectedReceiverKotlinType)
else
StackValue.none()
StackValue.underlyingValueOfInlineClass(typeMapper.mapType(targetKotlinType), targetKotlinType, receiver)
}
else -> codegen.intermediateValueForProperty(target as PropertyDescriptor, false, null, StackValue.none())
}
codegen.markStartLineNumber(expression)
if (isGetter) {
value.put(OBJECT_TYPE, targetKotlinType, v)
} else {
value.store(
StackValue.local(
codegen.frameMap.getIndex(
codegen.context.functionDescriptor.valueParameters.last()
),
OBJECT_TYPE, targetKotlinType
),
v
)
}
v.areturn(signature.returnType)
}
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 16,188 | kotlin | Apache License 2.0 |
converter/src/main/java/com/epicadk/hapiprotoconverter/converter/AdverseEventConverter.kt | epicadk | 402,074,793 | false | {"Kotlin": 2405480} | package com.epicadk.hapiprotoconverter.converter
import com.epicadk.hapiprotoconverter.converter.CodeableConceptConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.CodeableConceptConverter.toProto
import com.epicadk.hapiprotoconverter.converter.DateTimeConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.DateTimeConverter.toProto
import com.epicadk.hapiprotoconverter.converter.ExtensionConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.ExtensionConverter.toProto
import com.epicadk.hapiprotoconverter.converter.IdentifierConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.IdentifierConverter.toProto
import com.epicadk.hapiprotoconverter.converter.MetaConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.MetaConverter.toProto
import com.epicadk.hapiprotoconverter.converter.NarrativeConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.NarrativeConverter.toProto
import com.epicadk.hapiprotoconverter.converter.ReferenceConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.ReferenceConverter.toProto
import com.epicadk.hapiprotoconverter.converter.StringConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.StringConverter.toProto
import com.epicadk.hapiprotoconverter.converter.UriConverter.toHapi
import com.epicadk.hapiprotoconverter.converter.UriConverter.toProto
import com.google.fhir.r4.core.AdverseEvent
import com.google.fhir.r4.core.AdverseEvent.SuspectEntity
import com.google.fhir.r4.core.AdverseEventActualityCode
import com.google.fhir.r4.core.Id
import com.google.fhir.r4.core.String
public object AdverseEventConverter {
public fun AdverseEvent.toHapi(): org.hl7.fhir.r4.model.AdverseEvent {
val hapiValue = org.hl7.fhir.r4.model.AdverseEvent()
if (hasId()) {
hapiValue.id = id.value
}
if (hasMeta()) {
hapiValue.setMeta(meta.toHapi())
}
if (hasImplicitRules()) {
hapiValue.setImplicitRulesElement(implicitRules.toHapi())
}
if (hasText()) {
hapiValue.setText(text.toHapi())
}
if (extensionCount > 0) {
hapiValue.setExtension(extensionList.map { it.toHapi() })
}
if (modifierExtensionCount > 0) {
hapiValue.setModifierExtension(modifierExtensionList.map { it.toHapi() })
}
if (hasIdentifier()) {
hapiValue.setIdentifier(identifier.toHapi())
}
if (hasActuality()) {
hapiValue.setActuality(org.hl7.fhir.r4.model.AdverseEvent.AdverseEventActuality.valueOf(actuality.value.name.hapiCodeCheck().replace("_", "")))
}
if (categoryCount > 0) {
hapiValue.setCategory(categoryList.map { it.toHapi() })
}
if (hasEvent()) {
hapiValue.setEvent(event.toHapi())
}
if (hasSubject()) {
hapiValue.setSubject(subject.toHapi())
}
if (hasEncounter()) {
hapiValue.setEncounter(encounter.toHapi())
}
if (hasDate()) {
hapiValue.setDateElement(date.toHapi())
}
if (hasDetected()) {
hapiValue.setDetectedElement(detected.toHapi())
}
if (hasRecordedDate()) {
hapiValue.setRecordedDateElement(recordedDate.toHapi())
}
if (resultingConditionCount > 0) {
hapiValue.setResultingCondition(resultingConditionList.map { it.toHapi() })
}
if (hasLocation()) {
hapiValue.setLocation(location.toHapi())
}
if (hasSeriousness()) {
hapiValue.setSeriousness(seriousness.toHapi())
}
if (hasSeverity()) {
hapiValue.setSeverity(severity.toHapi())
}
if (hasOutcome()) {
hapiValue.setOutcome(outcome.toHapi())
}
if (hasRecorder()) {
hapiValue.setRecorder(recorder.toHapi())
}
if (contributorCount > 0) {
hapiValue.setContributor(contributorList.map { it.toHapi() })
}
if (suspectEntityCount > 0) {
hapiValue.setSuspectEntity(suspectEntityList.map { it.toHapi() })
}
if (subjectMedicalHistoryCount > 0) {
hapiValue.setSubjectMedicalHistory(subjectMedicalHistoryList.map { it.toHapi() })
}
if (referenceDocumentCount > 0) {
hapiValue.setReferenceDocument(referenceDocumentList.map { it.toHapi() })
}
if (studyCount > 0) {
hapiValue.setStudy(studyList.map { it.toHapi() })
}
return hapiValue
}
public fun org.hl7.fhir.r4.model.AdverseEvent.toProto(): AdverseEvent {
val protoValue = AdverseEvent.newBuilder()
if (hasId()) {
protoValue.setId(Id.newBuilder().setValue(id))
}
if (hasMeta()) {
protoValue.setMeta(meta.toProto())
}
if (hasImplicitRules()) {
protoValue.setImplicitRules(implicitRulesElement.toProto())
}
if (hasText()) {
protoValue.setText(text.toProto())
}
if (hasExtension()) {
protoValue.addAllExtension(extension.map { it.toProto() })
}
if (hasModifierExtension()) {
protoValue.addAllModifierExtension(modifierExtension.map { it.toProto() })
}
if (hasIdentifier()) {
protoValue.setIdentifier(identifier.toProto())
}
if (hasActuality()) {
protoValue.setActuality(AdverseEvent.ActualityCode.newBuilder().setValue(AdverseEventActualityCode.Value.valueOf(actuality.toCode().protoCodeCheck().replace("-",
"_").toUpperCase())).build())
}
if (hasCategory()) {
protoValue.addAllCategory(category.map { it.toProto() })
}
if (hasEvent()) {
protoValue.setEvent(event.toProto())
}
if (hasSubject()) {
protoValue.setSubject(subject.toProto())
}
if (hasEncounter()) {
protoValue.setEncounter(encounter.toProto())
}
if (hasDate()) {
protoValue.setDate(dateElement.toProto())
}
if (hasDetected()) {
protoValue.setDetected(detectedElement.toProto())
}
if (hasRecordedDate()) {
protoValue.setRecordedDate(recordedDateElement.toProto())
}
if (hasResultingCondition()) {
protoValue.addAllResultingCondition(resultingCondition.map { it.toProto() })
}
if (hasLocation()) {
protoValue.setLocation(location.toProto())
}
if (hasSeriousness()) {
protoValue.setSeriousness(seriousness.toProto())
}
if (hasSeverity()) {
protoValue.setSeverity(severity.toProto())
}
if (hasOutcome()) {
protoValue.setOutcome(outcome.toProto())
}
if (hasRecorder()) {
protoValue.setRecorder(recorder.toProto())
}
if (hasContributor()) {
protoValue.addAllContributor(contributor.map { it.toProto() })
}
if (hasSuspectEntity()) {
protoValue.addAllSuspectEntity(suspectEntity.map { it.toProto() })
}
if (hasSubjectMedicalHistory()) {
protoValue.addAllSubjectMedicalHistory(subjectMedicalHistory.map { it.toProto() })
}
if (hasReferenceDocument()) {
protoValue.addAllReferenceDocument(referenceDocument.map { it.toProto() })
}
if (hasStudy()) {
protoValue.addAllStudy(study.map { it.toProto() })
}
return protoValue.build()
}
private fun org.hl7.fhir.r4.model.AdverseEvent.AdverseEventSuspectEntityComponent.toProto():
AdverseEvent.SuspectEntity {
val protoValue = AdverseEvent.SuspectEntity.newBuilder()
if (hasId()) {
protoValue.setId(String.newBuilder().setValue(id))
}
if (hasExtension()) {
protoValue.addAllExtension(extension.map { it.toProto() })
}
if (hasModifierExtension()) {
protoValue.addAllModifierExtension(modifierExtension.map { it.toProto() })
}
if (hasInstance()) {
protoValue.setInstance(instance.toProto())
}
if (hasCausality()) {
protoValue.addAllCausality(causality.map { it.toProto() })
}
return protoValue.build()
}
private
fun org.hl7.fhir.r4.model.AdverseEvent.AdverseEventSuspectEntityCausalityComponent.toProto():
AdverseEvent.SuspectEntity.Causality {
val protoValue = AdverseEvent.SuspectEntity.Causality.newBuilder()
if (hasId()) {
protoValue.setId(String.newBuilder().setValue(id))
}
if (hasExtension()) {
protoValue.addAllExtension(extension.map { it.toProto() })
}
if (hasModifierExtension()) {
protoValue.addAllModifierExtension(modifierExtension.map { it.toProto() })
}
if (hasAssessment()) {
protoValue.setAssessment(assessment.toProto())
}
if (hasProductRelatedness()) {
protoValue.setProductRelatedness(productRelatednessElement.toProto())
}
if (hasAuthor()) {
protoValue.setAuthor(author.toProto())
}
if (hasMethod()) {
protoValue.setMethod(method.toProto())
}
return protoValue.build()
}
private fun AdverseEvent.SuspectEntity.toHapi():
org.hl7.fhir.r4.model.AdverseEvent.AdverseEventSuspectEntityComponent {
val hapiValue = org.hl7.fhir.r4.model.AdverseEvent.AdverseEventSuspectEntityComponent()
if (hasId()) {
hapiValue.id = id.value
}
if (extensionCount > 0) {
hapiValue.setExtension(extensionList.map { it.toHapi() })
}
if (modifierExtensionCount > 0) {
hapiValue.setModifierExtension(modifierExtensionList.map { it.toHapi() })
}
if (hasInstance()) {
hapiValue.setInstance(instance.toHapi())
}
if (causalityCount > 0) {
hapiValue.setCausality(causalityList.map { it.toHapi() })
}
return hapiValue
}
private fun AdverseEvent.SuspectEntity.Causality.toHapi():
org.hl7.fhir.r4.model.AdverseEvent.AdverseEventSuspectEntityCausalityComponent {
val hapiValue = org.hl7.fhir.r4.model.AdverseEvent.AdverseEventSuspectEntityCausalityComponent()
if (hasId()) {
hapiValue.id = id.value
}
if (extensionCount > 0) {
hapiValue.setExtension(extensionList.map { it.toHapi() })
}
if (modifierExtensionCount > 0) {
hapiValue.setModifierExtension(modifierExtensionList.map { it.toHapi() })
}
if (hasAssessment()) {
hapiValue.setAssessment(assessment.toHapi())
}
if (hasProductRelatedness()) {
hapiValue.setProductRelatednessElement(productRelatedness.toHapi())
}
if (hasAuthor()) {
hapiValue.setAuthor(author.toHapi())
}
if (hasMethod()) {
hapiValue.setMethod(method.toHapi())
}
return hapiValue
}
}
| 1 | Kotlin | 0 | 3 | 2abe5967a905f6a29ed5736c75e8ffb2cf6d3e78 | 10,144 | hapi-proto-converter | Apache License 2.0 |
json-schema-validator/src/test/kotlin/io/openapiprocessor/jsonschema/schema/DynamicScopeSpec.kt | openapi-processor | 418,185,783 | false | {"Java": 629502, "Kotlin": 243428, "Just": 440} | /*
* Copyright 2022 https://github.com/openapi-processor/openapi-parser
* PDX-License-Identifier: Apache-2.0
*/
package io.openapiprocessor.jsonschema.schema
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.shouldBeSameInstanceAs
import io.kotest.matchers.types.shouldNotBeSameInstanceAs
import io.openapiprocessor.jsonschema.support.Uris.*
import java.net.URI
class DynamicScopeSpec : StringSpec({
isolationMode = IsolationMode.InstancePerTest
val registry = ReferenceRegistry()
fun createSchema (id: String? = null, recursiveAnchor: Boolean? = null): JsonSchema {
val uri = if(id != null) createUri(id) else emptyUri()
val map = mutableMapOf<String, Any>()
if (id != null) {
map["\$id"] = id
}
val scope = Scope.createScope(uri, map, SchemaVersion.Draft201909)
return if (recursiveAnchor == null) {
registry.addReference(Ref(scope), scope, map)
JsonSchemaObject(
map,
JsonSchemaContext(scope, registry)
)
} else {
map["\$recursiveAnchor"] = recursiveAnchor
registry.addDynamicReference(Ref(scope, "#"), scope, map)
JsonSchemaObject(
map,
JsonSchemaContext(scope, registry)
)
}
}
fun createSchema2 (id: String? = null, dynamicAnchor: String? = null): JsonSchema {
val uri = if(id != null) createUri(id) else emptyUri()
val map = mutableMapOf<String, Any>()
if (id != null) {
map["\$id"] = id
}
val scope = Scope.createScope(uri, map, SchemaVersion.Draft202012)
return if (dynamicAnchor == null) {
registry.addReference(Ref(scope), scope, map)
JsonSchemaObject(
map,
JsonSchemaContext(scope, registry)
)
} else {
map["\$dynamicAnchor"] = dynamicAnchor
registry.addDynamicReference(
Ref(
scope,
dynamicAnchor
), scope, map)
JsonSchemaObject(
map,
JsonSchemaContext(scope, registry)
)
}
}
"create scope from schema without id" {
val dynamicScope = DynamicScope(createSchema())
val found = dynamicScope.findScope(URI.create("#"))
found.shouldBeNull()
}
"adding schema without id should not change dynamic scope" {
val dynamicScope = DynamicScope(createSchema())
val schema = createSchema()
val scope = dynamicScope.add(schema)
dynamicScope.shouldBeSameInstanceAs(scope)
}
"adding schema with id should create new dynamic scope" {
val dynamicScope = DynamicScope(createSchema())
val scope = dynamicScope.add(createSchema("https://localhost/foo"))
scope.shouldNotBeSameInstanceAs(dynamicScope)
}
"if current id has no dynamic anchor use current id" {
var dynamicScope = DynamicScope(createSchema())
dynamicScope = dynamicScope.add(createSchema("https://localhost/bar"))
val scope = dynamicScope.findScope(URI.create("#"))
scope.shouldBeNull()
}
"if current id has dynamic anchor move up to outermost scope" {
var dynamicScope = DynamicScope(createSchema())
dynamicScope = dynamicScope.add(createSchema("https://localhost/last", true))
dynamicScope = dynamicScope.add(createSchema("https://localhost/skip", true))
dynamicScope = dynamicScope.add(createSchema("https://localhost/current", true))
val scope = dynamicScope.findScope(URI.create("#"))
scope.shouldBe(URI.create("https://localhost/last"))
}
"if current id has dynamic anchor move up to outermost scope and ignore scopes without anchor" {
var dynamicScope = DynamicScope(createSchema())
dynamicScope = dynamicScope.add(createSchema("https://localhost/other", null))
dynamicScope = dynamicScope.add(createSchema("https://localhost/last", true))
dynamicScope = dynamicScope.add(createSchema("https://localhost/skip0", null))
dynamicScope = dynamicScope.add(createSchema("https://localhost/skip1", true))
dynamicScope = dynamicScope.add(createSchema("https://localhost/skip2", null))
dynamicScope = dynamicScope.add(createSchema("https://localhost/current", true))
val scope = dynamicScope.findScope(URI.create("#"))
scope.shouldBe(URI.create("https://localhost/last"))
}
})
| 15 | Java | 1 | 12 | 99f9ff6254ce4dc73407c383d54ad36a780460a5 | 4,726 | openapi-parser | Apache License 2.0 |
substrate-sdk-android/src/main/java/io/novasama/substrate_sdk_android/scale/Delegate.kt | novasamatech | 429,839,517 | false | null | package io.novasama.substrate_sdk_android.scale
import io.novasama.substrate_sdk_android.scale.dataType.DataType
import io.novasama.substrate_sdk_android.scale.dataType.optional
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
class NonNullFieldDelegate<S : Schema<S>, T>(
private val dataType: DataType<T>,
private val schema: S,
default: T? = null
) : ReadOnlyProperty<Schema<S>, Field<T>> {
private var field: Field<T> = schema.field(dataType, default)
override fun getValue(thisRef: Schema<S>, property: KProperty<*>) = field
fun optional(): NullableFieldDelegate<S, T> {
schema.fields.remove(field)
return NullableFieldDelegate(optional(dataType), schema, field.defaultValue)
}
}
class NullableFieldDelegate<S : Schema<S>, T>(
dataType: optional<T>,
schema: S,
default: T? = null
) :
ReadOnlyProperty<Schema<S>, Field<T?>> {
private var field: Field<T?> = schema.nullableField(dataType, default)
override fun getValue(thisRef: Schema<S>, property: KProperty<*>) = field
}
| 3 | null | 7 | 9 | 8deb9bcec9a5d9d74c509ccc6393cfd0b4ef7144 | 1,079 | substrate-sdk-android | Apache License 2.0 |
common/src/main/kotlin/com/jmsoftware/maf/common/domain/authcenter/permission/PermissionType.kt | johnnymillergh | 240,563,247 | false | null | package com.jmsoftware.maf.common.domain.authcenter.permission
import com.jmsoftware.maf.common.util.logger
/**
* # PermissionType
*
* Change description here
*
* @author <NAME> (锺俊), e-mail: <EMAIL>, date: 4/16/22 6:44 PM
*/
enum class PermissionType(val type: Byte, val description: String) {
/**
* Controller
*/
CONTROLLER(0.toByte(), "Controller"),
/**
* Page
*/
PAGE(1.toByte(), "Page"),
/**
* Button
*/
BUTTON(2.toByte(), "Button (API)");
companion object {
private val log = logger()
fun getByType(type: Byte): PermissionType? {
var permissionType: PermissionType? = null
val values = values()
for (pt in values) {
if (pt.type == type) {
permissionType = pt
}
}
return permissionType
}
/**
* Get enum by name
*
* @param name enum name
* @return enum
*/
fun getByName(name: String): PermissionType? {
return try {
valueOf(name)
} catch (e: IllegalArgumentException) {
log.error("Invalid enum name: $name", e)
null
}
}
}
}
| 1 | Kotlin | 4 | 11 | 67917520e69c3f2a47fdd06817e9421cd4d82159 | 1,291 | muscle-and-fitness-server | Apache License 2.0 |
app/src/main/java/com/yabancikelimedefteri/presentation/settings/models/ColorSchemeItem.kt | AhmetOcak | 621,942,001 | false | {"Kotlin": 215272} | package com.yabancikelimedefteri.presentation.settings.models
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.yabancikelimedefteri.core.ui.theme.color_schemes.CustomColorScheme
import com.yabancikelimedefteri.core.ui.theme.color_schemes.NatureColorScheme
import com.yabancikelimedefteri.core.ui.theme.color_schemes.NeonColorScheme
import com.yabancikelimedefteri.core.ui.theme.color_schemes.PinkColorScheme
import com.yabancikelimedefteri.core.ui.theme.color_schemes.RedColorScheme
import com.yabancikelimedefteri.core.ui.theme.color_schemes.SeaColorScheme
import com.yabancikelimedefteri.domain.model.datastore.ColorSchemeKeys
@Composable
fun ColorSchemesSettingItem(
nameId: Int,
icon: ImageVector,
onClick: (ColorSchemeKeys) -> Unit,
currentScheme: CustomColorScheme,
isDarkTheme: Boolean
) {
Card(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 24.dp, horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(imageVector = icon, contentDescription = null)
Text(text = stringResource(id = nameId))
}
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
colorSchemes.forEach { scheme ->
ColorScheme(
onClick = onClick,
schemeType = scheme,
isCurrentScheme = currentScheme == scheme,
isDarkTheme = isDarkTheme
)
}
}
}
}
}
@Composable
private fun ColorScheme(
isCurrentScheme: Boolean,
onClick: (ColorSchemeKeys) -> Unit,
schemeType: CustomColorScheme,
isDarkTheme: Boolean
) {
val scheme = if (isDarkTheme) schemeType.darkColorScheme else schemeType.lightColorScheme
val brush = Brush.linearGradient(
listOf(
scheme.primary,
scheme.secondary,
scheme.onSurfaceVariant,
scheme.background
)
)
Card(
modifier = Modifier.size(32.dp),
onClick = {
onClick(
when (schemeType) {
is NeonColorScheme -> ColorSchemeKeys.NEON
is NatureColorScheme -> ColorSchemeKeys.NATURE
is RedColorScheme -> ColorSchemeKeys.RED
is SeaColorScheme -> ColorSchemeKeys.SEA
else -> ColorSchemeKeys.PINK
}
)
},
shape = CircleShape,
border = if (isCurrentScheme) BorderStroke(2.dp, MaterialTheme.colorScheme.error) else null
) {
Canvas(
modifier = Modifier.fillMaxSize(),
onDraw = {
drawCircle(brush)
}
)
}
}
private val colorSchemes = listOf(
NeonColorScheme,
NatureColorScheme,
PinkColorScheme,
SeaColorScheme,
RedColorScheme
) | 2 | Kotlin | 0 | 2 | 1f02241c6fe9417a1d5b77ce0261ac9e85e02fa4 | 4,227 | YabanciKelimeDefterim | MIT License |
mylibrary/src/main/java/id/indosw/igdownloader/util/ClipboardListener.kt | SWRevo | 336,055,943 | false | null | package id.indosw.igdownloader.util
import android.content.ClipboardManager.OnPrimaryClipChangedListener
abstract class ClipboardListener : OnPrimaryClipChangedListener | 3 | null | 5 | 6 | b551aa7c4538ad14e401e4b9601ae2935c835319 | 170 | InstagramDownloader | Apache License 2.0 |
embrace-android-features/src/main/kotlin/io/embrace/android/embracesdk/internal/anr/NoOpAnrService.kt | embrace-io | 704,537,857 | false | {"Kotlin": 2879745, "C": 189341, "Java": 162931, "C++": 13140, "CMake": 4261} | package io.embrace.android.embracesdk.internal.anr
import io.embrace.android.embracesdk.internal.payload.AnrInterval
internal class NoOpAnrService : AnrService {
override fun getCapturedData(): List<AnrInterval> {
return emptyList()
}
override fun handleCrash(crashId: String) {
}
override fun startAnrCapture() {
}
override fun addBlockedThreadListener(listener: BlockedThreadListener) {
}
override fun close() {
}
override fun cleanCollections() {
}
}
| 23 | Kotlin | 8 | 134 | 06fb424ba2746c22e8e47e549a9f00ae8f85d72d | 518 | embrace-android-sdk | Apache License 2.0 |
settings-sharedpreferences-encryption/src/sharedTest/java/de/charlex/settings/sharedpreferences/encryption/SettingsEncryptionTest.kt | ch4rl3x | 309,776,447 | false | {"Kotlin": 82402} | package de.charlex.settings.sharedpreferences.encryption
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test
abstract class SettingsEncryptionTest {
lateinit var settings: EncryptedSettings
@Test
fun test_Int_Settings() {
settings.put(EncryptedPreferences.PreferenceInt, EncryptedPreferences.PreferenceInt.defaultValue)
assertEquals(1, settings.get(EncryptedPreferences.PreferenceInt))
settings.put(EncryptedPreferences.PreferenceInt, 10)
assertEquals(10, settings.get(EncryptedPreferences.PreferenceInt))
}
@Test
fun test_String_Settings() {
settings.put(EncryptedPreferences.PreferenceString, EncryptedPreferences.PreferenceString.defaultValue)
assertEquals("default", settings.get(EncryptedPreferences.PreferenceString))
settings.put(EncryptedPreferences.PreferenceString, "test")
assertEquals("test", settings.get(EncryptedPreferences.PreferenceString))
}
@Test
fun test_Float_Settings() {
settings.put(EncryptedPreferences.PreferenceFloat, EncryptedPreferences.PreferenceFloat.defaultValue)
assertEquals(1.1f, settings.get(EncryptedPreferences.PreferenceFloat))
settings.put(EncryptedPreferences.PreferenceFloat, 2.2f)
assertEquals(2.2f, settings.get(EncryptedPreferences.PreferenceFloat))
}
@Test
fun test_Long_Settings() {
settings.put(EncryptedPreferences.PreferenceLong, EncryptedPreferences.PreferenceLong.defaultValue)
assertEquals(1L, settings.get(EncryptedPreferences.PreferenceLong))
settings.put(EncryptedPreferences.PreferenceLong, 2L)
assertEquals(2L, settings.get(EncryptedPreferences.PreferenceLong))
}
@Test
fun test_Boolean_Settings() {
settings.put(EncryptedPreferences.PreferenceBoolean, EncryptedPreferences.PreferenceBoolean.defaultValue)
assertEquals(true, settings.get(EncryptedPreferences.PreferenceBoolean))
settings.put(EncryptedPreferences.PreferenceBoolean, false)
assertEquals(false, settings.get(EncryptedPreferences.PreferenceBoolean))
}
@Test
fun test_StringSet_Settings() {
settings.put(EncryptedPreferences.PreferenceStringSet, EncryptedPreferences.PreferenceStringSet.defaultValue)
assertArrayEquals(setOf("Element 1", "Element 2").toTypedArray(), settings.get(EncryptedPreferences.PreferenceStringSet).toTypedArray())
settings.put(EncryptedPreferences.PreferenceStringSet, setOf("Element 1a", "Element 2b", "Element 3c"))
assertArrayEquals(setOf("Element 1a", "Element 2b", "Element 3c").toTypedArray(), settings.get(EncryptedPreferences.PreferenceStringSet).toTypedArray())
}
@Test
fun test_Enum_Settings() {
settings.put(EncryptedPreferences.PreferenceEnumStringKey, EncryptedPreferences.PreferenceEnumStringKey.defaultValue)
assertEquals(StringKeyEnum.Value2, settings.get(EncryptedPreferences.PreferenceEnumStringKey))
settings.put(EncryptedPreferences.PreferenceEnumStringKey, StringKeyEnum.Value1)
assertEquals(StringKeyEnum.Value1, settings.get(EncryptedPreferences.PreferenceEnumStringKey))
}
@Test
fun test_Enum_Int_Key_Settings() {
settings.put(EncryptedPreferences.PreferenceEnumIntKey, EncryptedPreferences.PreferenceEnumIntKey.defaultValue)
assertEquals(IntKeyEnum.Value2, settings.get(EncryptedPreferences.PreferenceEnumIntKey))
settings.put(EncryptedPreferences.PreferenceEnumIntKey, IntKeyEnum.Value1)
assertEquals(IntKeyEnum.Value1, settings.get(EncryptedPreferences.PreferenceEnumIntKey))
}
@Test
fun test_Enum_Ordinal_Key_Settings() {
settings.put(EncryptedPreferences.PreferenceEnumOrdinalKey, EncryptedPreferences.PreferenceEnumOrdinalKey.defaultValue)
assertEquals(Enum.Value2, settings.get(EncryptedPreferences.PreferenceEnumOrdinalKey))
settings.put(EncryptedPreferences.PreferenceEnumOrdinalKey, Enum.Value1)
assertEquals(Enum.Value1, settings.get(EncryptedPreferences.PreferenceEnumOrdinalKey))
}
@Test
fun test_Enum_Name_Key_Settings() {
settings.put(EncryptedPreferences.PreferenceEnumNameKey, EncryptedPreferences.PreferenceEnumNameKey.defaultValue)
assertEquals(Enum.Value2, settings.get(EncryptedPreferences.PreferenceEnumNameKey))
settings.put(EncryptedPreferences.PreferenceEnumNameKey, Enum.Value1)
assertEquals(Enum.Value1, settings.get(EncryptedPreferences.PreferenceEnumNameKey))
}
@Test
fun removeEnum() {
// prepare
settings.put(EncryptedPreferences.PreferenceEnumNameKey, Enum.Value1)
// execute
settings.remove(EncryptedPreferences.PreferenceEnumNameKey)
// verify
// should be reset to default when calling get
assertEquals(Enum.Value2, settings.get(EncryptedPreferences.PreferenceEnumNameKey))
}
@Test
fun clear() {
// prepare
settings.put(EncryptedPreferences.PreferenceString, "test")
settings.put(EncryptedPreferences.PreferenceEnumNameKey, Enum.Value1)
// execute
settings.clear()
// verify
assertEquals(Enum.Value2, settings.get(EncryptedPreferences.PreferenceEnumNameKey))
assertEquals("default", settings.get(EncryptedPreferences.PreferenceString))
}
}
| 8 | Kotlin | 4 | 6 | d89b362e808d5b23ccbdc572e480d4e86f19fcc4 | 5,409 | settings | Apache License 2.0 |
app/src/main/java/com/satyamthakur/bioguardian/BioGuardian.kt | dev-satyamthakur | 750,941,674 | false | {"Kotlin": 71316} | package com.satyamthakur.bioguardian
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class BioGuardian: Application() {
} | 0 | Kotlin | 0 | 0 | 49850118d632279ceb7d08b8eefef9df50f91212 | 164 | Bio-Guardian | MIT License |
src/test/kotlin/ar/edu/unq/pds03backend/GenericResponseTest.kt | cassa10 | 478,695,193 | false | {"Kotlin": 387344, "Shell": 2326, "Dockerfile": 168} | package ar.edu.unq.pds03backend
import ar.edu.unq.pds03backend.dto.GenericResponse
import junit.framework.TestCase.assertEquals
import org.junit.Test
import org.springframework.http.HttpStatus
class GenericResponseTest {
@Test
fun `test generic response init`(){
val httpStatus1 = HttpStatus.OK
val message1 = "msg1"
val httpStatus2 = HttpStatus.NOT_FOUND
val message2 = "msg error"
val res1 = GenericResponse(httpStatus1, message1)
val res2 = GenericResponse(httpStatus2, message2)
with(res1) {
assertEquals(httpStatus, httpStatus1)
assertEquals(message, message1)
assertEquals(status, httpStatus1.name)
assertEquals(statusCode, httpStatus1.value())
}
with(res2) {
assertEquals(httpStatus, httpStatus2)
assertEquals(message, message2)
assertEquals(status, httpStatus2.name)
assertEquals(statusCode, httpStatus2.value())
}
}
} | 0 | Kotlin | 1 | 0 | 2e61373e3b06ba75399dc429683eec6281f405e9 | 1,018 | pds03-backend | MIT License |
platform/platform-impl/src/com/intellij/ide/wizard/language/EmptyProjectGeneratorNewProjectWizard.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.wizard.language
import com.intellij.icons.AllIcons
import com.intellij.ide.projectWizard.NewProjectWizardConstants
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.*
import com.intellij.ide.wizard.NewProjectWizardChainStep.Companion.nextStep
import com.intellij.ide.wizard.comment.CommentNewProjectWizardStep
import com.intellij.openapi.module.GeneralModuleType
import com.intellij.openapi.module.ModuleTypeManager
import com.intellij.openapi.project.Project
import com.intellij.ui.UIBundle
import javax.swing.Icon
class EmptyProjectGeneratorNewProjectWizard : GeneratorNewProjectWizard {
override val id: String = NewProjectWizardConstants.Generators.EMPTY_PROJECT
override val name: String = UIBundle.message("label.project.wizard.empty.project.generator.name")
override val icon: Icon = AllIcons.Nodes.Module
override fun createStep(context: WizardContext): NewProjectWizardStep =
RootNewProjectWizardStep(context)
.nextStep(::CommentStep)
.nextStep(::newProjectWizardBaseStepWithoutGap)
.nextStep(::GitNewProjectWizardStep)
.nextStep(::Step)
private class CommentStep(parent: NewProjectWizardStep) : CommentNewProjectWizardStep(parent) {
override val comment: String = UIBundle.message("label.project.wizard.empty.project.generator.full.description")
}
private class Step(parent: NewProjectWizardStep) : AbstractNewProjectWizardStep(parent) {
override fun setupProject(project: Project) {
val moduleType = ModuleTypeManager.getInstance().findByID(GeneralModuleType.TYPE_ID)
val builder = moduleType.createModuleBuilder()
setupProjectFromBuilder(project, builder)
}
}
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 1,836 | intellij-community | Apache License 2.0 |
src/main/kotlin/com/pineypiney/game_engine/objects/transforms/Transform3D.kt | PineyPiney | 491,900,499 | false | {"Kotlin": 641121, "GLSL": 32418} | package com.pineypiney.game_engine.objects.transforms
import com.pineypiney.game_engine.util.extension_functions.copy
import com.pineypiney.game_engine.util.maths.I
import glm_.quat.Quat
import glm_.vec3.Vec3
class Transform3D(position: Vec3 = Vec3(), rotation: Quat = Quat(), scale: Vec3 = Vec3(1)): Transform<Vec3, Quat, Vec3>() {
override var position: Vec3 = position
set(value) {
field = value
recalculateModel()
}
override var rotation: Quat = rotation
set(value) {
field = value
recalculateModel()
}
override var scale: Vec3 = scale
set(value) {
field = value
recalculateModel()
}
init {
recalculateModel()
}
override fun translate(move: Vec3){
position plusAssign move
recalculateModel()
}
override fun rotate(angle: Quat){
rotation timesAssign angle
recalculateModel()
}
fun rotate(euler: Vec3) = rotate(Quat(euler))
override fun scale(mult: Vec3){
scale timesAssign mult
recalculateModel()
}
override fun recalculateModel(){
model = (I.translate(position) * rotation.toMat4()).scale(scale)
}
override fun copy(): Transform3D = Transform3D(position.copy(), Quat(rotation), scale.copy()).apply { recalculateModel() }
companion object{
val origin; get() = Transform3D()
}
} | 0 | Kotlin | 0 | 0 | f927b3d9fa5f402fc85db008e46d876f397e5cf7 | 1,451 | GameEngine | MIT License |
components/filemanager/receive/src/main/java/com/flipperdevices/filemanager/receive/viewmodel/ReceiveViewModel.kt | flipperdevices | 288,258,832 | false | null | package com.flipperdevices.share.receive.viewmodel
import android.app.Application
import android.content.Intent
import androidx.lifecycle.viewModelScope
import com.flipperdevices.bridge.api.model.FlipperRequestPriority
import com.flipperdevices.bridge.api.model.wrapToRequest
import com.flipperdevices.bridge.protobuf.streamToCommandFlow
import com.flipperdevices.bridge.service.api.FlipperServiceApi
import com.flipperdevices.bridge.service.api.provider.FlipperBleServiceConsumer
import com.flipperdevices.bridge.service.api.provider.FlipperServiceProvider
import com.flipperdevices.core.di.ComponentHolder
import com.flipperdevices.core.log.LogTagProvider
import com.flipperdevices.core.log.error
import com.flipperdevices.core.log.info
import com.flipperdevices.core.ui.AndroidLifecycleViewModel
import com.flipperdevices.deeplink.model.DeeplinkContent
import com.flipperdevices.protobuf.storage.file
import com.flipperdevices.protobuf.storage.writeRequest
import com.flipperdevices.share.common.model.DownloadProgress
import com.flipperdevices.share.common.model.ShareState
import com.flipperdevices.share.receive.di.ShareReceiveComponent
import java.io.File
import java.io.InputStream
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ReceiveViewModel(
private val deeplinkContent: DeeplinkContent,
private val flipperPath: String,
application: Application
) : AndroidLifecycleViewModel(application),
FlipperBleServiceConsumer,
LogTagProvider {
override val TAG = "ReceiveViewModel"
@Inject
lateinit var serviceProvider: FlipperServiceProvider
private val uploadStarted = AtomicBoolean(false)
private val contentResolver = application.contentResolver
private val receiveStateFlow = MutableStateFlow(
ShareState(
deeplinkContent.length()?.let {
DownloadProgress.Fixed(0L, it)
} ?: DownloadProgress.Infinite(0L)
)
)
init {
ComponentHolder.component<ShareReceiveComponent>().inject(this)
serviceProvider.provideServiceApi(consumer = this, lifecycleOwner = this)
}
fun getReceiveState(): StateFlow<ShareState> = receiveStateFlow
override fun onServiceApiReady(serviceApi: FlipperServiceApi) {
viewModelScope.launch {
startUpload(serviceApi)
}
viewModelScope.launch {
serviceApi.requestApi.getSpeed().collect { serialSpeed ->
receiveStateFlow.update {
it.copy(
downloadProgress = it.downloadProgress.updateSpeed(
serialSpeed.transmitBytesInSec
)
)
}
}
}
}
fun cancelUpload() {
receiveStateFlow.update {
it.copy(dialogShown = false)
}
}
private suspend fun startUpload(serviceApi: FlipperServiceApi) = withContext(Dispatchers.IO) {
if (!uploadStarted.compareAndSet(false, true)) {
info { "Upload file $deeplinkContent already started" }
return@withContext
}
info { "Upload file $deeplinkContent start" }
val exception = runCatching {
deeplinkContent.openStream().use { fileStream ->
val stream = fileStream ?: return@use
val filePath =
File(flipperPath, deeplinkContent.filename() ?: "Unknown").absolutePath
val requestFlow = streamToCommandFlow(
stream, deeplinkContent.length()
) { chunkData ->
storageWriteRequest = writeRequest {
path = filePath
file = file { data = chunkData }
}
}.map {
it.wrapToRequest(FlipperRequestPriority.FOREGROUND)
}
val response = serviceApi.requestApi.request(requestFlow)
info { "File send with response $response" }
}
}.exceptionOrNull()
cleanUp()
receiveStateFlow.update {
it.copy(
dialogShown = false,
processCompleted = true
)
}
if (exception != null) {
error(exception) { "Can't upload $deeplinkContent" }
}
}
private fun DeeplinkContent.openStream(): InputStream? {
return when (this) {
is DeeplinkContent.ExternalUri -> {
contentResolver.openInputStream(uri)
}
is DeeplinkContent.InternalStorageFile -> {
file.inputStream()
}
}
}
private fun cleanUp() {
when (deeplinkContent) {
is DeeplinkContent.ExternalUri -> {
contentResolver.releasePersistableUriPermission(
deeplinkContent.uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
is DeeplinkContent.InternalStorageFile -> {
deeplinkContent.file.delete()
}
}
}
}
| 2 | Kotlin | 31 | 293 | 522f873d6dcf09a8f1907c1636fb0c3a996f5b44 | 5,437 | Flipper-Android-App | MIT License |
shared/src/androidMain/kotlin/com/gurpreetsk/oofmrlinus/MuseumApp.kt | imGurpreetSK | 835,042,964 | false | {"Kotlin": 27037, "Swift": 677} | package com.gurpreetsk.oofmrlinus
import android.app.Application
import com.gurpreetsk.oofmrlinus.di.initKoin
class MuseumApp : Application() {
override fun onCreate() {
super.onCreate()
initKoin()
}
}
| 0 | Kotlin | 0 | 0 | f70d3048d4dcdb70fd3df96ef0c8f0198b9ed787 | 228 | OofMrLinus | Apache License 2.0 |
feature-assets/src/main/java/io/novafoundation/nova/feature_assets/presentation/send/amount/di/SelectSendComponent.kt | novasamatech | 415,834,480 | false | {"Kotlin": 8137060, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.feature_assets.presentation.send.amount.di
import androidx.fragment.app.Fragment
import dagger.BindsInstance
import dagger.Subcomponent
import io.novafoundation.nova.common.di.scope.ScreenScope
import io.novafoundation.nova.feature_assets.presentation.AssetPayload
import io.novafoundation.nova.feature_assets.presentation.send.amount.SelectSendFragment
@Subcomponent(
modules = [
SelectSendModule::class
]
)
@ScreenScope
interface SelectSendComponent {
@Subcomponent.Factory
interface Factory {
fun create(
@BindsInstance fragment: Fragment,
@BindsInstance recipientAddress: String?,
@BindsInstance payload: AssetPayload
): SelectSendComponent
}
fun inject(fragment: SelectSendFragment)
}
| 12 | Kotlin | 6 | 9 | b39307cb56302ce7298582dbd03f33f6b2e2a807 | 810 | nova-wallet-android | Apache License 2.0 |
collector-exoplayer/src/main/java/com/bitmovin/analytics/exoplayer/ExoUtil.kt | bitmovin | 120,633,749 | false | null | package com.bitmovin.analytics.exoplayer
import android.os.Handler
import android.os.Looper
import com.google.android.exoplayer2.ExoPlayerLibraryInfo
import com.google.android.exoplayer2.Player
internal object ExoUtil {
fun exoStateToString(state: Int): String {
return when (state) {
Player.STATE_IDLE -> "Idle"
Player.STATE_BUFFERING -> "Buffering"
Player.STATE_READY -> "Ready"
Player.STATE_ENDED -> "Ended"
else -> "Unknown PlayerState"
}
}
val playerVersion: String
get() {
try {
val versionField = ExoPlayerLibraryInfo::class.java.getField("VERSION")
return versionField[null] as String
} catch (ignored: NoSuchFieldException) {
} catch (ignored: IllegalAccessException) {
}
return "unknown"
}
// Method that can be used to make sure a certain code block is executed
// on same thread as provided looper
// Be careful, given code is either executed synchronously when calling
// thread is same thread as applicationLooper, or asynchronously if not
// This means code calling this cannot rely on order of execution
fun executeSyncOrAsyncOnLooperThread(applicationLooper: Looper, function: () -> Unit) {
if (Thread.currentThread() != applicationLooper.thread) {
val handler = Handler(applicationLooper)
handler.post {
function.invoke()
}
} else {
function.invoke()
}
}
}
| 0 | Kotlin | 6 | 8 | c593bdde3d6968b8be6263b5a79c20af2c95df0d | 1,591 | bitmovin-analytics-collector-android | Amazon Digital Services License |
src/main/kotlin/com/skillw/pouvoir/internal/core/asahi/prefix/bukkit/Task.kt | Glom-c | 396,683,163 | false | null | package com.skillw.pouvoir.internal.core.asahi.prefix.bukkit
import com.skillw.asahi.api.annotation.AsahiPrefix
import com.skillw.asahi.api.prefixParser
import com.skillw.asahi.api.quest
import com.skillw.asahi.api.quester
import com.skillw.pouvoir.internal.core.asahi.util.delay
import taboolib.common.platform.function.submit
import taboolib.common.platform.function.submitAsync
import java.util.*
import java.util.concurrent.CompletableFuture
/**
* @className Task
*
* @author Glom
* @date 2023/1/14 0:56 Copyright 2024 Glom.
*/
@AsahiPrefix(["async", "taskAsync"])
private fun async() = prefixParser {
var delayGetter = quester { 0L }
var periodGetter = quester { 0L }
if (expect("in")) {
delayGetter = questTick()
}
if (expect("every")) {
periodGetter = questTick()
}
val content = parseScript()
result {
val delay = delayGetter.get()
val period = periodGetter.get()
val asyncContext = context().clone()
val completable = CompletableFuture<Any?>()
submitAsync(delay == 0L, delay, period) {
if (completable.isCancelled) return@submitAsync
completable.complete(content.run(asyncContext))
context().putAllIfExists(asyncContext)
}
completable.autoCancelled()
addTask(completable)
}
}
@AsahiPrefix(["sync", "taskSync", "task"])
private fun sync() = prefixParser {
var delayGetter = quester { 0L }
var periodGetter = quester { 0L }
if (expect("in")) {
delayGetter = questTick()
}
if (expect("every")) {
periodGetter = questTick()
}
val content = parseScript()
result {
val delay = delayGetter.get()
val period = periodGetter.get()
val submitContext = context().clone()
val completable = CompletableFuture<Any?>()
submit(delay == 0L, false, delay, period) {
if (completable.isCancelled) return@submit
completable.complete(content.run(submitContext))
context().putAllIfExists(submitContext)
}
completable.autoCancelled()
addTask(completable)
}
}
@AsahiPrefix(["inSync"])
private fun inSync() = prefixParser {
val content = parseScript()
result {
taboolib.common.util.sync {
context().clone().run {
val result = content.run()
context().putAllIfExists(this)
result
}
}
}
}
@AsahiPrefix(["await"])
private fun await() = prefixParser<Any?> {
val any = expect("any")
val all = expect("all")
if (peek() != "[" && all) {
return@prefixParser result {
awaitAllTask()
}
}
val list = if (peek() == "[") quest() else quest<CompletableFuture<Any?>>().quester { listOf(it) }
result {
val tasks = list.get().toTypedArray()
if (any)
CompletableFuture.anyOf(*tasks).join()
else
CompletableFuture.allOf(*tasks).join()
}
}
@AsahiPrefix(["wait", "delay", "sleep"], "lang")
private fun delay() = prefixParser {
val tick = questTick()
result {
delay(tick.get())
}
} | 3 | null | 8 | 9 | 35b93485f5f4c2d5c534a2765ff7cfb8f34dd737 | 3,183 | Pouvoir | MIT License |
locallydynamic-server-library/server/src/main/java/com/jeppeman/locallydynamic/server/extensions/InputStream.kt | poovarasanvasudevan | 239,129,218 | true | {"Kotlin": 319796, "Java": 302260, "Shell": 7767} | package com.jeppeman.locallydynamic.server.extensions
import java.io.InputStream
import java.nio.charset.Charset
fun InputStream.readString(charset: Charset = Charsets.UTF_8) = readBytes().toString(charset) | 0 | null | 0 | 0 | 9e52f801e8afdb88b245600dbfd4d6691fd22d95 | 208 | LocallyDynamic | Apache License 2.0 |
test-fixture/integration/src/main/kotlin/com/linecorp/kotlinjdsl/test/integration/querydsl/where/AbstractCriteriaQueryDslWhereIntegrationTest.kt | line | 442,633,985 | false | null | package com.linecorp.kotlinjdsl.test.integration.querydsl.where
import com.linecorp.kotlinjdsl.listQuery
import com.linecorp.kotlinjdsl.querydsl.expression.col
import com.linecorp.kotlinjdsl.querydsl.from.join
import com.linecorp.kotlinjdsl.singleQuery
import com.linecorp.kotlinjdsl.subquery
import com.linecorp.kotlinjdsl.test.entity.Address
import com.linecorp.kotlinjdsl.test.entity.order.Order
import com.linecorp.kotlinjdsl.test.entity.order.OrderAddress
import com.linecorp.kotlinjdsl.test.entity.order.OrderGroup
import com.linecorp.kotlinjdsl.test.integration.AbstractCriteriaQueryDslIntegrationTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.math.BigDecimal
abstract class AbstractCriteriaQueryDslWhereIntegrationTest : AbstractCriteriaQueryDslIntegrationTest() {
private val orderItem1 = orderItem { }
private val orderItem2 = orderItem { }
private val order1 = order { purchaserId = 1000 }
private val order2 = order { purchaserId = 2000 }
private val order3 = order {
purchaserId = 3000
groups = hashSetOf(orderGroup {
items = hashSetOf(orderItem1, orderItem2)
address = orderAddress {
zipCode = "zipCode1"
}
})
}
@BeforeEach
fun setUp() {
entityManager.persistAll(order1, order2, order3)
entityManager.flushAndClear()
}
@Test
fun where() {
// when
val order = queryFactory.singleQuery<Order> {
select(entity(Order::class))
from(entity(Order::class))
where(col(Order::purchaserId).equal(1000))
}
// then
assertThat(order)
.usingRecursiveComparison()
.withComparatorForType(BigDecimal::compareTo, BigDecimal::class.java)
.isEqualTo(order1)
}
@Test
fun `where using subquery`() {
// when
val subquery = queryFactory.subquery {
val order = entity(Order::class, "o")
select(col(order, Order::id))
from(order)
where(col(order, Order::purchaserId).lessThan(2000))
}
val orderIds = queryFactory.listQuery {
select(col(Order::id))
from(entity(Order::class))
where(col(Order::id).`in`(subquery))
}
// then
assertThat(orderIds).isEqualTo(listOf(order1.id))
}
@Test
fun `where using subquery with ref key`() {
// when
val subQuery = queryFactory.subquery {
select(nestedCol(col(OrderGroup::order), Order::id))
from(entity(OrderGroup::class))
join(OrderGroup::address)
associate(OrderAddress::class, Address::class, on(OrderAddress::address))
where(col(Address::zipCode).equal("zipCode1"))
}
val orderIds = queryFactory.listQuery {
select(col(Order::id))
from(entity(Order::class))
where(col(Order::id).`in`(subQuery))
}
// then
assertThat(orderIds).isEqualTo(listOf(order3.id).sorted())
}
}
| 26 | Kotlin | 60 | 504 | f28908bf432cf52f73a9573b1ac2be5eb4b2b7dc | 3,117 | kotlin-jdsl | Apache License 2.0 |
module_user/src/main/kotlin/com/crow/module_user/ui/viewmodel/UserViewModel.kt | CrowForKotlin | 610,636,509 | false | null | package com.crow.module_user.ui.viewmodel
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.lifecycle.viewModelScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.crow.base.copymanga.BaseStrings
import com.crow.base.copymanga.BaseUser
import com.crow.base.tools.extensions.DataStoreAgent
import com.crow.base.tools.extensions.asyncClear
import com.crow.base.tools.extensions.asyncDecode
import com.crow.base.tools.extensions.dp2px
import com.crow.base.tools.extensions.toTypeEntity
import com.crow.base.ui.viewmodel.mvi.BaseMviViewModel
import com.crow.module_user.model.UserIntent
import com.crow.module_user.model.resp.LoginResultsOkResp
import com.crow.module_user.model.resp.UserResultErrorResp
import com.crow.module_user.network.UserRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.net.HttpURLConnection
import com.crow.base.R as baseR
/*************************
* @Machine: RedmiBook Pro 15 Win11
* @Path: module_user/src/main/java/com/crow/module_user/viewmodel
* @Time: 2023/3/18 21:16
* @Author: CrowForKotlin
* @Description: UserViewModel
* @formatter:on
**************************/
class UserViewModel(private val repository: UserRepository) : BaseMviViewModel<UserIntent>() {
// 使用StateFlow设计成 粘性状态
private var _userInfo = MutableStateFlow<LoginResultsOkResp?>(null)
val userInfo: StateFlow<LoginResultsOkResp?> get() = _userInfo
// 头像链接
var mIconUrl: String? = null
private set
init {
// 初始化 用户信息
viewModelScope.launch { _userInfo.emit((toTypeEntity<LoginResultsOkResp>(DataStoreAgent.DATA_USER.asyncDecode())).also { mIconUrl = it?.mIconUrl }) }
}
override fun dispatcher(intent: UserIntent) {
when (intent) {
is UserIntent.Login -> doLogin(intent)
is UserIntent.Reg -> doReg(intent)
is UserIntent.GetUserUpdateInfo -> doGetUserInfo(intent)
is UserIntent.GetUserInfo -> { }
}
}
private fun doLogin(intent: UserIntent.Login) {
// 200代表 登录 请求成功
flowResult(intent, repository.login(intent.username, intent.password)) { value ->
if (value.mCode == HttpURLConnection.HTTP_OK) {
intent.copy(loginResultsOkResp = toTypeEntity<LoginResultsOkResp>(value.mResults)?.also {
mIconUrl = it.mIconUrl
_userInfo.emit(it)
})
}
else {
intent.copy(userResultErrorResp = (toTypeEntity<UserResultErrorResp>(value.mResults) ?: return@flowResult intent))
}
}
}
private fun doReg(intent: UserIntent.Reg) {
flowResult(intent, repository.reg(intent.username, intent.password)) { value ->
if (value.mCode == HttpURLConnection.HTTP_OK) intent.copy(regResultsOkResp = (toTypeEntity(value.mResults) ?: return@flowResult intent))
else intent.copy(userResultErrorResp = (toTypeEntity(value.mResults) ?: return@flowResult intent))
}
}
private fun doGetUserInfo(intent: UserIntent.GetUserUpdateInfo) {
flowResult(intent, repository.getUserUpdateInfo()) { value ->
intent.copy(userUpdateInfoResp = value.mResults)
}
}
// 清除用户信息
fun doClearUserInfo() {
viewModelScope.launch {
DataStoreAgent.DATA_USER.asyncClear()
BaseUser.CURRENT_USER_TOKEN = ""
mIconUrl = null
_userInfo.emit(null)
}
}
// 长度不小于6且不包含空
fun getUsername(text: String): String? = text.run { if (length < 6 || contains(" ")) return null else this }
fun getPassword(text: String): String? = text.run { if (length < 6 || contains(" ")) return null else this }
// 加载Icon --- needApply : 是否需要适配固定大小
inline fun doLoadIcon(context: Context, needApply: Boolean = true, crossinline doOnReady: (resource: Drawable) -> Unit) {
if (needApply) {
Glide.with(context)
.load(if (mIconUrl == null) baseR.drawable.base_icon_app else BaseStrings.URL.MangaFuna.plus(mIconUrl))
.placeholder(baseR.drawable.base_icon_app)
.apply(RequestOptions().circleCrop().override(context.dp2px(48f).toInt()))
.into(object : CustomTarget<Drawable>() {
override fun onLoadCleared(placeholder: Drawable?) {}
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) { doOnReady(resource) }
})
return
}
Glide.with(context)
.load(if (mIconUrl == null) baseR.drawable.base_icon_app else BaseStrings.URL.MangaFuna.plus(mIconUrl))
.placeholder(baseR.drawable.base_icon_app)
.into(object : CustomTarget<Drawable>() {
override fun onLoadCleared(placeholder: Drawable?) {}
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) { doOnReady(resource) }
})
}
} | 8 | null | 3 | 76 | 3b64f3bc7ef0f8014e9311f1c69515ecba83ebfc | 5,256 | CopyMangaX | Apache License 2.0 |
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/middle/flower/Kaoruko.kt | qwewqa | 390,928,568 | false | null | package xyz.qwewqa.relive.simulator.core.presets.dress.middle.flower
import xyz.qwewqa.relive.simulator.core.presets.condition.FlowerOnlyCondition
import xyz.qwewqa.relive.simulator.core.presets.condition.SunOnlyCondition
import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress1090013
import xyz.qwewqa.relive.simulator.core.stage.Act
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.autoskill.new
import xyz.qwewqa.relive.simulator.core.stage.buff.ActPowerUpBuff
import xyz.qwewqa.relive.simulator.core.stage.buff.BuffCategory
import xyz.qwewqa.relive.simulator.core.stage.buff.EffectiveDamageDealtUpBuff
import xyz.qwewqa.relive.simulator.core.stage.dress.DressCategory
import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint
import xyz.qwewqa.relive.simulator.core.stage.passive.ActCritical50UnitSkill
import xyz.qwewqa.relive.simulator.core.stage.passive.TeamCriticalUpBuffPassive
import xyz.qwewqa.relive.simulator.core.stage.passive.TeamDexterityUpBuffPassive
val DevilKaoruko = dress1090013(
name = "<NAME>",
acts = listOf(
ActType.Act1.blueprint("Brilliance Slash") {
Act {
targetBack().act {
attack(
modifier = values1,
hitCount = 1,
)
}
targetSelf().act {
addBrilliance(values2)
}
}
},
ActType.Act2.blueprint("Soul Contract") {
Act {
targetBack().act {
attack(
modifier = values1,
hitCount = 2,
)
}
targetAllyAoe().act {
applyBuff(
ActPowerUpBuff,
value = values2,
turns = times2,
)
applyBuff(
EffectiveDamageDealtUpBuff,
value = values3,
turns = times3,
)
}
}
},
ActType.Act3.blueprint("Devil's Whisper") {
Act {
targetBack().act {
attack(
modifier = values1,
hitCount = 2,
)
}
targetAoe().act {
dispelTimed(BuffCategory.Positive)
dispelCountable(BuffCategory.Positive)
}
}
},
ActType.ClimaxAct.blueprint("Flames of Hell") {
Act {
targetAllyAoe().act {
dispelTimed(BuffCategory.Negative)
}
targetAoe().act {
dispelTimed(BuffCategory.Positive)
attack(
modifier = values3,
hitCount = 4,
)
}
}
}
),
autoSkills = listOf(
listOf(
TeamDexterityUpBuffPassive.new(10, time = 3),
),
listOf(
TeamCriticalUpBuffPassive.new(20, time = 3),
),
listOf(
), // TODO: CX Seal
),
unitSkill = ActCritical50UnitSkill + (FlowerOnlyCondition or SunOnlyCondition),
categories = setOf(DressCategory.Arcana),
)
| 0 | Kotlin | 11 | 7 | 70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74 | 3,468 | relight | MIT License |
backend/src/test/kotlin/metrik/project/domain/model/StageTest.kt | hyrepo | 381,448,946 | true | {"Kotlin": 282451, "TypeScript": 129526, "JavaScript": 96555, "Gherkin": 26976, "Shell": 7991, "Dockerfile": 2490, "HTML": 354, "Less": 341} | package metrik.project.domain.model
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class StageTest {
@Test
internal fun `should return completedTime when stage contains completedTime`() {
assertEquals(1610700490630, Stage(startTimeMillis = 1610700490500, durationMillis = 129, pauseDurationMillis = 1, completedTimeMillis = 1610700490630).getStageDoneTime())
}
@Test
internal fun `should return sum of startTime and durationTime and pauseTime given stage does not contain completedTime`() {
assertEquals(1610700490630, Stage(startTimeMillis = 1610700490500, durationMillis = 129, pauseDurationMillis = 1, completedTimeMillis = null).getStageDoneTime())
}
} | 0 | null | 0 | 1 | f0bb069647ec1ed96558f526c802a02d8e6b88d0 | 737 | metrik | MIT License |
app/src/main/java/me/devsaki/hentoid/util/BundleX.kt | avluis | 37,775,708 | false | null | package me.devsaki.hentoid.util
import android.os.Bundle
import android.os.Parcel
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Creates a property delegate that uses the property name as the key to get and set [Bundle]
* values. The property will return [default] if the key is not present in the [Bundle].
*/
private fun <T> property(
default: T,
get: (String, T) -> T,
put: (String, T) -> Unit
) = object : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>) =
get(property.name, default)
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) =
put(property.name, value)
}
/**
* Creates a property delegate that uses the property name as the key to get and set [Bundle]
* values. The property will return null if the key is not present in the [Bundle]
* and the value is removed from the [Bundle] when the property is set to null.
*/
private fun <T> Bundle.nullableProperty(
get: (String) -> T,
put: (String, T) -> Unit
) = object : ReadWriteProperty<Any, T?> {
override fun getValue(thisRef: Any, property: KProperty<*>) =
if (containsKey(property.name)) get(property.name) else null
override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) =
if (value == null) remove(property.name) else put(property.name, value)
}
fun Bundle.boolean(default: Boolean) = property(default, ::getBoolean, ::putBoolean)
fun Bundle.boolean() = nullableProperty(::getBoolean, ::putBoolean)
fun Bundle.byte(default: Byte) = property(default, ::getByte, ::putByte)
fun Bundle.byte() = nullableProperty(::getByte, ::putByte)
fun Bundle.short(default: Short) = property(default, ::getShort, ::putShort)
fun Bundle.short() = nullableProperty(::getShort, ::putShort)
fun Bundle.int(default: Int) = property(default, ::getInt, ::putInt)
fun Bundle.int() = nullableProperty(::getInt, ::putInt)
fun Bundle.long(default: Long) = property(default, ::getLong, ::putLong)
fun Bundle.long() = nullableProperty(::getLong, ::putLong)
fun Bundle.float(default: Float) = property(default, ::getFloat, ::putFloat)
fun Bundle.float() = nullableProperty(::getFloat, ::putFloat)
fun Bundle.char(default: Char) = property(default, ::getChar, ::putChar)
fun Bundle.char() = nullableProperty(::getChar, ::putChar)
fun Bundle.string(default: String) = property(default, ::getString, ::putString)
fun Bundle.string() = nullableProperty(::getString, ::putString)
fun Bundle.sizeI() = nullableProperty(::getSize, ::putSize)
fun Bundle.sizeF() = nullableProperty(::getSizeF, ::putSizeF)
fun Bundle.intArray() = nullableProperty(::getIntArray, ::putIntArray)
fun Bundle.longArray() = nullableProperty(::getLongArray, ::putLongArray)
fun Bundle.intArrayList() = nullableProperty(::getIntegerArrayList, ::putIntegerArrayList)
fun Bundle.bundle() = nullableProperty(::getBundle, ::putBundle)
fun Bundle.toByteArray(): ByteArray {
val parcel = Parcel.obtain()
parcel.writeBundle(this)
val bytes = parcel.marshall()
parcel.recycle()
return bytes
}
fun Bundle.fromByteArray(data: ByteArray): Bundle {
val parcel = Parcel.obtain()
parcel.unmarshall(data, 0, data.size)
parcel.setDataPosition(0)
val bundle = parcel.readBundle(this.classLoader)
parcel.recycle()
return bundle ?: Bundle()
} | 167 | null | 84 | 992 | f54df07b79da4147951bc9902ab0dbd70edb50f1 | 3,382 | Hentoid | Apache License 2.0 |
library/src/main/java/com/prongbang/mvirx/RxViewRenderer.kt | dgfug | 409,275,566 | true | {"Kotlin": 12064} | package com.prongbang.mvirx
/**
* How to use:
* class FeatureActivity : AppCompatActivity(), RxViewRenderer<FeatureState, FeatureEffect> {
* override fun render(state: FeatureState) {
*
* }
*
* override fun renderEffect(effect: FeatureEffect) {
*
* }
* }
*/
interface RxViewRenderer<S : RxState, E : RxEffect> {
fun render(state: S)
fun renderEffect(effect: E)
} | 1 | Kotlin | 0 | 0 | 9541681f6feb9e9ca74dd79bdb19a37dafb5cab5 | 396 | mvi-rx | MIT License |
src/main/kotlin/no/nav/tms/minesaker/api/saf/SafConsumer.kt | navikt | 331,032,645 | false | {"Kotlin": 176442, "Dockerfile": 219} | package no.nav.personbruker.minesaker.api.saf
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.HttpHeaders.Authorization
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import no.nav.dokument.saf.selvbetjening.generated.dto.HentJournalposter
import no.nav.dokument.saf.selvbetjening.generated.dto.HentSakstemaer
import no.nav.personbruker.minesaker.api.common.exception.CommunicationException
import no.nav.personbruker.minesaker.api.common.exception.DocumentNotFoundException
import no.nav.personbruker.minesaker.api.common.exception.GraphQLResultException
import no.nav.personbruker.minesaker.api.domain.Sakstema
import no.nav.personbruker.minesaker.api.saf.common.GraphQLResponse
import no.nav.personbruker.minesaker.api.saf.journalposter.JournalposterRequest
import no.nav.personbruker.minesaker.api.saf.sakstemaer.SakstemaerRequest
import no.nav.personbruker.minesaker.api.sak.Kildetype
import no.nav.personbruker.minesaker.api.sak.SakstemaResult
import java.net.URL
import java.util.*
class SafConsumer(
private val httpClient: HttpClient,
private val safEndpoint: URL
) {
private val log = KotlinLogging.logger {}
private val safCallIdHeaderName = "Nav-Callid"
private val navConsumerIdHeaderName = "Nav-Consumer-Id"
private val navConsumerId = "mine-saker-api"
suspend fun hentSakstemaer(request: SakstemaerRequest, accessToken: String): SakstemaResult {
return try {
val result: HentSakstemaer.Result = unwrapGraphQLResponse(sendQuery(request, accessToken))
SakstemaResult(result.toInternal())
} catch (e: Exception) {
log.warn("Klarte ikke å hente data fra SAF.", e)
SakstemaResult(errors = listOf(Kildetype.SAF))
}
}
suspend fun hentJournalposter(
innloggetBruker: String,
request: JournalposterRequest,
accessToken: String
): List<Sakstema> {
val result: HentJournalposter.Result = unwrapGraphQLResponse(sendQuery(request, accessToken))
return result.toInternal(innloggetBruker)
}
suspend fun hentDokument(
journapostId: String,
dokumentinfoId: String,
accessToken: String
): ByteArray {
val httpResponse = fetchDocument(journapostId, dokumentinfoId, accessToken)
return unpackRawResponseBody(httpResponse)
}
private suspend fun fetchDocument(
journapostId: String,
dokumentinfoId: String,
accessToken: String
): HttpResponse = withContext(Dispatchers.IO) {
val callId = UUID.randomUUID()
log.info("Sender POST-kall med correlationId=$callId")
val urlToFetch = "$safEndpoint/rest/hentdokument/$journapostId/$dokumentinfoId/ARKIV"
log.info("Skal hente data fra: $urlToFetch")
httpClient.request {
url(urlToFetch)
method = HttpMethod.Get
header(Authorization, "Bearer $accessToken")
header(safCallIdHeaderName, callId)
header(navConsumerIdHeaderName, navConsumerId)
}
}
private suspend fun unpackRawResponseBody(response: HttpResponse): ByteArray {
if (response.status == HttpStatusCode.NotFound) {
throw DocumentNotFoundException("Fant ikke dokument hos SAF")
} else if (!response.status.isSuccess()) {
throw CommunicationException("Klarte ikke å hente dokument fra SAF. Http-status [${response.status}]")
}
try {
return response.readBytes()
} catch (e: Exception) {
throw CommunicationException("Klarte ikke å lese dokument fra SAF.", e)
}
}
private suspend fun sendQuery(request: GraphQLRequest, accessToken: String): HttpResponse = withContext(Dispatchers.IO) {
val callId = UUID.randomUUID()
log.info("Sender graphql-spørring med correlationId=$callId")
httpClient.post {
url("$safEndpoint/graphql")
method = HttpMethod.Post
header(safCallIdHeaderName, callId)
header(Authorization, "Bearer $accessToken")
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
setBody(request)
timeout {
socketTimeoutMillis = 25000
connectTimeoutMillis = 10000
requestTimeoutMillis = 35000
}
}
}
private suspend inline fun <reified T> unwrapGraphQLResponse(response: HttpResponse): T {
if (!response.status.isSuccess()) {
throw CommunicationException("Fikk http-status [${response.status}] fra SAF.")
}
val graphQLResponse = parseBody<T>(response)
logIfContainsDataAndErrors(graphQLResponse)
return graphQLResponse.extractData()
}
private suspend inline fun <reified T> parseBody(response: HttpResponse): GraphQLResponse<T> {
return try {
response.body()
} catch (e: Exception) {
throw CommunicationException("Klarte ikke tolke respons fra SAD", e)
}
}
private inline fun <reified T> GraphQLResponse<T>.extractData(): T {
return data ?: throw GraphQLResultException("Ingen data i resultatet fra SAF.", errors, extensions)
}
private fun logIfContainsDataAndErrors(response: GraphQLResponse<*>) {
if (response.containsData() && response.containsErrors()) {
val msg = "Resultatet inneholdt data og feil, dataene returneres til bruker. " +
"Feilene var errors: ${response.errors}, extensions: ${response.extensions}"
log.warn(msg)
}
}
private fun GraphQLResponse<*>.containsData() = data != null
private fun GraphQLResponse<*>.containsErrors() = errors?.isNotEmpty() == true
}
| 3 | Kotlin | 1 | 0 | c77241f766ef551675a695c0fcbbdd3c52daf25e | 5,976 | mine-saker-api | MIT License |
src/controller/java/src/matter/tlv/TlvReader.kt | project-chip | 244,694,174 | false | null | /*
*
* Copyright (c) 2023 Project CHIP Authors
* Copyright (c) 2019-2023 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package matter.tlv
import java.lang.Double.longBitsToDouble
import java.lang.Float.intBitsToFloat
/**
* Implements Matter TLV reader that supports all values and tags as defined in the Spec.
*
* @param bytes the bytes to interpret
*/
class TlvReader(bytes: ByteArray) : Iterable<Element> {
private val bytes = bytes.copyOf()
private var index = 0
/**
* Reads the next element from the TLV.
*
* @throws TlvParsingException if the TLV data was invalid
*/
fun nextElement(): Element {
// Ensure that at least one byte for control data is available for reading.
checkSize("controlByte", 1)
val controlByte = bytes[index]
val elementType =
runCatching { Type.from(controlByte) }
.onFailure {
throw TlvParsingException("Type error at $index for ${controlByte.toBinary()}", it)
}
.getOrThrow()
index++
// Read tag, and advance index past tag bytes
val tag =
runCatching { Tag.from(controlByte, index, bytes) }
.onFailure {
throw TlvParsingException("Tag error at $index for ${controlByte.toBinary()}", it)
}
.getOrThrow()
index += tag.size
// Element has either a length section or a fixed number of bytes for the value section. If
// present, length is encoded as 1 or 2 bytes indicating the number of bytes in the value.
val lengthSize = elementType.lengthSize
val valueSize: Int
if (lengthSize > 0) {
checkSize("length", lengthSize)
if (lengthSize > Int.SIZE_BYTES) {
throw TlvParsingException("Length $lengthSize at $index too long")
}
valueSize = bytes.sliceArray(index until index + lengthSize).fromLittleEndianToLong().toInt()
index += lengthSize
} else {
valueSize = elementType.valueSize.toInt()
}
// Ensure that the encoded length fits in the range of the array, and advance index to the
// next control byte.
checkSize("value", valueSize)
val valueBytes = bytes.sliceArray(index until index + valueSize)
index += valueSize
// Only supporting a small subset of value types currently. Others will just be interpreted
// as a null value.
val value: Value =
when (elementType) {
is SignedIntType -> IntValue(valueBytes.fromLittleEndianToLong(isSigned = true))
is UnsignedIntType -> UnsignedIntValue(valueBytes.fromLittleEndianToLong())
is Utf8StringType -> Utf8StringValue(String(valueBytes, Charsets.UTF_8))
is ByteStringType -> ByteStringValue(valueBytes)
is BooleanType -> BooleanValue(elementType.value)
is FloatType -> FloatValue(intBitsToFloat(valueBytes.fromLittleEndianToLong().toInt()))
is DoubleType -> DoubleValue(longBitsToDouble(valueBytes.fromLittleEndianToLong()))
is StructureType -> StructureValue
is ArrayType -> ArrayValue
is ListType -> ListValue
is EndOfContainerType -> EndOfContainerValue
else -> NullValue
}
return Element(tag, value)
}
/**
* Reads the next element from the TLV. Unlike nextElement() this method leaves the TLV reader
* positioned at the same element and doesn't advance it to the next element.
*
* @throws TlvParsingException if the TLV data was invalid
*/
fun peekElement(): Element {
val currentIndex = index
val element = nextElement()
index = currentIndex
return element
}
/**
* Reads the encoded Long value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getLong(tag: Tag): Long {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is IntValue) { "Unexpected value $value at index $index (expected IntValue)" }
return value.value
}
/**
* Reads the encoded ULong value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getULong(tag: Tag): ULong {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is UnsignedIntValue) {
"Unexpected value $value at index $index (expected UnsignedIntValue)"
}
return value.value.toULong()
}
/**
* Reads the encoded Int value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getInt(tag: Tag): Int {
return checkRange(getLong(tag), Int.MIN_VALUE.toLong()..Int.MAX_VALUE.toLong()).toInt()
}
/**
* Reads the encoded UInt value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getUInt(tag: Tag): UInt {
return checkRange(getULong(tag), UInt.MIN_VALUE.toULong()..UInt.MAX_VALUE.toULong()).toUInt()
}
/**
* Reads the encoded Short value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getShort(tag: Tag): Short {
return checkRange(getLong(tag), Short.MIN_VALUE.toLong()..Short.MAX_VALUE.toLong()).toShort()
}
/**
* Reads the encoded UShort value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getUShort(tag: Tag): UShort {
return checkRange(getULong(tag), UShort.MIN_VALUE.toULong()..UShort.MAX_VALUE.toULong())
.toUShort()
}
/**
* Reads the encoded Byte value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getByte(tag: Tag): Byte {
return checkRange(getLong(tag), Byte.MIN_VALUE.toLong()..Byte.MAX_VALUE.toLong()).toByte()
}
/**
* Reads the encoded UByte value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getUByte(tag: Tag): UByte {
return checkRange(getULong(tag), UByte.MIN_VALUE.toULong()..UByte.MAX_VALUE.toULong()).toUByte()
}
/**
* Reads the encoded Boolean value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getBool(tag: Tag): Boolean {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is BooleanValue) {
"Unexpected value $value at index $index (expected BooleanValue)"
}
return value.value
}
/**
* Reads the encoded Float value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getFloat(tag: Tag): Float {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is FloatValue) { "Unexpected value $value at index $index (expected FloatValue)" }
return value.value
}
/**
* Reads the encoded Double value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getDouble(tag: Tag): Double {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is DoubleValue) {
"Unexpected value $value at index $index (expected DoubleValue)"
}
return value.value
}
/**
* Reads the encoded UTF8 String value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getUtf8String(tag: Tag): String {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is Utf8StringValue) {
"Unexpected value $value at index $index (expected Utf8StringValue)"
}
return value.value
}
/**
* Reads the encoded Octet String value and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getByteString(tag: Tag): ByteArray {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is ByteStringValue) {
"Unexpected value $value at index $index (expected ByteStringValue)"
}
return value.value
}
/**
* Verifies that the current element is Null with expected tag and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun getNull(tag: Tag) {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is NullValue) { "Unexpected value $value at index $index (expected NullValue)" }
}
/**
* Retrieves a Boolean value associated with the given tag.
*
* @param tag The Tag to query for.
* @return The Boolean value associated with the tag.
*/
fun getBoolean(tag: Tag): Boolean {
return getBool(tag)
}
/**
* Retrieves a String value associated with the given tag. The returned string is in UTF-8 format.
*
* @param tag The Tag to query for.
* @return The String value associated with the tag.
*/
fun getString(tag: Tag): String {
return getUtf8String(tag)
}
/**
* Retrieves a ByteArray value associated with the given tag.
*
* @param tag The Tag to query for.
* @return The ByteArray value associated with the tag.
*/
fun getByteArray(tag: Tag): ByteArray {
return getByteString(tag)
}
/**
* Checks if the current element's value is of type NullValue.
*
* @return True if the current element's value is NullValue, otherwise false.
*/
fun isNull(): Boolean {
val value = peekElement().value
return (value is NullValue)
}
/**
* Checks if the next tag in sequence matches the provided tag.
*
* @param tag The Tag to compare against the next tag.
* @return True if the next tag matches the provided tag, otherwise false.
*/
fun isNextTag(tag: Tag): Boolean {
val nextTag = peekElement().tag
return (nextTag == tag)
}
/**
* Verifies that the current element is a start of a Structure and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun enterStructure(tag: Tag) {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is StructureValue) {
"Unexpected value $value at index $index (expected StructureValue)"
}
}
/**
* Verifies that the current element is a start of an Array and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun enterArray(tag: Tag) {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is ArrayValue) { "Unexpected value $value at index $index (expected ArrayValue)" }
}
/**
* Verifies that the current element is a start of a List and advances to the next element.
*
* @throws TlvParsingException if the element is not of the expected type or tag
*/
fun enterList(tag: Tag) {
val value = nextElement().verifyTagAndGetValue(tag)
require(value is ListValue) { "Unexpected value $value at index $index (expected ListValue)" }
}
/**
* Completes the reading of a Tlv container and prepares to read elements after the container.
*
* Note that if a TlvReader is not currently positioned at the EndOfContainerValue then function
* skips all unread element in container until it finds the end.
*
* @throws TlvParsingException if the end of the container element is not found
*/
fun exitContainer() {
var relevantDepth = 1
while (relevantDepth > 0) {
val value = nextElement().value
if (value is EndOfContainerValue) {
relevantDepth--
} else if (value is StructureValue || value is ArrayValue || value is ListValue) {
relevantDepth++
}
}
}
private fun Element.verifyTagAndGetValue(expectedTag: Tag): Value {
require(tag == expectedTag) {
"Unexpected value tag $tag at index $index (expected $expectedTag)"
}
return value
}
/**
* Skips the current element and advances to the next element.
*
* @throws TlvParsingException if the TLV data was invalid
*/
fun skipElement() {
nextElement()
}
/** Returns the total number of bytes read since the TlvReader was initialized. */
fun getLengthRead(): Int {
return index
}
/** Returns the total number of bytes that can be read until the end of TLV data is reached. */
fun getRemainingLength(): Int {
return bytes.size - index
}
/** Returns true if TlvReader is positioned at the end of container. */
fun isEndOfContainer(): Boolean {
// Ensure that at least one byte for control data is available for reading.
checkSize("controlByte", 1)
return bytes[index] == EndOfContainerType.encode()
}
/** Returns true if TlvReader reached the end of Tlv data. Returns false otherwise. */
fun isEndOfTlv(): Boolean {
return bytes.size == index
}
/** Resets the reader to the start of the provided byte array. */
fun reset() {
index = 0
}
override fun iterator(): Iterator<Element> {
return object : AbstractIterator<Element>() {
override fun computeNext() {
if (index < bytes.size) {
setNext(nextElement())
} else {
done()
}
}
}
}
private fun checkSize(propertyName: String, size: Number) {
if (index + size.toInt() > bytes.size) {
throw TlvParsingException(
"Invalid $propertyName length $size at index $index with ${bytes.size - index} available."
)
}
}
private fun <T : Comparable<T>> checkRange(
value: T,
range: ClosedRange<T>,
message: String = "Value $value at index $index is out of range $range"
): T {
if (value !in range) {
throw TlvParsingException(message)
}
return value
}
}
/** Exception thrown if there was an issue decoding the Matter TLV data. */
class TlvParsingException internal constructor(msg: String, cause: Throwable? = null) :
RuntimeException(msg, cause)
| 949 | null | 53 | 6,671 | 420e6d424c00aed3ead4015eafd71a1632c5e540 | 14,614 | connectedhomeip | Apache License 2.0 |
dotmimsync/src/main/java/com/mimetis/dotmim/sync/set/SyncRow.kt | vunder | 425,091,264 | false | {"Kotlin": 437311} | package com.mimetis.dotmim.sync.set
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import com.mimetis.dotmim.sync.DataRowState
import com.mimetis.dotmim.sync.PrimitiveSerializer
import java.util.*
@Serializable
class SyncRow(@Transient val length: Int = 0) {
private var buffer: Array<@Serializable(with = PrimitiveSerializer::class) Any?> =
Array(length) {}
lateinit var table: SyncTable
lateinit var rowState: DataRowState
// val length: Int
// get() = buffer.size
constructor(
table: SyncTable,
row: Array<Any?>,
state: DataRowState = DataRowState.Unchanged
) : this(row.size) {
buffer = row
this.table = table
this.rowState = state
}
operator fun get(columnName: String): Any? {
val index = table.columns!!.getIndex(columnName)
return this[index]
}
/**
* Get the value in the array that correspond to the SchemaColumn instance given
*/
operator fun get(column: SyncColumn): Any? =
this[column.columnName]
operator fun set(columnName: String, value: Any?) {
val column = table.columns!![columnName]
val index = table.columns!!.indexOf(column)
this[index] = value
}
operator fun get(index: Int): Any? {
return buffer[index]
}
operator fun set(index: Int, value: Any?) {
buffer[index] = value
}
fun toArray(): Array<Any?> {
val array = Array<Any?>(this.length + 1) {}
System.arraycopy(this.buffer, 0, array, 1, this.length)
array[0] = this.rowState.value
return array
}
/**
* Import a raw array, containing state on Index 0
*/
fun fromArray(row: Array<Any?>) {
val length = table.columns?.size ?: 0
if (row.size != length + 1)
throw Exception("row must contains State on position 0 and UpdateScopeId on position 1")
System.arraycopy(row, 1, buffer, 0, length)
val drs = row[0]
this.rowState = if (drs is DataRowState) {
drs
} else {
DataRowState.values().first { it.value == drs }
}
}
fun clear() {
Arrays.fill(buffer, null)
//this.table = null
}
}
| 0 | Kotlin | 2 | 0 | dea5c08c78dbae1e74552fafa3d720468b7cfabf | 2,285 | dotmimsync | MIT License |
android_demo/demo_tflite/app/src/main/java/com/edvard/poseestimation/ImageClassifierFloatInception.kt | edvardHua | 129,207,952 | false | null | /*
* Copyright 2018 <NAME> (<EMAIL>), <NAME> (<EMAIL>)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.edvard.poseestimation
import android.app.Activity
import android.util.Log
import org.opencv.core.CvType
import org.opencv.core.Mat
import org.opencv.core.Size
import org.opencv.imgproc.Imgproc
import java.io.IOException
/**
* Pose Estimator
*/
class ImageClassifierFloatInception private constructor(
activity: Activity,
imageSizeX: Int,
imageSizeY: Int,
private val outputW: Int,
private val outputH: Int,
modelPath: String,
numBytesPerChannel: Int = 4 // a 32bit float value requires 4 bytes
) : ImageClassifier(activity, imageSizeX, imageSizeY, modelPath, numBytesPerChannel) {
/**
* An array to hold inference results, to be feed into Tensorflow Lite as outputs.
* This isn't part of the super class, because we need a primitive array here.
*/
private val heatMapArray: Array<Array<Array<FloatArray>>> =
Array(1) { Array(outputW) { Array(outputH) { FloatArray(14) } } }
private var mMat: Mat? = null
override fun addPixelValue(pixelValue: Int) {
//bgr
imgData!!.putFloat((pixelValue and 0xFF).toFloat())
imgData!!.putFloat((pixelValue shr 8 and 0xFF).toFloat())
imgData!!.putFloat((pixelValue shr 16 and 0xFF).toFloat())
}
override fun getProbability(labelIndex: Int): Float {
// return heatMapArray[0][labelIndex];
return 0f
}
override fun setProbability(
labelIndex: Int,
value: Number
) {
// heatMapArray[0][labelIndex] = value.floatValue();
}
override fun getNormalizedProbability(labelIndex: Int): Float {
return getProbability(labelIndex)
}
override fun runInference() {
tflite?.run(imgData!!, heatMapArray)
if (mPrintPointArray == null)
mPrintPointArray = Array(2) { FloatArray(14) }
if (!CameraActivity.isOpenCVInit)
return
// Gaussian Filter 5*5
if (mMat == null)
mMat = Mat(outputW, outputH, CvType.CV_32F)
val tempArray = FloatArray(outputW * outputH)
val outTempArray = FloatArray(outputW * outputH)
for (i in 0..13) {
var index = 0
for (x in 0 until outputW) {
for (y in 0 until outputH) {
tempArray[index] = heatMapArray[0][y][x][i]
index++
}
}
mMat!!.put(0, 0, tempArray)
Imgproc.GaussianBlur(mMat!!, mMat!!, Size(5.0, 5.0), 0.0, 0.0)
mMat!!.get(0, 0, outTempArray)
var maxX = 0f
var maxY = 0f
var max = 0f
// Find keypoint coordinate through maximum values
for (x in 0 until outputW) {
for (y in 0 until outputH) {
val center = get(x, y, outTempArray)
if (center > max) {
max = center
maxX = x.toFloat()
maxY = y.toFloat()
}
}
}
if (max == 0f) {
mPrintPointArray = Array(2) { FloatArray(14) }
return
}
mPrintPointArray!![0][i] = maxX
mPrintPointArray!![1][i] = maxY
// Log.i("TestOutPut", "pic[$i] ($maxX,$maxY) $max")
}
}
private operator fun get(
x: Int,
y: Int,
arr: FloatArray
): Float {
return if (x < 0 || y < 0 || x >= outputW || y >= outputH) -1f else arr[x * outputW + y]
}
companion object {
/**
* Create ImageClassifierFloatInception instance
*
* @param imageSizeX Get the image size along the x axis.
* @param imageSizeY Get the image size along the y axis.
* @param outputW The output width of model
* @param outputH The output height of model
* @param modelPath Get the name of the model file stored in Assets.
* @param numBytesPerChannel Get the number of bytes that is used to store a single
* color channel value.
*/
fun create(
activity: Activity,
imageSizeX: Int = 192,
imageSizeY: Int = 192,
outputW: Int = 48,
outputH: Int = 48,
modelPath: String = "hourglass.tflite",
numBytesPerChannel: Int = 4
): ImageClassifierFloatInception =
ImageClassifierFloatInception(
activity,
imageSizeX,
imageSizeY,
outputW,
outputH,
modelPath,
numBytesPerChannel)
}
}
| 90 | null | 3 | 963 | e31fb850c92ba7e220f861e9484b9cd1bdd5696f | 4,757 | PoseEstimationForMobile | Apache License 2.0 |
core/src/main/kotlin/ca/allanwang/kau/utils/BundleUtils.kt | AllanWang | 93,970,224 | false | {"Gradle": 16, "YAML": 6, "Java Properties": 2, "Shell": 4, "Text": 15, "Ignore List": 14, "Batchfile": 1, "Kotlin": 141, "EditorConfig": 1, "Markdown": 13, "Ruby": 1, "Proguard": 2, "XML": 220, "Java": 4, "HTML": 1, "INI": 1, "SVG": 3, "JSON": 1, "Gradle Kotlin DSL": 2} | /*
* Copyright 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ca.allanwang.kau.utils
import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityOptions
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.util.Pair
import android.view.View
import androidx.annotation.AnimRes
import ca.allanwang.kau.R
import java.io.Serializable
/**
* Created by <NAME> on 10/12/17.
*/
/**
* Similar to [Bundle.putAll], but checks for a null insert and returns the parent bundle
*/
infix fun Bundle.with(bundle: Bundle?): Bundle {
if (bundle != null) putAll(bundle)
return this
}
/**
* Saves all bundle args based on their respective types.
*
* Taken courtesy of <a href="https://github.com/Kotlin/anko">Anko</a>
*
* Previously, Anko was a dependency in KAU, but has been removed on 12/24/2018
* as most of the methods weren't used
*/
fun bundleOf(vararg params: kotlin.Pair<String, Any?>): Bundle {
val b = Bundle()
for (p in params) {
val (k, v) = p
when (v) {
null -> b.putSerializable(k, null)
is Boolean -> b.putBoolean(k, v)
is Byte -> b.putByte(k, v)
is Char -> b.putChar(k, v)
is Short -> b.putShort(k, v)
is Int -> b.putInt(k, v)
is Long -> b.putLong(k, v)
is Float -> b.putFloat(k, v)
is Double -> b.putDouble(k, v)
is String -> b.putString(k, v)
is CharSequence -> b.putCharSequence(k, v)
is Parcelable -> b.putParcelable(k, v)
is Serializable -> b.putSerializable(k, v)
is BooleanArray -> b.putBooleanArray(k, v)
is ByteArray -> b.putByteArray(k, v)
is CharArray -> b.putCharArray(k, v)
is DoubleArray -> b.putDoubleArray(k, v)
is FloatArray -> b.putFloatArray(k, v)
is IntArray -> b.putIntArray(k, v)
is LongArray -> b.putLongArray(k, v)
is Array<*> -> {
@Suppress("UNCHECKED_CAST")
when {
v.isArrayOf<Parcelable>() -> b.putParcelableArray(k, v as Array<out Parcelable>)
v.isArrayOf<CharSequence>() -> b.putCharSequenceArray(k, v as Array<out CharSequence>)
v.isArrayOf<String>() -> b.putStringArray(k, v as Array<out String>)
else -> throw KauException("Unsupported bundle component (${v.javaClass})")
}
}
is ShortArray -> b.putShortArray(k, v)
is Bundle -> b.putBundle(k, v)
else -> throw KauException("Unsupported bundle component (${v.javaClass})")
}
}
return b
}
/**
* Adds transition bundle if context is activity and build is lollipop+
*/
@SuppressLint("NewApi")
fun Bundle.withSceneTransitionAnimation(context: Context) {
if (context !is Activity || !buildIsLollipopAndUp) return
val options = ActivityOptions.makeSceneTransitionAnimation(context)
putAll(options.toBundle())
}
/**
* Given the parent view and map of view ids to tags,
* create a scene transition animation
*/
fun Bundle.withSceneTransitionAnimation(parent: View, data: Map<Int, String>) =
withSceneTransitionAnimation(parent.context, data.mapKeys { (id, _) ->
parent.findViewById<View>(id)
})
/**
* Given a mapping of views to tags,
* create a scene transition animation
*/
@SuppressLint("NewApi")
fun Bundle.withSceneTransitionAnimation(context: Context, data: Map<out View, String>) {
if (context !is Activity || !buildIsLollipopAndUp) return
val options = ActivityOptions.makeSceneTransitionAnimation(
context,
*data.map { (view, tag) -> Pair(view, tag) }.toTypedArray()
)
putAll(options.toBundle())
}
fun Bundle.withCustomAnimation(
context: Context,
@AnimRes enterResId: Int,
@AnimRes exitResId: Int
) {
this with ActivityOptions.makeCustomAnimation(
context,
enterResId, exitResId
).toBundle()
}
fun Bundle.withSlideIn(context: Context) = withCustomAnimation(
context,
R.anim.kau_slide_in_right, R.anim.kau_fade_out
)
fun Bundle.withSlideOut(context: Context) = withCustomAnimation(
context,
R.anim.kau_fade_in, R.anim.kau_slide_out_right_top
)
fun Bundle.withFade(context: Context) = withCustomAnimation(
context,
android.R.anim.fade_in, android.R.anim.fade_out
)
| 5 | Kotlin | 27 | 221 | 259345ccb6c28f24de8b945e9aa5a1f25d610f84 | 4,984 | KAU | Apache License 2.0 |
kcrud-employment/src/main/kotlin/kcrud/domain/Main.kt | perracodex | 682,128,013 | false | {"Kotlin": 649058, "JavaScript": 29040, "CSS": 12723, "HTML": 5862, "Dockerfile": 3125} | /*
* Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license.
*/
package kcrud.domain
/**
* Main function for the employment module.
* This module is not executable. Execute the application server module instead.
*/
public fun main() {
println("Employment module. Execute the application server module instead.")
}
| 0 | Kotlin | 0 | 2 | bb381082eff46b81f9fe803b08a24f718b12339f | 363 | kcrud | MIT License |
app/src/main/kotlin/com/login/app/App.kt | SerhiiVarynytskyi | 217,059,265 | false | null | package com.login.app
import com.login.app.di.component.DaggerAppComponent
import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
class App : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.builder().create(this)
}
override fun onCreate() {
super.onCreate()
}
} | 0 | Kotlin | 0 | 0 | ae0b7390fbf1fe2d06576ca1be187a8c97ab9734 | 398 | social-network-login-helper | MIT License |
save-backend/src/main/kotlin/com/saveourtool/save/backend/repository/AgentRepository.kt | saveourtool | 300,279,336 | false | {"Kotlin": 3413689, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366} | package com.saveourtool.save.backend.repository
import com.saveourtool.save.entities.Agent
import com.saveourtool.save.spring.repository.BaseEntityRepository
import org.springframework.stereotype.Repository
/**
* JPA repository for agents.
*/
@Repository
interface AgentRepository : BaseEntityRepository<Agent> {
/**
* Find agent by its container id
*
* @param containerId container id
* @return [Agent]
*/
fun findByContainerId(containerId: String): Agent?
/**
* Find agent by its container name
*
* @param containerName
* @return [Agent]
*/
fun findByContainerName(containerName: String): Agent?
}
| 201 | Kotlin | 3 | 38 | 7e126d4fb23f8527c47ca9fa27282379759d154e | 671 | save-cloud | MIT License |
shared/src/commonMain/kotlin/presentation/theme/Color.kt | m07med176 | 672,368,552 | false | null | package presentation.theme
import androidx.compose.ui.graphics.Color
object Color{
val red = Color(0xFFFF1100)
val primary = Color(0xFFDB3022)
val secondary = Color(0xFFF9F9F9)
val mainText = Color(0xFF222222)
val lightGray = Color(0xFF9B9B9B)
val Success = Color(0xFF2ED573)
val Warning = Color(0xFFFFBE21)
val Danger = Color(0xFFEA5B5B)
val Background = Color(0xFFFFFFFF)
} | 0 | Kotlin | 0 | 1 | 6f979657f767c2fe5d3b906902e33bf6621f079e | 420 | productApp-compose-multiplatform | Apache License 2.0 |
ERMSEmployee/src/main/java/com/kust/ermsemployee/ui/dashboard/FeatureListingAdapter.kt | sabghat90 | 591,653,827 | false | null | package com.kust.ermsemployee.ui.dashboard
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.kust.ermsemployee.data.model.FeatureModel
import com.kust.ermsemployee.databinding.FeatureItemBinding
class FeatureListingAdapter : RecyclerView.Adapter<FeatureListingAdapter.FeatureListingViewHolder>() {
var features : MutableList<FeatureModel> = arrayListOf()
private lateinit var listener : OnItemClickListener
interface OnItemClickListener {
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: OnItemClickListener) {
this.listener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FeatureListingViewHolder {
val view = FeatureItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return FeatureListingViewHolder(view, listener)
}
override fun onBindViewHolder(holder: FeatureListingViewHolder, position: Int) {
val feature = features[position]
holder.bind(feature, position)
}
override fun getItemCount(): Int {
return features.size
}
inner class FeatureListingViewHolder(private val binding: FeatureItemBinding, listener : OnItemClickListener) : RecyclerView.ViewHolder(binding.root) {
fun bind(feature: FeatureModel, position: Int) {
binding.btnImg.setImageResource(feature.image)
binding.btnFeature.text = feature.title
}
init {
binding.btnFeature.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position)
}
}
}
}
} | 3 | Kotlin | 1 | 7 | 12030507bbd683a1004a19eb9eda78462fe48b81 | 1,797 | ERMS | MIT License |
library/src/main/java/io/karn/notify/entities/Payload.kt | RockySteveJobs | 163,662,488 | true | {"Kotlin": 80107} | package io.karn.notify.entities
import android.app.PendingIntent
import android.graphics.Bitmap
import android.media.RingtoneManager
import android.net.Uri
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.app.NotificationCompat
import io.karn.notify.Notify
import io.karn.notify.R
import io.karn.notify.internal.utils.Action
import io.karn.notify.internal.utils.NotifyImportance
/**
* Wrapper class to provide configurable options for a NotifcationCompact object.
*/
sealed class Payload {
/**
* The Metadata contains configuration that is considered to be such that it controls the
* overall non-layout behaviour of the notification.
*/
data class Meta(
/**
* The handler for a notification click.
*/
var clickIntent: PendingIntent? = null,
/**
* The handler for a dismissal of a notification ('clear all' or swipe away).
*/
var clearIntent: PendingIntent? = null,
/**
* Specifies the behaviour of the notification once it has been clicked. If set to
* false, the notification is not dismissed once it has been clicked.
*/
var cancelOnClick: Boolean = true,
/**
* The category of the notification which allows android to prioritize the
* notification as required.
*/
var category: String? = null,
/**
* Set whether or not this notification is only relevant to the current device.
*/
var localOnly: Boolean = false,
/**
* Indicates whether the notification is sticky. If enabled, the notification is not
* affected by the clear all and is not dismissible.
*/
var sticky: Boolean = false,
/**
* The duration of time in milliseconds after which the notification is automatically dismissed.
*/
var timeout: Long = 0L,
/**
* Add a person that is relevant to this notification.
*
* Depending on user preferences, this may allow the notification to pass through interruption filters, and
* to appear more prominently in the user interface.
*
* The person should be specified by the {@code String} representation of a
* {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}.
*
* The system will also attempt to resolve {@code mailto:} and {@code tel:} schema
* URIs. The path part of these URIs must exist in the contacts database, in the
* appropriate column, or the reference will be discarded as invalid. Telephone schema
* URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}.
*/
internal val contacts: ArrayList<String> = ArrayList()
) {
fun people(init: ArrayList<String>.() -> Unit) {
contacts.init()
}
}
/**
* Defines the alerting configuration for a particular notification. This includes notification
* visibility, sounds, vibrations, etc.
*
* This configuration system may not work as expected on all devices. Refer to the Wiki for more
* information.
*/
data class Alerts(
/**
* The visibility of the notification as it appears on the lockscreen. By default it is
* hidden.
*/
@NotificationCompat.NotificationVisibility var lockScreenVisibility: Int = NotificationCompat.VISIBILITY_PRIVATE,
/**
* The default CHANNEL_ID for a notification on versions >= Android O.
*/
val channelKey: String = Notify.CHANNEL_DEFAULT_KEY,
/**
* The default CHANNEL_NAME for a notification on versions >= Android O.
*/
var channelName: String = Notify.CHANNEL_DEFAULT_NAME,
/**
* The default CHANNEL_DESCRIPTION for a notification on versions >= Android O.
*/
var channelDescription: String = Notify.CHANNEL_DEFAULT_DESCRIPTION,
/**
* The default IMPORTANCE for a notification.
*/
@NotifyImportance var channelImportance: Int = Notify.IMPORTANCE_NORMAL,
/**
* The LED colors of the notification notifyChannel.
*/
@ColorInt var lightColor: Int = Notify.NO_LIGHTS,
/**
* Vibration pattern for notification on this notifyChannel.
*/
var vibrationPattern: List<Long> = ArrayList(),
/**
* A custom notification sound if any.
*/
var sound: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
)
/**
* Contains configuration that is specific to the header of a notification.
*/
data class Header(
/**
* The icon that appears for the notification as a DrawableRes Integer.
*/
@DrawableRes var icon: Int = R.drawable.ic_app_icon,
/**
* The color of the notification items -- icon, appName, and expand indicator.
*/
@ColorInt var color: Int = 0x4A90E2,
/**
* The optional text that appears next to the appName of a notification.
*/
var headerText: CharSequence? = null,
/**
* Setting this field to false results in the timestamp (now, 5m, ...) next to the
* application name to be hidden.
*/
var showTimestamp: Boolean = true
)
/**
* Deterministic property assignment for a notification type.
*/
sealed class Content {
/**
* All 'standard' notifications specify a title and a text field.
*/
interface Standard {
/**
* The first line of a standard notification.
*/
var title: CharSequence?
/**
* The second line of the notification.
*/
var text: CharSequence?
}
interface SupportsLargeIcon {
/**
* The large icon of the notification.
*/
var largeIcon: Bitmap?
}
/**
* Indicates whether a notification is expandable.
*/
interface Expandable {
/**
* The content that is displayed when the notification is expanded expanded.
*/
var expandedText: CharSequence?
}
/**
* The object representation of a 'Default' notification.
*/
data class Default(
override var title: CharSequence? = null,
override var text: CharSequence? = null,
override var largeIcon: Bitmap? = null
) : Content(), Standard, SupportsLargeIcon
/**
* The object representation of a 'TextList' notification.
*/
data class TextList(
override var title: CharSequence? = null,
override var text: CharSequence? = null,
override var largeIcon: Bitmap? = null,
/**
* The lines of the notification.
*/
var lines: List<CharSequence> = ArrayList()
) : Content(), Standard, SupportsLargeIcon
/**
* The object representation of a 'BigText' notification.
*/
data class BigText(
override var title: CharSequence? = null,
override var text: CharSequence? = null,
override var largeIcon: Bitmap? = null,
override var expandedText: CharSequence? = null,
/**
* The large text associated with the notification.
*/
var bigText: CharSequence? = null
) : Content(), Standard, SupportsLargeIcon, Expandable
/**
* The object representation of a 'BigPicture' notification.
*/
data class BigPicture(
override var title: CharSequence? = null,
override var text: CharSequence? = null,
override var largeIcon: Bitmap? = null,
override var expandedText: CharSequence? = null,
/**
* The large image that appears when the notification is expanded.s
*/
var image: Bitmap? = null
) : Content(), Standard, SupportsLargeIcon, Expandable
/**
* The object representaiton of a 'Message' notification.
*/
data class Message(
override var largeIcon: Bitmap? = null,
/**
* The title of the conversation.
*/
var conversationTitle: CharSequence? = null,
/**
* The display name of the device user.
*/
var userDisplayName: CharSequence = "",
/**
* A collection of messages associated with a particualar conversation.
*/
var messages: List<NotificationCompat.MessagingStyle.Message> = ArrayList()
) : Content(), SupportsLargeIcon
}
/**
* Contains configuration specific to the manual stacking behaviour of a notification.
* Manual stacking occurs for all notifications with the same key, additionally the summary
* configuration is taken from the latest notification with the specified stack key.
*/
data class Stackable(
/**
* The key which defines the stack as well as the corresponding notification ID.
*/
var key: String? = null,
/**
* The click intent of the stacked notification.
*/
var clickIntent: PendingIntent? = null,
/**
* The summary content of this particular notification. How it appears in the list of
* notifications in the stack.
*/
var summaryContent: CharSequence? = null,
/**
* The title of the stacked notification.
*
* Takes a function that receives a lambda with the total count of existing
* notifications with the same stack key.
*/
var summaryTitle: ((count: Int) -> String)? = null,
/**
* The second line of the collapsed notification which is meant to show a summary of the
* stack.
*
* Takes a function that receives a lambda with the total count of existing
* notifications with the same stack key.
*/
var summaryDescription: ((count: Int) -> String)? = null,
/**
* The actions associated with the stackable notification when it is stacked. These
* actions override the actions for the individual notification.
*/
internal var stackableActions: ArrayList<Action>? = null
) {
/**
* Scoped function for modifying the behaviour of the actions associated with the 'Stacked'
* notification.
*/
fun actions(init: ArrayList<Action>.() -> Unit) {
this.stackableActions = ArrayList()
this.stackableActions?.init()
}
}
}
| 0 | Kotlin | 0 | 0 | f765689b784dd4afc9ca689b8e818f87914bf645 | 11,686 | notify | MIT License |
app/src/main/java/org/bitbucket/moviex/MainActivity.kt | yuelvic | 146,885,310 | false | null | package org.bitbucket.moviex
import android.os.Bundle
import android.view.Menu
import androidx.appcompat.widget.SearchView
import com.xrojan.rxbus.RxBus
import kotlinx.android.synthetic.main.activity_main.*
import org.bitbucket.moviex.ui.base.BaseActivity
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.options_menu, menu)
val searchView = menu.findItem(R.id.search).actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
RxBus.post(newText!!)
return false
}
})
return true
}
override fun configureViewModel() {
}
override fun configureUI() {
setSupportActionBar(this.toolbar)
}
}
| 0 | Kotlin | 0 | 2 | 20c51bfa3e933967d9cb3451fb8d7ffc0857cd69 | 1,167 | MovieX | The Unlicense |
src/test/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/helper/builders/OffenderBooking.kt | ministryofjustice | 444,895,409 | false | {"Kotlin": 1869814, "PLSQL": 244328, "Dockerfile": 1112} | package uk.gov.justice.digital.hmpps.nomisprisonerapi.helper.builders
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.nomisprisonerapi.helper.builders.PartyRole.WITNESS
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.AdjudicationIncident
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.AdjudicationIncidentParty
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.AgencyInternalLocation
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.AgencyLocation
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.CourseActivity
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Incentive
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.IncidentDecisionAction
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Offender
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.OffenderBooking
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.OffenderKeyDateAdjustment
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.OffenderProgramProfile
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.OffenderSentence
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Staff
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.AgencyInternalLocationRepository
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.AgencyLocationRepository
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.OffenderBookingRepository
import java.time.LocalDate
import java.time.LocalDateTime
@DslMarker
annotation class BookingDslMarker
@NomisDataDslMarker
interface BookingDsl {
@AdjudicationPartyDslMarker
fun adjudicationParty(
incident: AdjudicationIncident,
comment: String = "They witnessed everything",
role: PartyRole = WITNESS,
partyAddedDate: LocalDate = LocalDate.of(2023, 5, 10),
staff: Staff? = null,
adjudicationNumber: Long? = null,
actionDecision: String = IncidentDecisionAction.NO_FURTHER_ACTION_CODE,
dsl: AdjudicationPartyDsl.() -> Unit = {},
): AdjudicationIncidentParty
@IncentiveDslMarker
fun incentive(
iepLevelCode: String = "ENT",
userId: String? = null,
sequence: Long = 1,
commentText: String = "comment",
auditModuleName: String? = null,
iepDateTime: LocalDateTime = LocalDateTime.now(),
): Incentive
@CourseAllocationDslMarker
fun courseAllocation(
courseActivity: CourseActivity,
startDate: String? = "2022-10-31",
programStatusCode: String = "ALLOC",
endDate: String? = null,
endReasonCode: String? = null,
endComment: String? = null,
suspended: Boolean = false,
dsl: CourseAllocationDsl.() -> Unit = { payBand() },
): OffenderProgramProfile
@OffenderSentenceDslMarker
fun sentence(
calculationType: String = "ADIMP_ORA",
category: String = "2003",
startDate: LocalDate = LocalDate.now(),
status: String = "I",
dsl: OffenderSentenceDsl.() -> Unit = { },
): OffenderSentence
@OffenderKeyDateAdjustmentDslMarker
fun adjustment(
adjustmentTypeCode: String = "ADA",
adjustmentDate: LocalDate = LocalDate.now(),
createdDate: LocalDateTime = LocalDateTime.now(), // used in migration date filtering
adjustmentNumberOfDays: Long = 10,
active: Boolean = true,
dsl: OffenderKeyDateAdjustmentDsl.() -> Unit = { },
): OffenderKeyDateAdjustment
}
@Component
class BookingBuilderRepository(
private val offenderBookingRepository: OffenderBookingRepository,
private val agencyLocationRepository: AgencyLocationRepository,
private val agencyInternalLocationRepository: AgencyInternalLocationRepository,
) {
fun save(offenderBooking: OffenderBooking): OffenderBooking = offenderBookingRepository.save(offenderBooking)
fun lookupAgencyLocation(id: String): AgencyLocation = agencyLocationRepository.findByIdOrNull(id)!!
fun lookupAgencyInternalLocation(id: Long): AgencyInternalLocation = agencyInternalLocationRepository.findByIdOrNull(id)!!
}
@Component
class BookingBuilderFactory(
private val repository: BookingBuilderRepository,
private val courseAllocationBuilderFactory: CourseAllocationBuilderFactory,
private val incentiveBuilderFactory: IncentiveBuilderFactory,
private val adjudicationPartyBuilderFactory: AdjudicationPartyBuilderFactory,
private val offenderSentenceBuilderFactory: OffenderSentenceBuilderFactory,
private val offenderKeyDateAdjustmentBuilderFactory: OffenderKeyDateAdjustmentBuilderFactory,
) {
fun builder() = BookingBuilder(
repository,
courseAllocationBuilderFactory,
incentiveBuilderFactory,
adjudicationPartyBuilderFactory,
offenderSentenceBuilderFactory,
offenderKeyDateAdjustmentBuilderFactory,
)
}
class BookingBuilder(
private val repository: BookingBuilderRepository,
private val courseAllocationBuilderFactory: CourseAllocationBuilderFactory,
private val incentiveBuilderFactory: IncentiveBuilderFactory,
private val adjudicationPartyBuilderFactory: AdjudicationPartyBuilderFactory,
private val offenderSentenceBuilderFactory: OffenderSentenceBuilderFactory,
private val offenderKeyDateAdjustmentBuilderFactory: OffenderKeyDateAdjustmentBuilderFactory,
) : BookingDsl {
private lateinit var offenderBooking: OffenderBooking
fun build(
offender: Offender,
bookingSequence: Int,
agencyLocationCode: String,
bookingBeginDate: LocalDateTime = LocalDateTime.now(),
active: Boolean,
inOutStatus: String,
youthAdultCode: String,
livingUnitId: Long,
): OffenderBooking {
val agencyLocation = repository.lookupAgencyLocation(agencyLocationCode)
return OffenderBooking(
offender = offender,
rootOffender = offender,
bookingSequence = bookingSequence,
createLocation = agencyLocation,
location = agencyLocation,
bookingBeginDate = bookingBeginDate,
active = active,
inOutStatus = inOutStatus,
youthAdultCode = youthAdultCode,
assignedLivingUnit = repository.lookupAgencyInternalLocation(livingUnitId),
)
.let { repository.save(it) }
.also { offenderBooking = it }
}
override fun courseAllocation(
courseActivity: CourseActivity,
startDate: String?,
programStatusCode: String,
endDate: String?,
endReasonCode: String?,
endComment: String?,
suspended: Boolean,
dsl: CourseAllocationDsl.() -> Unit,
) =
courseAllocationBuilderFactory.builder()
.let { builder ->
builder.build(offenderBooking, startDate, programStatusCode, endDate, endReasonCode, endComment, suspended, courseActivity)
.also { offenderBooking.offenderProgramProfiles += it }
.also { builder.apply(dsl) }
}
override fun sentence(
calculationType: String,
category: String,
startDate: LocalDate,
status: String,
dsl: OffenderSentenceDsl.() -> Unit,
) =
offenderSentenceBuilderFactory.builder()
.let { builder ->
builder.build(
calculationType = calculationType,
category = category,
startDate = startDate,
status = status,
offenderBooking = offenderBooking,
sequence = offenderBooking.sentences.size.toLong() + 1,
)
.also { offenderBooking.sentences += it }
.also { builder.apply(dsl) }
}
override fun adjustment(
adjustmentTypeCode: String,
adjustmentDate: LocalDate,
createdDate: LocalDateTime,
adjustmentNumberOfDays: Long,
active: Boolean,
dsl: OffenderKeyDateAdjustmentDsl.() -> Unit,
): OffenderKeyDateAdjustment = offenderKeyDateAdjustmentBuilderFactory.builder().let { builder ->
builder.build(
adjustmentTypeCode = adjustmentTypeCode,
adjustmentDate = adjustmentDate,
createdDate = createdDate,
adjustmentNumberOfDays = adjustmentNumberOfDays,
active = active,
offenderBooking = offenderBooking,
)
.also { offenderBooking.keyDateAdjustments += it }
.also { builder.apply(dsl) }
}
override fun incentive(
iepLevelCode: String,
userId: String?,
sequence: Long,
commentText: String,
auditModuleName: String?,
iepDateTime: LocalDateTime,
) =
incentiveBuilderFactory.builder()
.build(
offenderBooking,
iepLevelCode,
userId,
sequence,
commentText,
auditModuleName,
iepDateTime,
)
.also { offenderBooking.incentives += it }
override fun adjudicationParty(
incident: AdjudicationIncident,
comment: String,
role: PartyRole,
partyAddedDate: LocalDate,
staff: Staff?,
adjudicationNumber: Long?,
actionDecision: String,
dsl: AdjudicationPartyDsl.() -> Unit,
) =
adjudicationPartyBuilderFactory.builder().let { builder ->
builder.build(
adjudicationNumber = adjudicationNumber,
comment = comment,
staff = staff,
incidentRole = role.code,
actionDecision = actionDecision,
partyAddedDate = partyAddedDate,
incident = incident,
offenderBooking = offenderBooking,
whenCreated = LocalDateTime.now(),
index = incident.parties.size + 1,
)
.also { incident.parties += it }
.also { builder.apply(dsl) }
}
}
| 1 | Kotlin | 0 | 0 | fc716d6941f50a34d1a5b5863ef6248e9c00892b | 9,316 | hmpps-nomis-prisoner-api | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/personalize/ContinuousHyperParameterRangePropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.personalize
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.personalize.CfnSolution
@Generated
public fun buildContinuousHyperParameterRangeProperty(initializer: @AwsCdkDsl
CfnSolution.ContinuousHyperParameterRangeProperty.Builder.() -> Unit):
CfnSolution.ContinuousHyperParameterRangeProperty =
CfnSolution.ContinuousHyperParameterRangeProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | a1cf8fbfdfef9550b3936de2f864543edb76348b | 529 | aws-cdk-kt | Apache License 2.0 |
test/src/test/kotlin/test/java/integration/core/compile/success/method/resulthelper/ResultHelperTest.kt | afezeria | 456,986,646 | false | null | package test.java.integration.core.compile.success.method.resulthelper
import org.junit.Test
import test.BaseTest
import test.Person
import java.util.*
import kotlin.test.assertContentEquals
/**
*
* @author afezeria
*/
class ResultHelperTest : BaseTest() {
@Test
fun `query return single column`() {
initData(
Person(1, "a"),
Person(2, "a"),
)
val impl =
getJavaDaoInstance<QueryReturnSingleColumnDao>()
val list = impl.query()
assert(list.size == 2)
assertContentEquals(list, listOf(1L, 2L))
}
@Test
fun `query with override constructor parameter mapping`() {
initData(
Person(1, "a"),
Person(2, "a"),
)
val impl =
getJavaDaoInstance<QueryWithOverrideParameterMappingDao>()
val list = impl.query()
assert(list.size == 2)
assertContentEquals(list.map { it.id }, listOf(1L, 2L))
}
@Test
fun `query method return list of HashMap`() {
initData(
Person(1, "a"),
Person(2, "a"),
)
val impl =
getJavaDaoInstance<QueryReturnHashMapListDao>()
val all = impl.query()
assert(all.size == 2)
assertContentEquals(all.map { it["id"] }, listOf(1L, 2L))
}
@Test
fun `query method return list of map`() {
initData(
Person(1, "a"),
Person(2, "a"),
)
val impl =
getJavaDaoInstance<QueryReturnMapListDao>()
val all = impl.query()
assert(all.size == 2)
assertContentEquals(all.map { it["id"] }, listOf(1L, 2L))
}
@Test
fun `query method return list without type argument`() {
initData(
Person(1, "a"),
Person(2, "a"),
)
val impl =
getJavaDaoInstance<QueryReturnListWithoutTypeArgumentDao>()
val all = impl.query()
assert(all.size == 2)
assert(all[0] is Long)
// assertContentEquals(all.map { it.id }, listOf(1, 3))
}
@Test
fun `query method return set`() {
initData(
Person(1, "a"),
Person(2, "a"),
Person(3, "b"),
)
val impl =
getJavaDaoInstance<QueryReturnSetDao>()
val all = impl.list(null)
assert(all is HashSet)
assert(all.size == 2)
assertContentEquals(all.map { it.id }, listOf(1, 3))
}
@Test
fun `query method return collection`() {
initData(
Person(1, "a"),
Person(2, "a"),
)
val impl =
getJavaDaoInstance<QueryReturnCollectionDao>()
val all = impl.list(null)
assert(all is ArrayList)
assert(all.size == 2)
assertContentEquals(all.map { it.id }, listOf(1, 2))
}
@Test
fun `query method return non abstract collection`() {
initData(
Person(1, "a"),
Person(2, "a"),
)
val impl =
getJavaDaoInstance<QueryReturnLinkedListDao>()
val all = impl.list(null)
assert(all is LinkedList)
assert(all.size == 2)
assertContentEquals(all.map { it.id }, listOf(1, 2))
}
} | 0 | Kotlin | 3 | 5 | f52fb74f3805b0518b2f0fce4eb842dee9517a4f | 3,266 | freedao | Apache License 2.0 |
src/main/java/net/dankrushen/danknn/danklayers/IDankOutputLayer.kt | ButterscotchV | 160,415,202 | false | {"Kotlin": 42598} | package net.dankrushen.danknn.danklayers
import net.dankrushen.danknn.DankConnection
interface IDankOutputLayer : IDankLayer {
val inputLayer: IDankInputLayer
val inputConnections: Array<DankConnection>
}
| 0 | Kotlin | 0 | 0 | e875bb2d32155b7272a4ca7715eab9ae0b984990 | 216 | DankNN | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/HomeOff.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.HomeOff: ImageVector
get() {
if (_homeOff != null) {
return _homeOff!!
}
_homeOff = Builder(name = "HomeOff", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(5.0f, 12.0f)
horizontalLineToRelative(-2.0f)
lineToRelative(4.497f, -4.497f)
moveToRelative(2.0f, -2.0f)
lineToRelative(2.504f, -2.504f)
lineToRelative(9.0f, 9.0f)
horizontalLineToRelative(-2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(5.0f, 12.0f)
verticalLineToRelative(7.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, 2.0f)
horizontalLineToRelative(10.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, -2.0f)
moveToRelative(0.0f, -4.0f)
verticalLineToRelative(-3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 21.0f)
verticalLineToRelative(-6.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(2.0f)
moveToRelative(2.0f, 2.0f)
verticalLineToRelative(6.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 3.0f)
lineToRelative(18.0f, 18.0f)
}
}
.build()
return _homeOff!!
}
private var _homeOff: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 3,313 | compose-icon-collections | MIT License |
jetbrains-core/tst/software/aws/toolkits/jetbrains/core/region/MockRegionProvider.kt | JetBrains | 223,485,227 | false | null | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.core.region
import com.intellij.openapi.components.service
import com.intellij.testFramework.ApplicationRule
import software.amazon.awssdk.regions.Region
import software.aws.toolkits.core.region.AwsPartition
import software.aws.toolkits.core.region.AwsRegion
import software.aws.toolkits.core.region.Service
import software.aws.toolkits.core.region.ToolkitRegionProvider
import software.aws.toolkits.core.region.aRegionId
import software.aws.toolkits.core.region.anAwsRegion
import software.aws.toolkits.core.utils.test.aString
import software.aws.toolkits.jetbrains.utils.rules.ClearableLazy
private class MockRegionProvider : ToolkitRegionProvider() {
private val overrideRegions: MutableMap<String, AwsRegion> = mutableMapOf()
private val services: MutableMap<String, Service> = mutableMapOf()
fun addRegion(region: AwsRegion): AwsRegion {
overrideRegions[region.id] = region
return region
}
fun addService(serviceName: String, service: Service) {
services[serviceName] = service
}
fun reset() {
overrideRegions.clear()
services.clear()
}
override fun partitionData(): Map<String, PartitionData> {
val combinedRegions = regions + overrideRegions
return combinedRegions
.asSequence()
.associate {
it.value.partitionId to PartitionData(
it.value.partitionId,
services,
combinedRegions.filterValues { regions -> regions.partitionId == it.value.partitionId }
)
}
}
override fun isServiceGlobal(region: AwsRegion, serviceId: String) =
if (serviceId in services.keys) super.isServiceGlobal(region, serviceId) else false
override fun isServiceSupported(region: AwsRegion, serviceName: String): Boolean = true
override fun defaultPartition(): AwsPartition = AWS_CLASSIC
override fun defaultRegion(): AwsRegion = US_EAST_1
companion object {
private val AWS_CLASSIC = AwsPartition("aws", "AWS Classic", listOf(US_EAST_1))
private val regions = mapOf(US_EAST_1.id to US_EAST_1)
fun getInstance(): MockRegionProvider = service<ToolkitRegionProvider>() as MockRegionProvider
}
}
class MockRegionProviderRule : ApplicationRule() {
private val lazyRegionProvider = ClearableLazy {
MockRegionProvider.getInstance()
}
private val regionManager: MockRegionProvider
get() = lazyRegionProvider.value
fun addRegion(region: AwsRegion): AwsRegion = regionManager.addRegion(region)
fun addRegion(sdkRegion: Region): AwsRegion = regionManager.addRegion(
AwsRegion(
id = sdkRegion.id(),
name = sdkRegion.toString(),
partitionId = sdkRegion.metadata().partition().id()
)
)
fun createAwsRegion(id: String = uniqueRegionId(), partitionId: String = aString()): AwsRegion =
anAwsRegion(id = id, partitionId = partitionId).also { regionManager.addRegion(it) }
private fun uniqueRegionId(): String {
repeat(10) {
val generatedId = aRegionId()
if (regionManager[generatedId] == null) {
return generatedId
}
}
throw IllegalStateException("Failed to generate a unique region ID")
}
fun defaultPartition(): AwsPartition = regionManager.defaultPartition()
fun defaultRegion(): AwsRegion = regionManager.defaultRegion()
fun addService(serviceName: String, service: Service) = regionManager.addService(serviceName, service)
override fun after() {
lazyRegionProvider.ifSet {
reset()
lazyRegionProvider.clear()
}
}
fun reset() {
regionManager.reset()
}
}
// dynamically get the default region from whatever is currently registered
fun getDefaultRegion() = service<ToolkitRegionProvider>().defaultRegion()
val US_EAST_1 = AwsRegion("us-east-1", "US East (N. Virginia)", "aws")
| 7 | null | 4 | 9 | ccee3307fe58ad48f93cd780d4378c336ee20548 | 4,160 | aws-toolkit-jetbrains | Apache License 2.0 |
app/src/main/java/com/sukitsuki/ano/adapter/AnimListAdapter.kt | Tsuki | 176,246,872 | false | null | package com.sukitsuki.ano.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sukitsuki.ano.R
import com.sukitsuki.ano.model.Anim
import kotlinx.android.synthetic.main.view_anime_list_holder.view.*
class AnimListAdapter(val context: Context) : RecyclerView.Adapter<AnimListAdapter.ViewHolder>() {
lateinit var onItemClick: ((Anim) -> Unit)
var oriDataSet: List<Anim> = emptyList()
var dataSet: List<Anim> = emptyList()
fun loadDataSet(newDataSet: List<Anim>) {
oriDataSet = newDataSet
dataSet = oriDataSet
this.notifyDataSetChanged()
}
fun filter(query: String) {
dataSet = if (query == "") oriDataSet
else oriDataSet.filter { it.title.toLowerCase().contains(query.toLowerCase()) }
this.notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val textView =
LayoutInflater.from(parent.context).inflate(R.layout.view_anime_list_holder, parent, false)
return ViewHolder(textView)
}
override fun getItemCount() = dataSet.size
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val anim = dataSet[position]
holder.textView.text = "${anim.title}-${anim.episodeTitle}"
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.animTitle
init {
// to enable marquee
textView.isSelected = true
itemView.setOnClickListener {
onItemClick.invoke(dataSet[adapterPosition])
}
}
}
}
| 0 | Kotlin | 1 | 1 | 9e4f9285e2b1c47068edabf396e268225e583ed1 | 1,755 | ano | MIT License |
core/test/io/github/tozydev/patek/utils/BukkitColorKtTest.kt | tozydev | 773,615,401 | false | {"Kotlin": 120010} | package io.github.tozydev.patek.utils
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class BukkitColorKtTest {
@Test
fun `should parse RGB color with default alpha`() {
val color = BukkitColor("#ff0000")
assertEquals(0xff, color.alpha, "Alpha")
assertEquals(0xff, color.red, "Red")
assertEquals(0, color.green, "Green")
assertEquals(0, color.blue, "Blue")
}
@Test
fun `should parse ARGB color`() {
val color = BukkitColor("#f00000ff")
assertEquals(0xf0, color.alpha, "Alpha")
assertEquals(0, color.red, "Red")
assertEquals(0, color.green, "Green")
assertEquals(0xff, color.blue, "Blue")
}
@Test
fun `should keep the zero alpha when parsing RGB color`() {
val color = BukkitColor("#0000ff00")
assertEquals(0, color.alpha, "Alpha")
assertEquals(0, color.red, "Red")
assertEquals(0xff, color.green, "Green")
assertEquals(0, color.blue, "Blue")
}
@Test
fun `should throws an exception when parsing an invalid color`() {
assertFailsWith<IllegalArgumentException> {
BukkitColor("#ghijklmn")
BukkitColor("1029033334")
}
}
@Test
fun `should parse color from string without hashtag`() {
val color = BukkitColor("ff0000")
assertEquals(0xff, color.alpha, "Alpha")
assertEquals(0xff, color.red, "Red")
assertEquals(0, color.green, "Green")
assertEquals(0, color.blue, "Blue")
}
}
| 0 | Kotlin | 0 | 1 | e7106075bd0a2fc2f41f9039ddcd5ba234d7e786 | 1,578 | patek | MIT License |
library/src/main/java/com/herry/libs/nodeview/model/NodeRoot.kt | HerryPark | 273,154,769 | false | null | package com.herry.libs.nodeview.model
import android.util.Log
class NodeRoot internal constructor(private val notify: NodeNotify, private val log: Boolean = false) : Node<NodeModelGroup>(NodeModelGroup()) {
private var nextNodeId = 0L
private var isTransition = false
private var isNodeSetChanged = false
private var param: NodeNotifyParam? = null
internal fun nextNodeId(): Long {
nextNodeId++
if (nextNodeId == Long.MAX_VALUE) {
nextNodeId = 1L
}
return nextNodeId
}
@Suppress("UNUSED_PARAMETER")
override var parent: Node<*>?
get() = null
set(value) {}
override fun getRoot(): NodeRoot = this
override fun beginTransition() {
isTransition = true
isNodeSetChanged = getViewCount() <= 0
if (log) {
Log.d("node_ui", "beginTransition isNodeSetChanged : $isNodeSetChanged")
}
}
override fun endTransition() {
if (log) {
Log.d("node_ui", "endTransition isTransition : $isTransition isNodeSetChanged : $isNodeSetChanged")
}
if (!isTransition || isNodeSetChanged) {
traversals()
this.param = null
notify.nodeSetChanged()
isNodeSetChanged = false
isTransition = false
} else {
this.param?.let {
applyTo(it)
}
this.param = null
isTransition = false
}
notify.nodeEndTransition()
}
override fun notifyFromChild(param: NodeNotifyParam, then: (() -> Unit)?) {
val success = notify(param, then)
if (!success) {
notify(param, null)
}
}
override fun notify(param: NodeNotifyParam, then: (() -> Unit)?): Boolean {
if (log && then != null) {
Log.d("node_ui", "notify param $param")
}
if (isNodeSetChanged) {
if (log) {
Log.d("node_ui", "notify isNodeSetChanged : TRUE")
}
then?.invoke()
return true
}
if (isTransition) {
val oldParam = this.param
if (oldParam != null) {
val composeParam = oldParam.compose(param)
if (log) {
Log.d("node_ui", "notify isTransition : $isTransition this.param : $oldParam composeParam : $composeParam ")
}
return if (composeParam != null) {
this.param = composeParam
then?.invoke()
true
} else {
applyTo(oldParam)
then?.invoke()
this.param = null
false
}
} else {
if (log) {
Log.d("node_ui", "notify isTransition : $isTransition this.param : null")
}
this.param = param
then?.invoke()
return true
}
} else {
if (log) {
Log.d("node_ui", "notify $isTransition ${getViewCount()}")
}
if (getViewCount() <= 0) {
then?.invoke()
traversals()
this.param = null
notify.nodeSetChanged()
} else {
then?.invoke()
applyTo(param)
}
return true
}
}
private fun applyTo(param: NodeNotifyParam) {
when (param.state) {
NodeNotifyParam.STATE.CHANGE -> {
if (log) {
Log.d("node_ui", "applyTo CHANGED : POS = ${param.position}, CNT = ${param.count}")
}
notify.nodeChanged(param.position, param.count)
}
NodeNotifyParam.STATE.INSERT -> {
if (log) {
Log.d("node_ui", "applyTo INSERTED : POS = ${param.position}, CNT = ${param.count}")
}
traversals()
notify.nodeInserted(param.position, param.count)
}
NodeNotifyParam.STATE.REMOVE -> {
if (log) {
Log.d("node_ui", "applyTo REMOVED : POS = ${param.position}, CNT = ${param.count}")
}
traversals()
notify.nodeRemoved(param.position, param.count)
}
}
}
override fun traversals(): Int {
return nodeChildren.traversals()
}
} | 0 | null | 1 | 3 | d30435c01387614ec24a79ffd5afcdb89edf5298 | 4,538 | HerryApiDemo | Apache License 2.0 |
android/engine/src/test/java/org/smartregister/fhircore/engine/sync/AppTimeStampContextTest.kt | opensrp | 339,242,809 | false | null | /*
* Copyright 2021-2023 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.engine.sync
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import java.time.OffsetDateTime
import javax.inject.Inject
import kotlinx.coroutines.test.runTest
import org.hl7.fhir.r4.model.ResourceType
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.smartregister.fhircore.engine.robolectric.RobolectricTest
import org.smartregister.fhircore.engine.util.SharedPreferencesHelper
@HiltAndroidTest
class AppTimeStampContextTest : RobolectricTest() {
@get:Rule(order = 0) val hiltAndroidRule = HiltAndroidRule(this)
@Inject lateinit var sharedPreference: SharedPreferencesHelper
private lateinit var appTimeStampContext: AppTimeStampContext
@Before
fun setUp() {
hiltAndroidRule.inject()
appTimeStampContext = AppTimeStampContext(sharedPreference)
}
@Test
fun testGetLastUpdateTimestampShouldReturnTimestamp() {
runTest {
// No timestamp saved for ResourceType Patient
Assert.assertNull(appTimeStampContext.getLasUpdateTimestamp(ResourceType.Patient))
val currentTimestamp = OffsetDateTime.now().toString()
appTimeStampContext.saveLastUpdatedTimestamp(ResourceType.Patient, currentTimestamp)
Assert.assertEquals(
currentTimestamp,
appTimeStampContext.getLasUpdateTimestamp(ResourceType.Patient)
)
}
}
@Test
fun saveLastUpdatedTimestampShouldSaveTimestampForResource() {
runTest {
val currentTimestamp = OffsetDateTime.now().toString()
appTimeStampContext.saveLastUpdatedTimestamp(ResourceType.CarePlan, currentTimestamp)
Assert.assertEquals(
currentTimestamp,
sharedPreference.read("CAREPLAN_LAST_SYNC_TIMESTAMP", null)
)
}
}
}
| 192 | null | 56 | 56 | 64a55e6920cb6280cf02a0d68152d9c03266518d | 2,421 | fhircore | Apache License 2.0 |
app/src/main/java/com/example/arturo/mycomics/ui/navigation/Navigator.kt | artjimlop | 96,988,205 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Kotlin": 60, "Proguard": 2, "XML": 17, "Java": 3} | package com.example.arturo.mycomics.ui.navigation
import android.content.Context
import android.content.Intent
import com.example.arturo.mycomics.ui.comics.models.ComicModel
import com.example.arturo.mycomics.ui.comics.views.ComicDetailActivity
import javax.inject.Inject
class Navigator @Inject constructor() {
fun goToComicDetail(context: Context, comicModel: ComicModel) {
val comicDetailIntent = Intent(context, ComicDetailActivity::class.java)
comicDetailIntent.putExtra(ComicDetailActivity.EXTRA_COMIC.toString(), comicModel.id)
context.startActivity(comicDetailIntent)
}
}
| 1 | null | 1 | 1 | e12c3df7736be0f28d1b2d9dd523129aaf817f98 | 615 | clean-architecture-kotlin | Apache License 2.0 |
app/src/androidTest/java/com/sample/android/tmdb/main/TestUpcomingTVSeries.kt | Ali-Rezaei | 158,464,119 | false | null | package com.sample.android.tmdb.ui.paging.main.movie
import android.content.Context
import android.content.Intent
import androidx.test.InstrumentationRegistry
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import com.sample.android.tmdb.ui.paging.main.BaseMainActivity
import org.junit.Rule
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class TestTrendingMovies : BaseMainActivity() {
@Rule
@JvmField
val activityTestRule: ActivityTestRule<TrendingMoviesActivity> =
object : ActivityTestRule<TrendingMoviesActivity>(
TrendingMoviesActivity::class.java
) {
override fun getActivityIntent(): Intent {
val targetContext: Context =
InstrumentationRegistry.getInstrumentation().targetContext
return Intent(targetContext, TrendingMoviesActivity::class.java)
}
}
override val title: String
get() = "Trending Movies"
} | 1 | null | 8 | 70 | ea80dd0481f141e55e0d06073d50676758073d34 | 1,055 | TMDb-Paging | The Unlicense |
src/main/kotlin/edu/put_the_machine/scrapper/model/dto/parser/LessonTimeInterval.kt | sstu-iksp | 338,553,080 | false | {"Gradle": 1, "Gradle Kotlin DSL": 1, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 52, "HTML": 6, "JSON": 6, "Kotlin": 22, "YAML": 1} | package edu.put_the_machine.scrapper.model.dto.parser
import java.time.LocalDate
import java.time.LocalTime
data class LessonTimeInterval(
val start: LocalTime,
val end: LocalTime,
val date: LocalDate
)
| 1 | null | 1 | 1 | f0559981d2330d57d9682633cf777711e96ea192 | 219 | schedule-scrapper | MIT License |
control_client/src/main/java/at/rmbt/client/control/MapServerClient.kt | rtr-nettest | 195,193,208 | false | {"Kotlin": 1584817, "Java": 669959, "HTML": 43778, "Shell": 4061} | package at.rmbt.client.control
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import at.rmbt.client.control.data.MapPresentationType
import at.rmbt.util.Maybe
import okhttp3.ResponseBody
import retrofit2.Response
import timber.log.Timber
import javax.inject.Inject
class MapServerClient @Inject constructor(
private val endpointProvider: MapEndpointProvider,
private val api: MapServerApi
) {
fun getMarkers(body: MarkersRequestBody): Maybe<MarkersResponse> {
return api.getMarkers(endpointProvider.getMapMarkersUrl, body).exec()
}
fun loadTiles(x: Int, y: Int, zoom: Int, type: MapPresentationType, filters: Map<String, String> = HashMap()): Response<ResponseBody>? {
return try {
val url = String.format(endpointProvider.getMapTilesUrl, type.value, zoom, x, y)
val uriBuilder = Uri.parse(url).buildUpon()
for (entry in filters.entries) {
uriBuilder.appendQueryParameter(entry.key, entry.value)
}
api.loadTiles(uriBuilder.build().toString()).execute()
} catch(e: Exception) {
Timber.e("Map tiles loading exception ${e.localizedMessage}")
null
}
}
fun prepareDetailsLink(openUUID: String) =
MutableLiveData<String>().apply { postValue(String.format(endpointProvider.mapMarkerShowDetailsUrl, openUUID)) }
fun obtainMapFiltersInfo(body: FilterLanguageRequestBody): Maybe<MapFilterResponse> = api.getFilters(endpointProvider.mapFilterInfoUrl, body).exec()
fun obtainNationalTable(): Maybe<NationalTableResponse> = api.loadOperators(endpointProvider.nettestHeader, endpointProvider.getNationalTableUrl).exec()
} | 1 | Kotlin | 12 | 28 | 4b0754a8bdbf1203ecc5961f642105ec131a9536 | 1,708 | open-rmbt-android | Apache License 2.0 |
objects/src/commonMain/kotlin/ru/krindra/vkkt/objects/ads/AdsTargSuggestionsSchoolsType.kt | krindra | 780,080,411 | false | null | package ru.krindra.vknorthtypes.ads
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class AdsTargSuggestionsSchoolsType(val value: String){
@SerialName("school") SCHOOL("school"),
@SerialName("university") UNIVERSITY("university"),
@SerialName("faculty") FACULTY("faculty"),
@SerialName("chair") CHAIR("chair"),
}
| 0 | null | 0 | 1 | 58407ea02fc9d971f86702f3b822b33df65dd3be | 385 | VKKT | MIT License |
processing-tests/common/test/kotlin/com/livefront/sealedenum/compilation/hierarchy/SealedInterfaceHierarchy.kt | livefront | 244,991,153 | false | null | package com.livefront.sealedenum.compilation.hierarchy
import com.livefront.sealedenum.GenSealedEnum
import org.intellij.lang.annotations.Language
class FirstInterfaceHierarchy {
sealed interface A {
sealed interface B : A {
object C : B
@GenSealedEnum(generateEnum = true)
companion object
}
@GenSealedEnum(generateEnum = true)
companion object
}
}
@Language("kotlin")
val firstInterfaceHierarchyAGenerated = """
package com.livefront.sealedenum.compilation.hierarchy
import com.livefront.sealedenum.EnumForSealedEnumProvider
import com.livefront.sealedenum.SealedEnum
import com.livefront.sealedenum.SealedEnumWithEnumProvider
import kotlin.Int
import kotlin.LazyThreadSafetyMode
import kotlin.String
import kotlin.collections.List
import kotlin.reflect.KClass
/**
* An isomorphic enum for the sealed class [FirstInterfaceHierarchy.A]
*/
public enum class FirstInterfaceHierarchy_AEnum() {
FirstInterfaceHierarchy_A_B_C,
}
/**
* The isomorphic [FirstInterfaceHierarchy_AEnum] for [this].
*/
public val FirstInterfaceHierarchy.A.`enum`: FirstInterfaceHierarchy_AEnum
get() = FirstInterfaceHierarchy_ASealedEnum.sealedObjectToEnum(this)
/**
* The isomorphic [FirstInterfaceHierarchy.A] for [this].
*/
public val FirstInterfaceHierarchy_AEnum.sealedObject: FirstInterfaceHierarchy.A
get() = FirstInterfaceHierarchy_ASealedEnum.enumToSealedObject(this)
/**
* An implementation of [SealedEnum] for the sealed class [FirstInterfaceHierarchy.A]
*/
public object FirstInterfaceHierarchy_ASealedEnum : SealedEnum<FirstInterfaceHierarchy.A>,
SealedEnumWithEnumProvider<FirstInterfaceHierarchy.A, FirstInterfaceHierarchy_AEnum>,
EnumForSealedEnumProvider<FirstInterfaceHierarchy.A, FirstInterfaceHierarchy_AEnum> {
public override val values: List<FirstInterfaceHierarchy.A> by lazy(mode =
LazyThreadSafetyMode.PUBLICATION) {
listOf(
FirstInterfaceHierarchy.A.B.C
)
}
public override val enumClass: KClass<FirstInterfaceHierarchy_AEnum>
get() = FirstInterfaceHierarchy_AEnum::class
public override fun ordinalOf(obj: FirstInterfaceHierarchy.A): Int = when (obj) {
is FirstInterfaceHierarchy.A.B.C -> 0
}
public override fun nameOf(obj: FirstInterfaceHierarchy.A): String = when (obj) {
is FirstInterfaceHierarchy.A.B.C -> "FirstInterfaceHierarchy_A_B_C"
}
public override fun valueOf(name: String): FirstInterfaceHierarchy.A = when (name) {
"FirstInterfaceHierarchy_A_B_C" -> FirstInterfaceHierarchy.A.B.C
else -> throw IllegalArgumentException(""${'"'}No sealed enum constant ${'$'}name""${'"'})
}
public override fun sealedObjectToEnum(obj: FirstInterfaceHierarchy.A):
FirstInterfaceHierarchy_AEnum = when (obj) {
is FirstInterfaceHierarchy.A.B.C ->
FirstInterfaceHierarchy_AEnum.FirstInterfaceHierarchy_A_B_C
}
public override fun enumToSealedObject(`enum`: FirstInterfaceHierarchy_AEnum):
FirstInterfaceHierarchy.A = when (enum) {
FirstInterfaceHierarchy_AEnum.FirstInterfaceHierarchy_A_B_C -> FirstInterfaceHierarchy.A.B.C
}
}
/**
* The index of [this] in the values list.
*/
public val FirstInterfaceHierarchy.A.ordinal: Int
get() = FirstInterfaceHierarchy_ASealedEnum.ordinalOf(this)
/**
* The name of [this] for use with valueOf.
*/
public val FirstInterfaceHierarchy.A.name: String
get() = FirstInterfaceHierarchy_ASealedEnum.nameOf(this)
/**
* A list of all [FirstInterfaceHierarchy.A] objects.
*/
public val FirstInterfaceHierarchy.A.Companion.values: List<FirstInterfaceHierarchy.A>
get() = FirstInterfaceHierarchy_ASealedEnum.values
/**
* Returns an implementation of [SealedEnum] for the sealed class [FirstInterfaceHierarchy.A]
*/
public val FirstInterfaceHierarchy.A.Companion.sealedEnum: FirstInterfaceHierarchy_ASealedEnum
get() = FirstInterfaceHierarchy_ASealedEnum
/**
* Returns the [FirstInterfaceHierarchy.A] object for the given [name].
*
* If the given name doesn't correspond to any [FirstInterfaceHierarchy.A], an
* [IllegalArgumentException] will be thrown.
*/
public fun FirstInterfaceHierarchy.A.Companion.valueOf(name: String): FirstInterfaceHierarchy.A =
FirstInterfaceHierarchy_ASealedEnum.valueOf(name)
""".trimIndent()
@Language("kotlin")
val firstInterfaceHierarchyBGenerated = """
package com.livefront.sealedenum.compilation.hierarchy
import com.livefront.sealedenum.EnumForSealedEnumProvider
import com.livefront.sealedenum.SealedEnum
import com.livefront.sealedenum.SealedEnumWithEnumProvider
import kotlin.Int
import kotlin.LazyThreadSafetyMode
import kotlin.String
import kotlin.collections.List
import kotlin.reflect.KClass
/**
* An isomorphic enum for the sealed class [FirstInterfaceHierarchy.A.B]
*/
public enum class FirstInterfaceHierarchy_A_BEnum() {
FirstInterfaceHierarchy_A_B_C,
}
/**
* The isomorphic [FirstInterfaceHierarchy_A_BEnum] for [this].
*/
public val FirstInterfaceHierarchy.A.B.`enum`: FirstInterfaceHierarchy_A_BEnum
get() = FirstInterfaceHierarchy_A_BSealedEnum.sealedObjectToEnum(this)
/**
* The isomorphic [FirstInterfaceHierarchy.A.B] for [this].
*/
public val FirstInterfaceHierarchy_A_BEnum.sealedObject: FirstInterfaceHierarchy.A.B
get() = FirstInterfaceHierarchy_A_BSealedEnum.enumToSealedObject(this)
/**
* An implementation of [SealedEnum] for the sealed class [FirstInterfaceHierarchy.A.B]
*/
public object FirstInterfaceHierarchy_A_BSealedEnum : SealedEnum<FirstInterfaceHierarchy.A.B>,
SealedEnumWithEnumProvider<FirstInterfaceHierarchy.A.B, FirstInterfaceHierarchy_A_BEnum>,
EnumForSealedEnumProvider<FirstInterfaceHierarchy.A.B, FirstInterfaceHierarchy_A_BEnum> {
public override val values: List<FirstInterfaceHierarchy.A.B> by lazy(mode =
LazyThreadSafetyMode.PUBLICATION) {
listOf(
FirstInterfaceHierarchy.A.B.C
)
}
public override val enumClass: KClass<FirstInterfaceHierarchy_A_BEnum>
get() = FirstInterfaceHierarchy_A_BEnum::class
public override fun ordinalOf(obj: FirstInterfaceHierarchy.A.B): Int = when (obj) {
is FirstInterfaceHierarchy.A.B.C -> 0
}
public override fun nameOf(obj: FirstInterfaceHierarchy.A.B): String = when (obj) {
is FirstInterfaceHierarchy.A.B.C -> "FirstInterfaceHierarchy_A_B_C"
}
public override fun valueOf(name: String): FirstInterfaceHierarchy.A.B = when (name) {
"FirstInterfaceHierarchy_A_B_C" -> FirstInterfaceHierarchy.A.B.C
else -> throw IllegalArgumentException(""${'"'}No sealed enum constant ${'$'}name""${'"'})
}
public override fun sealedObjectToEnum(obj: FirstInterfaceHierarchy.A.B):
FirstInterfaceHierarchy_A_BEnum = when (obj) {
is FirstInterfaceHierarchy.A.B.C ->
FirstInterfaceHierarchy_A_BEnum.FirstInterfaceHierarchy_A_B_C
}
public override fun enumToSealedObject(`enum`: FirstInterfaceHierarchy_A_BEnum):
FirstInterfaceHierarchy.A.B = when (enum) {
FirstInterfaceHierarchy_A_BEnum.FirstInterfaceHierarchy_A_B_C ->
FirstInterfaceHierarchy.A.B.C
}
}
/**
* The index of [this] in the values list.
*/
public val FirstInterfaceHierarchy.A.B.ordinal: Int
get() = FirstInterfaceHierarchy_A_BSealedEnum.ordinalOf(this)
/**
* The name of [this] for use with valueOf.
*/
public val FirstInterfaceHierarchy.A.B.name: String
get() = FirstInterfaceHierarchy_A_BSealedEnum.nameOf(this)
/**
* A list of all [FirstInterfaceHierarchy.A.B] objects.
*/
public val FirstInterfaceHierarchy.A.B.Companion.values: List<FirstInterfaceHierarchy.A.B>
get() = FirstInterfaceHierarchy_A_BSealedEnum.values
/**
* Returns an implementation of [SealedEnum] for the sealed class [FirstInterfaceHierarchy.A.B]
*/
public val FirstInterfaceHierarchy.A.B.Companion.sealedEnum: FirstInterfaceHierarchy_A_BSealedEnum
get() = FirstInterfaceHierarchy_A_BSealedEnum
/**
* Returns the [FirstInterfaceHierarchy.A.B] object for the given [name].
*
* If the given name doesn't correspond to any [FirstInterfaceHierarchy.A.B], an
* [IllegalArgumentException] will be thrown.
*/
public fun FirstInterfaceHierarchy.A.B.Companion.valueOf(name: String): FirstInterfaceHierarchy.A.B
= FirstInterfaceHierarchy_A_BSealedEnum.valueOf(name)
""".trimIndent()
class SecondInterfaceHierarchy {
sealed interface A {
object B : A
sealed interface C : A {
object D : C
object E : C
sealed interface F : C {
object G : F
@GenSealedEnum
companion object
}
sealed interface H : C {
object I : H
@GenSealedEnum
companion object
}
@GenSealedEnum
companion object
}
sealed interface J : A {
object K : J
@GenSealedEnum
companion object
}
object L : A
@GenSealedEnum
companion object
}
}
@Language("kotlin")
val secondInterfaceHierarchyAGenerated = """
package com.livefront.sealedenum.compilation.hierarchy
import com.livefront.sealedenum.SealedEnum
import kotlin.Int
import kotlin.LazyThreadSafetyMode
import kotlin.String
import kotlin.collections.List
/**
* An implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A]
*/
public object SecondInterfaceHierarchy_ASealedEnum : SealedEnum<SecondInterfaceHierarchy.A> {
public override val values: List<SecondInterfaceHierarchy.A> by lazy(mode =
LazyThreadSafetyMode.PUBLICATION) {
listOf(
SecondInterfaceHierarchy.A.B,
SecondInterfaceHierarchy.A.C.D,
SecondInterfaceHierarchy.A.C.E,
SecondInterfaceHierarchy.A.C.F.G,
SecondInterfaceHierarchy.A.C.H.I,
SecondInterfaceHierarchy.A.J.K,
SecondInterfaceHierarchy.A.L
)
}
public override fun ordinalOf(obj: SecondInterfaceHierarchy.A): Int = when (obj) {
is SecondInterfaceHierarchy.A.B -> 0
is SecondInterfaceHierarchy.A.C.D -> 1
is SecondInterfaceHierarchy.A.C.E -> 2
is SecondInterfaceHierarchy.A.C.F.G -> 3
is SecondInterfaceHierarchy.A.C.H.I -> 4
is SecondInterfaceHierarchy.A.J.K -> 5
is SecondInterfaceHierarchy.A.L -> 6
}
public override fun nameOf(obj: SecondInterfaceHierarchy.A): String = when (obj) {
is SecondInterfaceHierarchy.A.B -> "SecondInterfaceHierarchy_A_B"
is SecondInterfaceHierarchy.A.C.D -> "SecondInterfaceHierarchy_A_C_D"
is SecondInterfaceHierarchy.A.C.E -> "SecondInterfaceHierarchy_A_C_E"
is SecondInterfaceHierarchy.A.C.F.G -> "SecondInterfaceHierarchy_A_C_F_G"
is SecondInterfaceHierarchy.A.C.H.I -> "SecondInterfaceHierarchy_A_C_H_I"
is SecondInterfaceHierarchy.A.J.K -> "SecondInterfaceHierarchy_A_J_K"
is SecondInterfaceHierarchy.A.L -> "SecondInterfaceHierarchy_A_L"
}
public override fun valueOf(name: String): SecondInterfaceHierarchy.A = when (name) {
"SecondInterfaceHierarchy_A_B" -> SecondInterfaceHierarchy.A.B
"SecondInterfaceHierarchy_A_C_D" -> SecondInterfaceHierarchy.A.C.D
"SecondInterfaceHierarchy_A_C_E" -> SecondInterfaceHierarchy.A.C.E
"SecondInterfaceHierarchy_A_C_F_G" -> SecondInterfaceHierarchy.A.C.F.G
"SecondInterfaceHierarchy_A_C_H_I" -> SecondInterfaceHierarchy.A.C.H.I
"SecondInterfaceHierarchy_A_J_K" -> SecondInterfaceHierarchy.A.J.K
"SecondInterfaceHierarchy_A_L" -> SecondInterfaceHierarchy.A.L
else -> throw IllegalArgumentException(""${'"'}No sealed enum constant ${'$'}name""${'"'})
}
}
/**
* The index of [this] in the values list.
*/
public val SecondInterfaceHierarchy.A.ordinal: Int
get() = SecondInterfaceHierarchy_ASealedEnum.ordinalOf(this)
/**
* The name of [this] for use with valueOf.
*/
public val SecondInterfaceHierarchy.A.name: String
get() = SecondInterfaceHierarchy_ASealedEnum.nameOf(this)
/**
* A list of all [SecondInterfaceHierarchy.A] objects.
*/
public val SecondInterfaceHierarchy.A.Companion.values: List<SecondInterfaceHierarchy.A>
get() = SecondInterfaceHierarchy_ASealedEnum.values
/**
* Returns an implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A]
*/
public val SecondInterfaceHierarchy.A.Companion.sealedEnum: SecondInterfaceHierarchy_ASealedEnum
get() = SecondInterfaceHierarchy_ASealedEnum
/**
* Returns the [SecondInterfaceHierarchy.A] object for the given [name].
*
* If the given name doesn't correspond to any [SecondInterfaceHierarchy.A], an
* [IllegalArgumentException] will be thrown.
*/
public fun SecondInterfaceHierarchy.A.Companion.valueOf(name: String): SecondInterfaceHierarchy.A =
SecondInterfaceHierarchy_ASealedEnum.valueOf(name)
""".trimIndent()
@Language("kotlin")
val secondInterfaceHierarchyACGenerated = """
package com.livefront.sealedenum.compilation.hierarchy
import com.livefront.sealedenum.SealedEnum
import kotlin.Int
import kotlin.LazyThreadSafetyMode
import kotlin.String
import kotlin.collections.List
/**
* An implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A.C]
*/
public object SecondInterfaceHierarchy_A_CSealedEnum : SealedEnum<SecondInterfaceHierarchy.A.C> {
public override val values: List<SecondInterfaceHierarchy.A.C> by lazy(mode =
LazyThreadSafetyMode.PUBLICATION) {
listOf(
SecondInterfaceHierarchy.A.C.D,
SecondInterfaceHierarchy.A.C.E,
SecondInterfaceHierarchy.A.C.F.G,
SecondInterfaceHierarchy.A.C.H.I
)
}
public override fun ordinalOf(obj: SecondInterfaceHierarchy.A.C): Int = when (obj) {
is SecondInterfaceHierarchy.A.C.D -> 0
is SecondInterfaceHierarchy.A.C.E -> 1
is SecondInterfaceHierarchy.A.C.F.G -> 2
is SecondInterfaceHierarchy.A.C.H.I -> 3
}
public override fun nameOf(obj: SecondInterfaceHierarchy.A.C): String = when (obj) {
is SecondInterfaceHierarchy.A.C.D -> "SecondInterfaceHierarchy_A_C_D"
is SecondInterfaceHierarchy.A.C.E -> "SecondInterfaceHierarchy_A_C_E"
is SecondInterfaceHierarchy.A.C.F.G -> "SecondInterfaceHierarchy_A_C_F_G"
is SecondInterfaceHierarchy.A.C.H.I -> "SecondInterfaceHierarchy_A_C_H_I"
}
public override fun valueOf(name: String): SecondInterfaceHierarchy.A.C = when (name) {
"SecondInterfaceHierarchy_A_C_D" -> SecondInterfaceHierarchy.A.C.D
"SecondInterfaceHierarchy_A_C_E" -> SecondInterfaceHierarchy.A.C.E
"SecondInterfaceHierarchy_A_C_F_G" -> SecondInterfaceHierarchy.A.C.F.G
"SecondInterfaceHierarchy_A_C_H_I" -> SecondInterfaceHierarchy.A.C.H.I
else -> throw IllegalArgumentException(""${'"'}No sealed enum constant ${'$'}name""${'"'})
}
}
/**
* The index of [this] in the values list.
*/
public val SecondInterfaceHierarchy.A.C.ordinal: Int
get() = SecondInterfaceHierarchy_A_CSealedEnum.ordinalOf(this)
/**
* The name of [this] for use with valueOf.
*/
public val SecondInterfaceHierarchy.A.C.name: String
get() = SecondInterfaceHierarchy_A_CSealedEnum.nameOf(this)
/**
* A list of all [SecondInterfaceHierarchy.A.C] objects.
*/
public val SecondInterfaceHierarchy.A.C.Companion.values: List<SecondInterfaceHierarchy.A.C>
get() = SecondInterfaceHierarchy_A_CSealedEnum.values
/**
* Returns an implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A.C]
*/
public val SecondInterfaceHierarchy.A.C.Companion.sealedEnum: SecondInterfaceHierarchy_A_CSealedEnum
get() = SecondInterfaceHierarchy_A_CSealedEnum
/**
* Returns the [SecondInterfaceHierarchy.A.C] object for the given [name].
*
* If the given name doesn't correspond to any [SecondInterfaceHierarchy.A.C], an
* [IllegalArgumentException] will be thrown.
*/
public fun SecondInterfaceHierarchy.A.C.Companion.valueOf(name: String):
SecondInterfaceHierarchy.A.C = SecondInterfaceHierarchy_A_CSealedEnum.valueOf(name)
""".trimIndent()
@Language("kotlin")
val secondInterfaceHierarchyACFGenerated = """
package com.livefront.sealedenum.compilation.hierarchy
import com.livefront.sealedenum.SealedEnum
import kotlin.Int
import kotlin.LazyThreadSafetyMode
import kotlin.String
import kotlin.collections.List
/**
* An implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A.C.F]
*/
public object SecondInterfaceHierarchy_A_C_FSealedEnum : SealedEnum<SecondInterfaceHierarchy.A.C.F>
{
public override val values: List<SecondInterfaceHierarchy.A.C.F> by lazy(mode =
LazyThreadSafetyMode.PUBLICATION) {
listOf(
SecondInterfaceHierarchy.A.C.F.G
)
}
public override fun ordinalOf(obj: SecondInterfaceHierarchy.A.C.F): Int = when (obj) {
is SecondInterfaceHierarchy.A.C.F.G -> 0
}
public override fun nameOf(obj: SecondInterfaceHierarchy.A.C.F): String = when (obj) {
is SecondInterfaceHierarchy.A.C.F.G -> "SecondInterfaceHierarchy_A_C_F_G"
}
public override fun valueOf(name: String): SecondInterfaceHierarchy.A.C.F = when (name) {
"SecondInterfaceHierarchy_A_C_F_G" -> SecondInterfaceHierarchy.A.C.F.G
else -> throw IllegalArgumentException(""${'"'}No sealed enum constant ${'$'}name""${'"'})
}
}
/**
* The index of [this] in the values list.
*/
public val SecondInterfaceHierarchy.A.C.F.ordinal: Int
get() = SecondInterfaceHierarchy_A_C_FSealedEnum.ordinalOf(this)
/**
* The name of [this] for use with valueOf.
*/
public val SecondInterfaceHierarchy.A.C.F.name: String
get() = SecondInterfaceHierarchy_A_C_FSealedEnum.nameOf(this)
/**
* A list of all [SecondInterfaceHierarchy.A.C.F] objects.
*/
public val SecondInterfaceHierarchy.A.C.F.Companion.values: List<SecondInterfaceHierarchy.A.C.F>
get() = SecondInterfaceHierarchy_A_C_FSealedEnum.values
/**
* Returns an implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A.C.F]
*/
public val SecondInterfaceHierarchy.A.C.F.Companion.sealedEnum:
SecondInterfaceHierarchy_A_C_FSealedEnum
get() = SecondInterfaceHierarchy_A_C_FSealedEnum
/**
* Returns the [SecondInterfaceHierarchy.A.C.F] object for the given [name].
*
* If the given name doesn't correspond to any [SecondInterfaceHierarchy.A.C.F], an
* [IllegalArgumentException] will be thrown.
*/
public fun SecondInterfaceHierarchy.A.C.F.Companion.valueOf(name: String):
SecondInterfaceHierarchy.A.C.F = SecondInterfaceHierarchy_A_C_FSealedEnum.valueOf(name)
""".trimIndent()
@Language("kotlin")
val secondInterfaceHierarchyACHGenerated = """
package com.livefront.sealedenum.compilation.hierarchy
import com.livefront.sealedenum.SealedEnum
import kotlin.Int
import kotlin.LazyThreadSafetyMode
import kotlin.String
import kotlin.collections.List
/**
* An implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A.C.H]
*/
public object SecondInterfaceHierarchy_A_C_HSealedEnum : SealedEnum<SecondInterfaceHierarchy.A.C.H>
{
public override val values: List<SecondInterfaceHierarchy.A.C.H> by lazy(mode =
LazyThreadSafetyMode.PUBLICATION) {
listOf(
SecondInterfaceHierarchy.A.C.H.I
)
}
public override fun ordinalOf(obj: SecondInterfaceHierarchy.A.C.H): Int = when (obj) {
is SecondInterfaceHierarchy.A.C.H.I -> 0
}
public override fun nameOf(obj: SecondInterfaceHierarchy.A.C.H): String = when (obj) {
is SecondInterfaceHierarchy.A.C.H.I -> "SecondInterfaceHierarchy_A_C_H_I"
}
public override fun valueOf(name: String): SecondInterfaceHierarchy.A.C.H = when (name) {
"SecondInterfaceHierarchy_A_C_H_I" -> SecondInterfaceHierarchy.A.C.H.I
else -> throw IllegalArgumentException(""${'"'}No sealed enum constant ${'$'}name""${'"'})
}
}
/**
* The index of [this] in the values list.
*/
public val SecondInterfaceHierarchy.A.C.H.ordinal: Int
get() = SecondInterfaceHierarchy_A_C_HSealedEnum.ordinalOf(this)
/**
* The name of [this] for use with valueOf.
*/
public val SecondInterfaceHierarchy.A.C.H.name: String
get() = SecondInterfaceHierarchy_A_C_HSealedEnum.nameOf(this)
/**
* A list of all [SecondInterfaceHierarchy.A.C.H] objects.
*/
public val SecondInterfaceHierarchy.A.C.H.Companion.values: List<SecondInterfaceHierarchy.A.C.H>
get() = SecondInterfaceHierarchy_A_C_HSealedEnum.values
/**
* Returns an implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A.C.H]
*/
public val SecondInterfaceHierarchy.A.C.H.Companion.sealedEnum:
SecondInterfaceHierarchy_A_C_HSealedEnum
get() = SecondInterfaceHierarchy_A_C_HSealedEnum
/**
* Returns the [SecondInterfaceHierarchy.A.C.H] object for the given [name].
*
* If the given name doesn't correspond to any [SecondInterfaceHierarchy.A.C.H], an
* [IllegalArgumentException] will be thrown.
*/
public fun SecondInterfaceHierarchy.A.C.H.Companion.valueOf(name: String):
SecondInterfaceHierarchy.A.C.H = SecondInterfaceHierarchy_A_C_HSealedEnum.valueOf(name)
""".trimIndent()
@Language("kotlin")
val secondInterfaceHierarchyAJGenerated = """
package com.livefront.sealedenum.compilation.hierarchy
import com.livefront.sealedenum.SealedEnum
import kotlin.Int
import kotlin.LazyThreadSafetyMode
import kotlin.String
import kotlin.collections.List
/**
* An implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A.J]
*/
public object SecondInterfaceHierarchy_A_JSealedEnum : SealedEnum<SecondInterfaceHierarchy.A.J> {
public override val values: List<SecondInterfaceHierarchy.A.J> by lazy(mode =
LazyThreadSafetyMode.PUBLICATION) {
listOf(
SecondInterfaceHierarchy.A.J.K
)
}
public override fun ordinalOf(obj: SecondInterfaceHierarchy.A.J): Int = when (obj) {
is SecondInterfaceHierarchy.A.J.K -> 0
}
public override fun nameOf(obj: SecondInterfaceHierarchy.A.J): String = when (obj) {
is SecondInterfaceHierarchy.A.J.K -> "SecondInterfaceHierarchy_A_J_K"
}
public override fun valueOf(name: String): SecondInterfaceHierarchy.A.J = when (name) {
"SecondInterfaceHierarchy_A_J_K" -> SecondInterfaceHierarchy.A.J.K
else -> throw IllegalArgumentException(""${'"'}No sealed enum constant ${'$'}name""${'"'})
}
}
/**
* The index of [this] in the values list.
*/
public val SecondInterfaceHierarchy.A.J.ordinal: Int
get() = SecondInterfaceHierarchy_A_JSealedEnum.ordinalOf(this)
/**
* The name of [this] for use with valueOf.
*/
public val SecondInterfaceHierarchy.A.J.name: String
get() = SecondInterfaceHierarchy_A_JSealedEnum.nameOf(this)
/**
* A list of all [SecondInterfaceHierarchy.A.J] objects.
*/
public val SecondInterfaceHierarchy.A.J.Companion.values: List<SecondInterfaceHierarchy.A.J>
get() = SecondInterfaceHierarchy_A_JSealedEnum.values
/**
* Returns an implementation of [SealedEnum] for the sealed class [SecondInterfaceHierarchy.A.J]
*/
public val SecondInterfaceHierarchy.A.J.Companion.sealedEnum: SecondInterfaceHierarchy_A_JSealedEnum
get() = SecondInterfaceHierarchy_A_JSealedEnum
/**
* Returns the [SecondInterfaceHierarchy.A.J] object for the given [name].
*
* If the given name doesn't correspond to any [SecondInterfaceHierarchy.A.J], an
* [IllegalArgumentException] will be thrown.
*/
public fun SecondInterfaceHierarchy.A.J.Companion.valueOf(name: String):
SecondInterfaceHierarchy.A.J = SecondInterfaceHierarchy_A_JSealedEnum.valueOf(name)
""".trimIndent()
| 6 | Kotlin | 7 | 87 | 00b8f3753c71ed7cdd82a9c5e822f9e558ffb8c1 | 23,946 | sealed-enum | Apache License 2.0 |
3247.Number of Subsequences with Odd Sum.kt | sarvex | 842,260,390 | false | {"Kotlin": 1775678, "PowerShell": 418} | internal class Solution {
fun subsequenceCount(nums: IntArray): Int {
val mod = 1e9.toInt() + 7
var f = IntArray(2)
for (x in nums) {
val g = IntArray(2)
if (x % 2 == 1) {
g[0] = (f[0] + f[1]) % mod
g[1] = (f[0] + f[1] + 1) % mod
} else {
g[0] = (f[0] + f[0] + 1) % mod
g[1] = (f[1] + f[1]) % mod
}
f = g
}
return f[1]
}
}
| 0 | Kotlin | 0 | 0 | 17a80985d970c8316fb694e4952692e598d700af | 409 | kotlin-leetcode | MIT License |
src/br/ufal/ic/ufood/data/user/UserRepositoryImpl.kt | koallann | 225,185,269 | false | {"Kotlin": 60836} | package br.ufal.ic.ufood.data.user
import br.ufal.ic.ufood.domain.Address
import br.ufal.ic.ufood.domain.Credentials
import br.ufal.ic.ufood.domain.User
import br.ufal.ic.ufood.domain.coupon.BreakfastCoupon
import br.ufal.ic.ufood.domain.coupon.Coupon
import br.ufal.ic.ufood.domain.coupon.DinnerCoupon
import br.ufal.ic.ufood.domain.coupon.LunchCoupon
class UserRepositoryImpl : UserRepository {
companion object {
private val validCouponCodes: Map<String, Coupon> by lazy {
hashMapOf(
"BREAKFAST_5" to BreakfastCoupon(),
"LUNCH_10" to LunchCoupon(),
"DINNER_8" to DinnerCoupon(),
"XyZ_coupon_10" to LunchCoupon()
)
}
private val users: MutableMap<String, User> by lazy { HashMap<String, User>() }
private val addresses: MutableMap<String, MutableList<Address>> by lazy { HashMap<String, MutableList<Address>>() }
private val coupons: MutableMap<String, MutableSet<Coupon>> by lazy { HashMap<String, MutableSet<Coupon>>() }
}
@Throws(IllegalArgumentException::class)
override fun signIn(credentials: Credentials): User {
val user = users[credentials.email]
if (user == null || user.credentials != credentials) {
throw IllegalArgumentException("Invalid email and/or password.")
}
return user
}
@Throws(IllegalArgumentException::class)
override fun signUp(user: User) {
if (users.containsKey(user.credentials.email)) {
throw IllegalArgumentException("Already used email.")
}
users[user.credentials.email] = user
}
override fun getAddresses(user: User): List<Address> {
return addresses[user.credentials.email] ?: emptyList()
}
@Throws(IllegalArgumentException::class)
override fun getAddress(user: User, addressId: Int): Address {
val addresses = addresses[user.credentials.email]
if (addresses == null || addressId !in 0 until addresses.size) {
throw IllegalArgumentException("Invalid address ID.")
}
return addresses[addressId]
}
override fun addAddress(user: User, address: Address) {
if (addresses[user.credentials.email] == null) {
addresses[user.credentials.email] = arrayListOf()
}
addresses[user.credentials.email]?.add(address)
}
override fun deleteAddress(user: User, addressId: Int) {
val addresses = addresses[user.credentials.email]
if (addresses != null && addressId in 0 until addresses.size) {
addresses.removeAt(addressId)
} else {
throw IllegalArgumentException("Invalid address ID.")
}
}
override fun getCoupons(user: User): List<Coupon> {
return coupons[user.credentials.email]?.toList() ?: emptyList()
}
@Throws(IllegalArgumentException::class)
override fun getCoupon(user: User, couponId: Int): Coupon {
val coupons = coupons[user.credentials.email]
if (coupons == null || couponId !in 0 until coupons.size) {
throw IllegalArgumentException("Invalid coupon ID.")
}
return coupons.toList()[couponId]
}
override fun deleteCoupon(user: User, couponId: Int) {
val coupons = coupons[user.credentials.email]
if (coupons != null && couponId in 0 until coupons.size) {
val coupon = coupons.toList()[couponId]
coupons.remove(coupon)
}
}
@Throws(IllegalArgumentException::class)
override fun applyCouponCode(user: User, couponCode: String) {
val coupon = validCouponCodes[couponCode] ?: throw IllegalArgumentException("Invalid coupon.")
if (coupons[user.credentials.email] == null) {
coupons[user.credentials.email] = hashSetOf()
}
if (coupons[user.credentials.email]?.add(coupon) == false) {
throw IllegalArgumentException("Coupon already added.")
}
}
}
| 0 | Kotlin | 0 | 0 | 83980d84cec3f08d08c627302976e5876dbc8b3b | 4,013 | uFood | Apache License 2.0 |
src/jsMain/kotlin/events_interactions_animations/detectCoordinates.kt | petertiupe | 432,820,771 | false | null | package events_interactions_animations
import de.tiupe.Selection
import de.tiupe.d3
import org.w3c.dom.Node
import org.w3c.dom.events.Event
fun detectCoordinates(){
console.log("detectCoordinates läuft")
pixelCoordinates("#detectCoordinatesSvg")
}
private fun pixelCoordinates(selctorString: String) {
val text = d3.select(selctorString)
.append("text")
val svg = d3.select(selctorString)
svg.attr("cursor", "crosshair")
.on("mousemove") { event: Event ->
console.log("$event")
val pointer = d3.pointer(event )
text.attr("x", 18 + pointer[0] ).attr("y", 6 + pointer[1] )
.text("${pointer[0]},${pointer[1]}")
}
} | 0 | Kotlin | 0 | 0 | f46e7c8f24d58ba62d4ad29db20ae2326aff748d | 718 | f2kd3 | MIT License |
app/src/wallet/java/com/merative/healthpass/ui/landing/LandingViewModel.kt | digitalhealthpass | 563,978,682 | false | {"Kotlin": 1047923, "HTML": 79495, "Python": 22113, "Java": 1959} | package com.merative.healthpass.ui.landing
import androidx.lifecycle.ViewModel
import com.merative.healthpass.models.sharedPref.ContactPackage
import com.merative.healthpass.ui.region.EnvironmentHandler
import com.merative.healthpass.utils.pref.ContactDB
import com.merative.healthpass.utils.pref.IssuerMetadataDB
import com.merative.healthpass.utils.pref.SchemaDB
import com.merative.healthpass.utils.pref.SharedPrefUtils
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Maybe
import javax.inject.Inject
class LandingViewModel @Inject constructor(
val sharedPrefUtils: SharedPrefUtils,
private val environmentHandler: EnvironmentHandler,
private val contactDB: ContactDB,
private val schemaDB: SchemaDB,
private val metadataDB: IssuerMetadataDB,
) : ViewModel() {
var issuersLoaded: Boolean = false
fun isTermsAccepted(): Boolean {
return sharedPrefUtils.getBoolean(SharedPrefUtils.KEY_TERMS_ACCEPTED)
}
fun isPrivacyAccepted(): Boolean {
return sharedPrefUtils.getBoolean(SharedPrefUtils.KEY_PRIVACY_ACCEPTED)
}
fun canShowTutorial(): Boolean {
return !sharedPrefUtils.getBoolean(SharedPrefUtils.KEY_TUTORIAL_SHOWN)
}
fun shouldDisableFeatureForRegion() = environmentHandler.shouldDisableFeatureForRegion()
fun hasPin(): Boolean = sharedPrefUtils.hasPin()
fun hasPinSkipped(): Boolean = sharedPrefUtils.hasPinSkipped()
fun isTimeToResetCache(): Boolean {
val autoReset = sharedPrefUtils.getAutoReset()
if (autoReset.isEnabled and autoReset.isTimeToReset()) {
return true
}
return false
}
fun resetCache(): Completable {
return schemaDB.deleteAll()
.andThen(metadataDB.deleteAll())
}
fun isEnvRegionSet(): Boolean = environmentHandler.isEnvRegionSet()
fun loadContact(profileCredId: String): Maybe<ContactPackage> {
return contactDB.loadAll().map { it.dataList }
.flatMapMaybe { contactPackageList ->
Maybe.create<ContactPackage> { emitter ->
val contactPackage = contactPackageList.firstOrNull { contactPackage ->
contactPackage.profilePackage?.verifiableObject?.credential?.id?.contains(profileCredId) == true
}
if (contactPackage != null) {
emitter.onSuccess(contactPackage)
} else {
emitter.onComplete()
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 2b086f6fad007d1a574f8f0511fff0e65e100930 | 2,573 | dhp-android-app | Apache License 2.0 |
app/src/androidTest/kotlin/mobi/akesson/jdm/ExampleTest.kt | akesson | 55,406,276 | false | null | package mobi.akesson.jdm
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* [Testing Fundamentals](http://d.android.com/tools/testing/testing_android.html)
*/
@RunWith(AndroidJUnit4::class)
class ExampleTest {
@get:Rule
val activityRule = ActivityTestRule(MainActivity::class.java)
@Test fun exemple() {
}
} | 4 | null | 0 | 0 | 140197c8e0feee71fedb37ba94e30eb4755b831d | 459 | JdM-Android | Apache License 2.0 |
src/test/kotlin/FinancialManagerTest.kt | gustavoarruda | 644,958,483 | false | null | import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import java.time.LocalDate
class FinancialManagerTest {
private lateinit var manager: FinancialManager
@Before
fun setUp() {
manager = FinancialManager()
}
@Test
fun testAddAsset() {
val asset = FinancialAsset("PETR4", "RV", 10, 50.0)
manager.addAsset(asset)
assertEquals(1, manager.getAssets().size)
}
@Test
fun testAddTransaction() {
val asset = FinancialAsset("PETR4", "RV", 10, 50.0)
val transaction = Transaction(LocalDate.now(), asset, 200.0)
manager.addTransaction(transaction)
assertEquals(1, manager.getTransactions().size)
assertEquals(200.0, manager.getCurrentBalance(), 0.0)
}
@Test
fun testGetAssetValue() {
val asset1 = FinancialAsset("PETR4", "RV", 10, 50.0)
val asset2 = FinancialAsset("GOOG", "RV", 5, 40.0)
manager.addAsset(asset1)
manager.addAsset(asset2)
assertEquals(700.0, manager.getAssetValue(), 0.0)
}
@Test
fun testGetCurrentBalance() {
val asset = FinancialAsset("PETR4", "RV", 10, 50.0)
val transaction = Transaction(LocalDate.now(), asset, 200.0)
manager.addTransaction(transaction)
assertEquals(200.0, manager.getCurrentBalance(), 0.0)
}
} | 0 | Kotlin | 0 | 0 | 8e2115d30937fd3612a7a322fcb06b78b2f5e006 | 1,367 | FinancialManagerFinal | MIT License |
plugin/src/main/kotlin/com/varabyte/kobweb/intellij/services/project/KobwebProjectCacheService.kt | varabyte | 745,632,890 | false | {"Kotlin": 69311} | package com.varabyte.kobweb.intellij.services.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.varabyte.kobweb.intellij.project.KobwebProject
import com.varabyte.kobweb.intellij.util.psi.containingKlib
import org.jetbrains.kotlin.idea.base.util.module
import java.util.*
/**
* A project service which caches [KobwebProject]s, allowing for quick lookups of whether a given element is part of one.
*
* Callers can fetch this service and then either register Kobweb Projects with it or query it.
*
* Knowing if you're inside a Kobweb project can be useful before running an inspection or action, so that we don't
* waste time processing code that isn't relevant to Kobweb (e.g. if we're in a multiplatform project with Kobweb,
* Android, and other types of modules).
*
* Note there's also an option to mark an element as explicitly NOT being part of a Kobweb project. This allows early
* aborting on followup checks, allowing the caller to distinguish the difference between "get returns null because
* this is not a kobweb project" vs "get returns null because we haven't put the value in the cache yet".
*
* @see KobwebProject
*/
interface KobwebProjectCacheService : Iterable<KobwebProject> {
operator fun get(module: Module): KobwebProject?
operator fun get(klib: VirtualFile): KobwebProject?
// This does NOT accept module / klib parameters like the `get` methods, because we need to support elements that
// potentially don't live in either a module nor a klib.
fun isNotKobweb(element: PsiElement): Boolean
fun add(project: KobwebProject)
fun addAll(collection: Collection<KobwebProject>)
fun markNonKobweb(element: PsiElement)
fun clear()
}
private class KobwebProjectCacheServiceImpl : KobwebProjectCacheService {
private val localProjects = Collections.synchronizedMap(mutableMapOf<Module, KobwebProject>())
private val externalProjects = Collections.synchronizedMap(mutableMapOf<VirtualFile, KobwebProject>())
private val nonKobwebProjects = Collections.synchronizedSet(mutableSetOf<Any>())
override operator fun get(module: Module) = localProjects[module]
override operator fun get(klib: VirtualFile) = externalProjects[klib]
override fun add(project: KobwebProject) {
when (project.source) {
is KobwebProject.Source.External -> externalProjects[project.source.klib] = project
is KobwebProject.Source.Local -> localProjects[project.source.module] = project
}
}
// There are easily thousands of elements in a project, so it would be wasteful to store each one individually.
// Instead, we return a container as broad as possible and store that.
private fun PsiElement.toElementContainer(): Any = module ?: containingKlib ?: containingFile
override fun isNotKobweb(element: PsiElement): Boolean {
return nonKobwebProjects.contains(element.toElementContainer())
}
override fun addAll(collection: Collection<KobwebProject>) {
collection.forEach { add(it) }
}
override fun markNonKobweb(element: PsiElement) {
nonKobwebProjects.add(element.toElementContainer())
}
override fun clear() {
externalProjects.clear()
localProjects.clear()
}
override fun iterator(): Iterator<KobwebProject> {
return (localProjects.values + externalProjects.values).iterator()
}
override fun toString(): String {
return "KobwebProjects${this.iterator().asSequence().joinToString(prefix = "[", postfix = "]") { it.name }}"
}
}
| 30 | Kotlin | 1 | 6 | cd01ca55e46653611903862730442da88fbbf1f4 | 3,646 | kobweb-intellij-plugin | Apache License 2.0 |
event-queue/src/main/kotlin/io/kommons/designpatterns/eventqueue/Audio.kt | debop | 235,066,649 | false | null | package io.kommons.designpatterns.eventqueue
import io.kommons.logging.KLogging
import io.kommons.logging.trace
import java.io.File
import java.io.IOException
import javax.sound.sampled.AudioInputStream
import javax.sound.sampled.AudioSystem
import javax.sound.sampled.LineUnavailableException
import kotlin.concurrent.thread
class Audio {
companion object: KLogging() {
const val MAX_PENDING = 16
private val INSTANCE = Audio()
fun getInstance(): Audio = INSTANCE
}
private var headIndex: Int = 0
private var tailIndex: Int = 0
@Volatile
private var updateThread: Thread? = null
val pendingAudio: Array<PlayMessage?> = Array(16) { null }
/**
* This method stops the Update Method's thread and waits till service stops.
*/
@Synchronized
fun stopService() {
updateThread?.interrupt()
updateThread?.join()
updateThread = null
}
/**
* Check the Update Method's thread is started.
*/
val isServiceRunning: Boolean get() = updateThread?.isAlive ?: false
/**
* Starts the thread for the Update Method pattern if it was not started previously. Also when the
* thread is is ready initializes the indexes of the queue
*/
fun init() {
if (updateThread == null) {
updateThread = thread(start = false) {
while (!Thread.currentThread().isInterrupted) {
update()
}
}
}
startThread()
}
@Synchronized
private fun startThread() {
assert(updateThread != null)
if (!updateThread!!.isAlive) {
updateThread!!.start()
headIndex = 0
tailIndex = 0
}
}
fun playSound(stream: AudioInputStream, volume: Float) {
init()
var i = headIndex
while (i != tailIndex) {
log.trace { "Get pending audio. index=$i" }
val playMessage = pendingAudio[i]
if (playMessage != null && playMessage.stream == stream) {
playMessage.volume = maxOf(volume, playMessage.volume)
return
}
i = (i + 1) % MAX_PENDING
}
pendingAudio[tailIndex] = PlayMessage(stream, volume)
tailIndex = (tailIndex + 1) % MAX_PENDING
}
/**
* This method uses the Update Method pattern. It takes the audio from the queue and plays it
*/
private fun update() {
// If there are no pending requests, do nothing.
if (headIndex == tailIndex) {
return
}
try {
val audioStream = pendingAudio[headIndex]!!.stream
headIndex++
val clip = AudioSystem.getClip()
clip.open(audioStream)
clip.start()
} catch (e: LineUnavailableException) {
log.trace { "Error occurred while loading thre audio: The line is unavailable" }
} catch (e: IOException) {
log.trace { "Input/Output error while loading the audio" }
} catch (e: IllegalArgumentException) {
log.trace { "The system doesn't support the sound: ${e.message}" }
}
}
fun getAudioStream(filePath: String): AudioInputStream =
AudioSystem.getAudioInputStream(File(filePath).absoluteFile)
} | 0 | Kotlin | 11 | 53 | c00bcc0542985bbcfc4652d0045f31e5c1304a70 | 3,340 | kotlin-design-patterns | Apache License 2.0 |
app/src/main/java/com/comjeong/nomadworker/domain/model/signin/SignInResult.kt | HUFSummer-Hackathon | 512,365,622 | false | null | package com.comjeong.nomadworker.domain.model.signin
data class SignInResult(
val message: String,
val status: Int,
val data: Result
) {
data class Result(
val userId: Long,
val userProfileImageUrl: String?,
val nickname: String?,
val accessToken: String?,
val latitude: Float,
val longitude: Float
)
}
| 2 | Kotlin | 0 | 0 | 5857dbe020888785367e0e4596a7b342aa1ec4a7 | 372 | NomadWorker-Android | MIT License |
module-server/src/main/kotlin/de/twomartens/wahlrecht/configuration/PropertyConfiguration.kt | 2martens | 673,979,017 | false | null | package de.twomartens.wahlrecht.configuration
import de.twomartens.wahlrecht.property.RestTemplateTimeoutProperties
import de.twomartens.wahlrecht.property.ServiceProperties
import de.twomartens.wahlrecht.property.StatusProbeProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Configuration
@Configuration
@EnableConfigurationProperties(RestTemplateTimeoutProperties::class, ServiceProperties::class,
StatusProbeProperties::class)
open class PropertyConfiguration | 0 | Kotlin | 0 | 0 | c3699d44a7fd4576302b3c7c0f5969e40e24587a | 555 | wahlrecht | Apache License 2.0 |
client/src/main/java/com/fesskiev/compose/ui/screens/EditNoteScreen.kt | fesskiev | 328,395,075 | false | null | package com.fesskiev.compose.ui.screens
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.fesskiev.compose.R
import com.fesskiev.compose.state.EditNoteUiState
import com.fesskiev.compose.ui.components.AsciiTextField
import com.fesskiev.compose.ui.components.ProgressBar
@Composable
fun EditNoteScreen(
uiState: EditNoteUiState,
onEditedNoteClick: () -> Unit,
onEditNoteChangedTitle: (String) -> Unit,
onEditNoteChangedDescription: (String) -> Unit,
onScreenClose: () -> Unit
) {
when {
uiState.loading -> ProgressBar()
uiState.editNoteSuccess -> { LaunchedEffect(Unit) { onScreenClose() } }
else -> {
EditNoteContent(
uiState = uiState,
onEditedClick = { onEditedNoteClick() },
onChangedTitle = { onEditNoteChangedTitle(it) },
onChangedDescription = { onEditNoteChangedDescription(it) }
)
}
}
}
@Composable
fun EditNoteContent(
uiState: EditNoteUiState,
onEditedClick: () -> Unit,
onChangedTitle: (String) -> Unit,
onChangedDescription: (String) -> Unit
) {
val isEmptyTitle = uiState.editNoteUserInputState.isEmptyTitleError
val isEmptyDescription = uiState.editNoteUserInputState.isEmptyDescriptionError
val titleLabel = when {
isEmptyTitle -> stringResource(R.string.error_empty_title)
else -> stringResource(R.string.note_title)
}
val descriptionLabel = when {
isEmptyDescription -> stringResource(R.string.error_empty_desc)
else -> stringResource(R.string.note_description)
}
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(Modifier.height(4.dp))
AsciiTextField(
label = titleLabel,
value = uiState.title,
textStyle = MaterialTheme.typography.subtitle1,
onValueChange = onChangedTitle,
isError = uiState.title.isEmpty()
)
Spacer(Modifier.height(20.dp))
AsciiTextField(
label = descriptionLabel,
value = uiState.description,
textStyle = MaterialTheme.typography.body2,
onValueChange = onChangedDescription,
isError = uiState.description.isEmpty(),
)
Button(
modifier = Modifier
.padding(top = 8.dp)
.height(48.dp)
.align(Alignment.End),
onClick = onEditedClick
) {
Text(stringResource(R.string.submit))
}
}
}
| 0 | Kotlin | 0 | 0 | eb50aeadbd1b33dc4f83859d63acc1ab5672e525 | 3,168 | NotesClientServerApp | MIT License |
data/src/main/java/com/nemesis/rio/data/mplus/seasons/database/SeasonsDao.kt | N3-M3-S1S | 370,791,918 | false | null | package com.nemesis.rio.data.mplus.seasons.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.nemesis.rio.domain.game.Expansion
import com.nemesis.rio.domain.mplus.seasons.Season
@Dao
abstract class SeasonsDao {
@Query("SELECT name FROM seasons WHERE expansion = :expansion ORDER BY id DESC")
abstract suspend fun getSeasonsForExpansion(expansion: Expansion): List<Season>
@Query("SELECT id FROM seasons WHERE api_value = :seasonApiValue")
abstract suspend fun getSeasonIdByApiValue(seasonApiValue: String): Int?
@Query("SELECT name FROM seasons WHERE id = (SELECT MAX(id) FROM seasons)")
abstract suspend fun getLastAddedSeason(): Season
@Query("SELECT api_value FROM seasons")
abstract suspend fun getSeasonApiValues(): List<String>
@Query("SELECT api_value FROM seasons WHERE name = :season")
abstract suspend fun getSeasonApiValue(season: Season): String
@Insert(onConflict = OnConflictStrategy.REPLACE)
internal abstract suspend fun save(seasonEntities: List<SeasonEntity>)
}
| 0 | Kotlin | 0 | 0 | 62dc309a7b4b80ff36ea624bacfa7b00b5d8607e | 1,126 | rio | MIT License |
core-kotlin-modules/core-kotlin-arrays/src/test/kotlin/com/baeldung/array/ArrayReorderUnitTest.kt | Baeldung | 260,481,121 | false | null | package cn.tuyucheng.taketoday.array
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import kotlin.random.Random
class ArrayReorderUnitTest {
lateinit var numbers: Array<Int>
@BeforeEach
fun setUp() {
numbers = arrayOf(3, 2, 50, 15, 10, 1)
}
@Test
fun `Given an array of int values, Then check the values on complete array reversal`() {
numbers.reverse()
Assertions.assertEquals(1, numbers[0])
Assertions.assertEquals(10, numbers[1])
Assertions.assertEquals(15, numbers[2])
Assertions.assertEquals(50, numbers[3])
Assertions.assertEquals(2, numbers[4])
Assertions.assertEquals(3, numbers[5])
}
@Test
fun `Given an array of int values, Then check the values on partial array reversal`() {
numbers.reverse(4, 6)
Assertions.assertEquals(3, numbers[0])
Assertions.assertEquals(2, numbers[1])
Assertions.assertEquals(50, numbers[2])
Assertions.assertEquals(15, numbers[3])
Assertions.assertEquals(1, numbers[4])
Assertions.assertEquals(10, numbers[5])
}
@Test
fun `Given an array of int values, Then check the values on complete array sort`() {
numbers.sort()
Assertions.assertEquals(1, numbers[0])
Assertions.assertEquals(2, numbers[1])
Assertions.assertEquals(3, numbers[2])
Assertions.assertEquals(10, numbers[3])
Assertions.assertEquals(15, numbers[4])
Assertions.assertEquals(50, numbers[5])
}
@Test
fun `Given an array of int values, Then check the values on partial array sort after an index`() {
numbers.sort(4)
Assertions.assertEquals(3, numbers[0])
Assertions.assertEquals(2, numbers[1])
Assertions.assertEquals(50, numbers[2])
Assertions.assertEquals(15, numbers[3])
Assertions.assertEquals(1, numbers[4])
Assertions.assertEquals(10, numbers[5])
}
@Test
fun `Given an array of int values, Then check the values on partial array sort between indices`() {
numbers.sort(0, 2)
Assertions.assertEquals(2, numbers[0])
Assertions.assertEquals(3, numbers[1])
Assertions.assertEquals(50, numbers[2])
Assertions.assertEquals(15, numbers[3])
Assertions.assertEquals(10, numbers[4])
Assertions.assertEquals(1, numbers[5])
}
@Test
fun `Given an array of int values, Then check when shuffled with a constant seed`() {
numbers.shuffle(Random(2))
Assertions.assertEquals(1, numbers[0])
Assertions.assertEquals(3, numbers[1])
Assertions.assertEquals(50, numbers[2])
Assertions.assertEquals(15, numbers[3])
Assertions.assertEquals(10, numbers[4])
Assertions.assertEquals(2, numbers[5])
}
} | 14 | null | 6 | 465 | f1ef5d5ded3f7ddc647f1b6119f211068f704577 | 2,560 | kotlin-tutorials | MIT License |
src/main/kotlin/xyz/bluspring/nicknamer/integrations/NicknamerModMenuIntegration.kt | BluSpring | 567,541,296 | false | {"Kotlin": 67338, "Java": 9529} | package xyz.bluspring.nicknamer.integrations
import com.terraformersmc.modmenu.api.ConfigScreenFactory
import com.terraformersmc.modmenu.api.ModMenuApi
import me.shedaniel.clothconfig2.api.ConfigBuilder
import net.minecraft.text.Text
import xyz.bluspring.nicknamer.config.ConfigManager
class NicknamerModMenuIntegration : ModMenuApi {
override fun getModConfigScreenFactory(): ConfigScreenFactory<*> {
return ConfigScreenFactory {
ConfigBuilder.create().apply {
parentScreen = it
title = Text.literal("Nicknamer Config")
setSavingRunnable {
ConfigManager.save()
}
getOrCreateCategory(Text.literal("General")).apply {
addEntry(
entryBuilder()
.startBooleanToggle(
Text.literal("Is enabled?"),
ConfigManager.config.enabled
)
.setDefaultValue(false)
.setSaveConsumer {
ConfigManager.config.enabled = it
}
.build()
)
addEntry(
entryBuilder()
.startBooleanToggle(
Text.literal("Display pronouns below nameplate?"),
ConfigManager.config.displayPronounsBelowUsername
)
.setDefaultValue(true)
.setSaveConsumer {
ConfigManager.config.displayPronounsBelowUsername = it
}
.build()
)
}
getOrCreateCategory(Text.literal("In-game Name Format")).apply {
setDescription(
listOf(
Text.literal("Sets what the name will look like on the nameplate."),
Text.literal("%username% - Username"),
Text.literal("%nickname% - Nickname"),
Text.literal("%pronouns% - Pronouns")
).toTypedArray()
)
ConfigManager.config.inGameFormat.forEach { (nameFormat, format) ->
addEntry(
entryBuilder()
.startTextField(Text.literal(nameFormat.displayName), format)
.setDefaultValue("%username% (%nickname%)")
.setSaveConsumer {
ConfigManager.config.inGameFormat[nameFormat] = it
}
.build()
)
}
}
getOrCreateCategory(Text.literal("Player List Name Format")).apply {
setDescription(
listOf(
Text.literal("Sets what the name will look like on the player list."),
Text.literal("%username% - Username"),
Text.literal("%nickname% - Nickname"),
Text.literal("%pronouns% - Pronouns")
).toTypedArray()
)
ConfigManager.config.playerListFormat.forEach { (nameFormat, format) ->
addEntry(
entryBuilder()
.startTextField(Text.literal(nameFormat.displayName), format)
.setDefaultValue("%username% (%nickname%) - [%pronouns%]")
.setSaveConsumer {
ConfigManager.config.playerListFormat[nameFormat] = it
}
.build()
)
}
}
getOrCreateCategory(Text.literal("Chat Format")).apply {
setDescription(
listOf(
Text.literal("Sets what the name will look like in the chat."),
Text.literal("%username% - Username"),
Text.literal("%nickname% - Nickname"),
Text.literal("%pronouns% - Pronouns")
).toTypedArray()
)
ConfigManager.config.chatFormat.forEach { (nameFormat, format) ->
addEntry(
entryBuilder()
.startTextField(Text.literal(nameFormat.displayName), format)
.setDefaultValue("%username% (%nickname%) - [%pronouns%]")
.setSaveConsumer {
ConfigManager.config.chatFormat[nameFormat] = it
}
.build()
)
}
}
}.build()
}
}
} | 2 | Kotlin | 0 | 6 | a43c676dbf4cdf3fd2cd4148f555a66da964ac11 | 5,316 | Nicknamer | The Unlicense |
domain/src/main/kotlin/cz/eman/kaalsample/domain/feature/usermanagement/source/UserDataSource.kt | eManPrague | 189,150,450 | false | null | package cz.eman.kaalsample.domain.feature.usermanagement.source
import cz.eman.kaal.domain.result.Result
import cz.eman.kaalsample.domain.feature.usermanagement.model.User
/**
* @author vsouhrada (<EMAIL>)
*/
interface UserDataSource {
suspend fun authorizeUser(user: User): Result<User>
suspend fun registerUser(user: User): Result<User>
} | 1 | null | 2 | 6 | f9c0f2c8f617a4810e5c050d6fb1b9f3e508988c | 355 | kaal-sample | MIT License |
project/core/src/main/kotlin/io/github/heyhey123/geoipfilter/hookDatabase.kt | heyhey123-git | 845,990,407 | false | {"Kotlin": 25049} | @file:Suppress("SwallowedException", "TooGenericExceptionCaught", "MagicNumber")
package io.github.heyhey123.geoipfilter
import com.maxmind.geoip2.DatabaseReader
import com.maxmind.geoip2.WebServiceClient
import io.github.heyhey123.geoipfilter.IPQuery.databaseReader
import io.github.heyhey123.geoipfilter.IPQuery.loadedDatabaseType
import io.github.heyhey123.geoipfilter.IPQuery.webServiceClient
import io.github.heyhey123.geoipfilter.PluginConfig.getAccountID
import io.github.heyhey123.geoipfilter.PluginConfig.getApiUrl
import io.github.heyhey123.geoipfilter.PluginConfig.getDatabaseFile
import io.github.heyhey123.geoipfilter.PluginConfig.getLicenseKey
import io.github.heyhey123.geoipfilter.PluginConfig.getUpdateAuto
import io.github.heyhey123.geoipfilter.utils.okhttp.DatabaseUpdate
import io.github.heyhey123.geoipfilter.utils.okhttp.httpQuery
import io.github.heyhey123.geoipfilter.utils.okhttp.types.HttpType
import taboolib.common.LifeCycle
import taboolib.common.io.newFile
import taboolib.common.platform.Awake
import taboolib.common.platform.function.getDataFolder
import taboolib.common.platform.function.warning
import java.io.File
@Awake(LifeCycle.CONST)
fun hookDatabase() {
val databaseType = PluginConfig.getDatabaseType()
when (databaseType) {
"MMDB" -> {
if (!getUpdateAuto()) {
loadLocalDatabase(
newFile(getDataFolder().resolve(getDatabaseFile()!!), false)
)
return
}
try {
httpQuery(
PluginConfig.getUpdateUrl() ?: return,
"",
HttpType.GET
) {
queryJson {
then {
DatabaseUpdate.update(isPeriod = true)
loadedDatabaseType = "MMDB"
}
catch {
error("GET failed")
}
}
}
} catch (e: Exception) {
warning("试图请求数据库更新地址失败,已自动停用检查")
loadedDatabaseType = "NONE"
loadLocalDatabase(
newFile(getDataFolder().resolve(getDatabaseFile()!!), false)
)
throw e
}
}
"API" -> {
try {
webServiceClient = WebServiceClient
.Builder(getAccountID(), getLicenseKey())
.host(getApiUrl())
.build()
loadedDatabaseType = "API"
} catch (e: Exception) {
warning("链接到 API 时出错")
loadedDatabaseType = "NONE"
throw e
}
}
}
}
fun loadLocalDatabase(database: File) {
try {
databaseReader = DatabaseReader.Builder(database).build()
} catch (e: Exception) {
warning("加载本地数据库时失败,自动禁用数据库")
loadedDatabaseType = "NONE"
throw e
}
}
| 0 | Kotlin | 0 | 0 | f5cf42d750d76b9b93e47b9e87b100ab524382f1 | 3,038 | GeoIpFilter | Creative Commons Zero v1.0 Universal |
j2k/src/org/jetbrains/kotlin/j2k/ast/NewClassExpression.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.j2k.ast
import org.jetbrains.kotlin.j2k.CodeBuilder
class NewClassExpression(
val name: ReferenceElement?,
val argumentList: ArgumentList,
val qualifier: Expression = Expression.Empty,
val anonymousClass: AnonymousClassBody? = null
) : Expression() {
override fun generateCode(builder: CodeBuilder) {
if (anonymousClass != null) {
builder.append("object:")
}
if (!qualifier.isEmpty) {
builder.append(qualifier).append(if (qualifier.isNullable) "!!." else ".")
}
if (name != null) {
builder.append(name)
}
if (anonymousClass == null || !anonymousClass.extendsInterface) {
builder.append(argumentList)
}
if (anonymousClass != null) {
builder.append(anonymousClass)
}
}
}
| 0 | null | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,487 | kotlin | Apache License 2.0 |
lib/src/test/kotlin/dev/hossain/android/catalogparser/ParserTest.kt | priyankpat | 440,923,899 | true | {"Kotlin": 14100} | package dev.hossain.android.catalogparser
import com.google.gson.Gson
import dev.hossain.android.catalogparser.models.AndroidDevice
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Tests the Android device catalog CSV parser.
*/
class ParserTest {
private lateinit var sut: Parser
@BeforeTest
fun setup() {
sut = Parser()
}
@Test
fun `given no csv header fails to parse devices`() {
val csvData: String = """
10.or,D,10or_D,2868-2874MB,Phone,Qualcomm MSM8917,720x1280,320,arm64-v8a;armeabi;armeabi-v7a,25;27,3.0
10.or,E,E,1857-2846MB,Phone,Qualcomm MSM8937,1080x1920,480,arm64-v8a;armeabi;armeabi-v7a,25;27,3.2
""".trimIndent()
val parsedDevices = sut.parseDeviceCatalogData(csvData)
assertEquals(0, parsedDevices.size)
}
@Test
fun `given valid csv data parses device list`() {
val csvData: String = """
Manufacturer,Model Name,Model Code,RAM (TotalMem),Form Factor,System on Chip,Screen Sizes,Screen Densities,ABIs,Android SDK Versions,OpenGL ES Versions
10.or,D,10or_D,2868-2874MB,Phone,Qualcomm MSM8917,720x1280,320,arm64-v8a;armeabi;armeabi-v7a,25;27,3.0
10.or,E,E,1857-2846MB,Phone,Qualcomm MSM8937,1080x1920,480,arm64-v8a;armeabi;armeabi-v7a,25;27,3.2
""".trimIndent()
val parsedDevices = sut.parseDeviceCatalogData(csvData)
assertEquals(2, parsedDevices.size)
}
@Test
fun `given valid csv data with duplicate api levels - filters out duplicates`() {
val csvData: String = """
Manufacturer,Model Name,Model Code,RAM (TotalMem),Form Factor,System on Chip,Screen Sizes,Screen Densities,ABIs,Android SDK Versions,OpenGL ES Versions
ManName,Model,Model-Code,2868-2874MB,Phone,Qualcomm MSM8917,720x1280,320,arm64-v8a;armeabi;armeabi-v7a,25;27;25;24;25,3.0
""".trimIndent()
val parsedDevices = sut.parseDeviceCatalogData(csvData)
assertEquals(1, parsedDevices.size)
assertEquals(listOf(24,25,27), parsedDevices.first().sdkVersions)
}
@Test
fun `given valid csv data with duplicate abis - filters out duplicates`() {
val csvData: String = """
Manufacturer,Model Name,Model Code,RAM (TotalMem),Form Factor,System on Chip,Screen Sizes,Screen Densities,ABIs,Android SDK Versions,OpenGL ES Versions
ManName,Model,Model-Code,2868-2874MB,Phone,Qualcomm MSM8917,720x1280,320,armeabi;armeabi-v7a;armeabi;armeabi-v7a,25;27,3.0
""".trimIndent()
val parsedDevices = sut.parseDeviceCatalogData(csvData)
assertEquals(1, parsedDevices.size)
assertEquals(listOf("armeabi", "armeabi-v7a"), parsedDevices.first().abis)
}
@Test
fun `given valid csv data with duplicate opengl versions - filters out duplicates`() {
val csvData: String = """
Manufacturer,Model Name,Model Code,RAM (TotalMem),Form Factor,System on Chip,Screen Sizes,Screen Densities,ABIs,Android SDK Versions,OpenGL ES Versions
ManName,Model,Model-Code,2868-2874MB,Phone,Qualcomm MSM8917,720x1280,320,armeabi,25;27,3.0;3.1;3.0
""".trimIndent()
val parsedDevices = sut.parseDeviceCatalogData(csvData)
assertEquals(1, parsedDevices.size)
assertEquals(listOf("3.0", "3.1"), parsedDevices.first().openGlEsVersions)
}
@Test
fun `given valid csv data row parses device attributes`() {
val csvData: String = """
Manufacturer,Model Name,Model Code,RAM (TotalMem),Form Factor,System on Chip,Screen Sizes,Screen Densities,ABIs,Android SDK Versions,OpenGL ES Versions
Google,Pixel 4 XL,coral,5466MB,Phone,Qualcomm SDM855,1440x3040,560,arm64-v8a;armeabi;armeabi-v7a,29;30,3.2
""".trimIndent()
val parsedDevices = sut.parseDeviceCatalogData(csvData)
assertEquals(1, parsedDevices.size)
val device = parsedDevices.first()
assertEquals("Google", device.manufacturer)
assertEquals("Pixel 4 XL", device.modelName)
assertEquals("coral", device.modelCode)
assertEquals("5466MB", device.ram)
assertEquals("Phone", device.formFactor)
assertEquals("Qualcomm SDM855", device.processorName)
assertEquals(listOf("1440x3040"), device.screenSizes)
assertEquals(listOf(560), device.screenDensities)
assertEquals(listOf("arm64-v8a", "armeabi", "armeabi-v7a"), device.abis)
assertEquals(listOf(29, 30), device.sdkVersions)
assertEquals(listOf("3.2"), device.openGlEsVersions)
}
@Test
fun `given all catalog data is loaded then parsers all devices`() {
val csvFileContent = javaClass.getResourceAsStream("/android-devices-catalog.csv").bufferedReader().readText()
val parsedDevices: List<AndroidDevice> = sut.parseDeviceCatalogData(csvFileContent)
assertTrue(parsedDevices.size > 1000, "Total parsed devices should be more than thousand")
}
@Test
fun `given parsed devices available - can converts to JSON`() {
val csvFileContent = javaClass.getResourceAsStream("/android-devices-catalog.csv").bufferedReader().readText()
val parsedDevices: List<AndroidDevice> = sut.parseDeviceCatalogData(csvFileContent)
val gson = Gson()
val convertedJson = gson.toJson(parsedDevices)
assertTrue(convertedJson.length > 1_000_000)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Use following to write file to resources
/*val resourceDirectory: Path = Paths.get("src", "test", "resources")
val resDir = resourceDirectory.toFile()
assertTrue(resDir.absolutePath.endsWith("src/test/resources"))
val jsonFile: File = File(resDir, "android-devices-catalog-min.json")
jsonFile.writeText(convertedJson)*/
}
}
| 0 | null | 0 | 1 | 64867a574b016d28e4bec4cd388a65f438f3175b | 5,894 | android-device-catalog-parser | Apache License 2.0 |
plugin/android-junit5/src/test/kotlin/de/mannodermaus/gradle/plugins/junit5/util/TestExtensions.kt | mannodermaus | 69,637,233 | false | null | package de.mannodermaus.gradle.plugins.junit5.util
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestFramework
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.testing.Test
import org.gradle.api.tasks.testing.junitplatform.JUnitPlatformOptions
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.internal.PluginUnderTestMetadataReading
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.function.Executable
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* @author <NAME> - <EMAIL>
*/
inline fun <reified T : Throwable> throws(block: () -> Unit): T {
var ex: Throwable? = null
var thrown = false
var matches = false
try {
block()
} catch (e: Throwable) {
ex = e
matches = T::class.isInstance(e)
thrown = true
} finally {
if (!matches && ex != null) throw AssertionError(
"block should have thrown a ${T::class.simpleName}, but threw a ${ex.javaClass.simpleName}")
if (!thrown) throw AssertionError("block should have thrown a ${T::class.simpleName}")
}
return ex as T
}
fun assertAll(vararg assertions: () -> Unit) {
Assertions.assertAll(*assertions.map { Executable { it() } }.toTypedArray())
}
fun assertAll(heading: String, vararg assertions: () -> Unit) {
Assertions.assertAll(heading, *assertions.map { Executable { it() } }.toTypedArray())
}
/* Extensions */
fun Project.evaluate() {
(this as ProjectInternal).evaluate()
}
fun Project.applyPlugin(pluginId: String) = apply { it.plugin(pluginId) }
@Suppress("UNCHECKED_CAST")
fun <T : Task> TaskContainer.get(name: String): T =
this.getByName(name) as T
fun Task.getDependentTaskNames(): List<String> =
this.dependsOn.map { dependent ->
when (dependent) {
is Task -> dependent.name
is TaskProvider<*> -> dependent.name
else -> throw IllegalArgumentException("don't know how to extract task name from: $dependent")
}
}
fun File.newFile(filePath: String, separator: String = "/"): File {
val path = Paths.get(this.toString(),
*filePath.splitToArray(delimiter = separator))
path.parent.mkdirs()
return path.toFile()
}
fun String.splitToArray(delimiter: String = "/"): Array<String> =
this.split(delimiter).toTypedArray()
fun Path.mkdirs() = Files.createDirectories(this)
fun Path.newFile(path: String) = this.resolve(path).toFile()
val Test.junitPlatformOptions: JUnitPlatformOptions
get() = (this.testFramework as JUnitPlatformTestFramework).options
fun List<File>.splitClasspath() = this
.map { it.absolutePath.replace("\\", "\\\\") }
.joinToString(", ") { "'$it'" }
fun GradleRunner.withPrunedPluginClasspath(agpVersion: TestedAgp) = also {
val fileKey = agpVersion.fileKey
val cl = Thread.currentThread().contextClassLoader
val url = cl.getResource("pruned-plugin-metadata-$fileKey.properties")
withPluginClasspath(PluginUnderTestMetadataReading.readImplementationClasspath(url))
}
/* Operators */
/**
* Produces the [cartesian product](http://en.wikipedia.org/wiki/Cartesian_product#n-ary_product) as a sequence of ordered pairs of elements lazily obtained
* from two [[Iterable]] instances
*/
operator fun <T : Any, U : Any> Iterable<T>.times(other: Iterable<U>): Sequence<Pair<T, U>> {
val first = iterator()
var second = other.iterator()
var a: T? = null
fun nextPair(): Pair<T, U>? {
if (a == null && first.hasNext()) a = first.next()
if (second.hasNext()) return Pair(a!!, second.next())
if (first.hasNext()) {
a = first.next(); second = other.iterator()
return Pair(a!!, second.next())
}
return null
}
return generateSequence { nextPair() }
}
| 6 | null | 52 | 863 | 8089c75235112149b6911c55111dc109b4b8f66c | 4,095 | android-junit5 | Apache License 2.0 |
asyncapi-core/src/test/kotlin/com/asyncapi/v3/schema/ReadJsonSchemaTest.kt | asyncapi | 262,555,517 | false | {"Kotlin": 1663312, "Java": 768695} | package com.asyncapi.v3.schema
import com.asyncapi.v3.ClasspathUtils
import com.asyncapi.v3.schema.json.*
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.jupiter.api.*
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
import java.util.stream.Stream
class ReadJsonSchemaTest {
private val objectMapper: ObjectMapper = ObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
fun compareSchemas(schemaToCompareWith: String,
schemaClass: Class<*>,
schemaProvider: SchemaProvider
) {
val jsonSchemaString = ClasspathUtils.readAsString(schemaToCompareWith)
val jsonSchema = objectMapper.readValue(jsonSchemaString, schemaClass)
val schemaToCheck: Any? = when (schemaClass) {
JsonSchema::class.java -> schemaProvider.jsonSchema()
AsyncAPISchema::class.java -> schemaProvider.asyncAPISchema()
else -> null
}
Assertions.assertEquals(jsonSchema, schemaToCheck)
}
@Nested
inner class JsonSchemaImplementation {
@ArgumentsSource(JsonSchemas::class)
@ParameterizedTest(name = "Read: {0}")
fun readJsonSchema(schemaToCompareWith: String, schemaProvider: SchemaProvider) {
compareSchemas(schemaToCompareWith, JsonSchema::class.java, schemaProvider)
}
}
@Nested
inner class AsyncAPISchemaImplementation {
@ArgumentsSource(JsonSchemas::class)
@ParameterizedTest(name = "Read: {0}")
fun readJsonSchema(schemaToCompareWith: String, schemaProvider: SchemaProvider) {
compareSchemas(schemaToCompareWith, AsyncAPISchema::class.java, schemaProvider)
}
}
class JsonSchemas: ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> {
return Stream.of(
Arguments.of("/json/v3/schema/json/arrays.schema.json", ArraysSchemaTest()),
Arguments.of("/json/v3/schema/json/complex-object.schema.json", ComplexObjectTest()),
Arguments.of("/json/v3/schema/json/conditional-validation-if-else.schema.json", ConditionalValidationIfElse()),
Arguments.of("/json/v3/schema/json/draft-07-core-schema-meta-schema.json", Draft07CoreSchemaMetaSchemaTest()),
Arguments.of("/json/v3/schema/json/enumerated-values.schema.json", EnumeratedValuesTest()),
Arguments.of("/json/v3/schema/json/person.schema.json", PersonTest()),
Arguments.of("/json/v3/schema/json/regex-pattern.schema.json", RegexPatternTest())
)
}
}
} | 11 | Kotlin | 22 | 64 | 94a3d1628b17ec58659693bc9ad3b98bca53f172 | 2,986 | jasyncapi | Apache License 2.0 |
completion/testData/basic/multifile/NotImportedNestedClassFromPrivateClass/NotImportedNestedClassFromPrivateClass.dependency.kt | JetBrains | 278,369,660 | false | null | package dependency
private class PrivateTopLevelClass {
class PublicNestedClass
protected class ProtectedNestedClass
private class PrivateNestedClass
inner class PublicInnerClass
protected inner class ProtectedInnerClass
private inner class PrivateInnerClass
} | 0 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 286 | intellij-kotlin | Apache License 2.0 |
app/src/main/java/com/a10miaomiao/bilimiao/adapter/VideoPagesAdapter.kt | 10miaomiao | 115,510,569 | false | null | package com.a10miaomiao.bilimiao.adapter
import com.a10miaomiao.bilimiao.R
import com.a10miaomiao.bilimiao.entity.VideoDetailsInfo
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
/**
* Created by 10喵喵 on 2017/11/3.
*/
class VideoPagesAdapter(list : List<VideoDetailsInfo.VideoPageInfo>) :
BaseQuickAdapter<VideoDetailsInfo.VideoPageInfo, BaseViewHolder>(R.layout.item_bangumi_episodes,list){
override fun convert(helper: BaseViewHolder?, item: VideoDetailsInfo.VideoPageInfo?) {
helper?.setText(R.id.tv_title, item?.title)
}
} | 1 | null | 1 | 20 | dfd78b56b5c41eb49454836ee2bce5cefc667db7 | 612 | bilimiao | Apache License 2.0 |
kge-core/src/main/kotlin/dev/staticsanches/kge/image/service/PixelService.kt | staticsanches | 796,330,735 | false | null | package dev.staticsanches.kge.image.service
import dev.staticsanches.kge.image.IntColorComponent
import dev.staticsanches.kge.image.Pixel
import dev.staticsanches.kge.spi.KGESPIExtensible
import kotlin.math.pow
/**
* Extensible service capable of handling [Pixel] manipulations.
*/
interface PixelService : KGESPIExtensible {
/**
* Returns the conversion of the [pixel] to RGB performing, if necessary, alpha blending
* with the [matteBackground]. The returned [Pixel.a] should be ignored.
*/
fun toRGB(
pixel: Pixel,
matteBackground: Pixel,
): Pixel
fun toGrayscale(pixel: Pixel): IntColorComponent
fun fromGrayscale(
grayscale: IntColorComponent,
alpha: IntColorComponent,
): Pixel
fun distance2(
rgb1: Pixel,
rgb2: Pixel,
): Float
companion object : PixelService by KGESPIExtensible.getOptionalWithHigherPriority() ?: DefaultPixelService
}
internal data object DefaultPixelService : PixelService {
override fun toRGB(
pixel: Pixel,
matteBackground: Pixel,
): Pixel =
when (pixel.a) {
255 -> pixel
0 -> matteBackground
else -> matteBackground.lerp(pixel, pixel.a / 255f) // uses linear interpolation
}
override fun toGrayscale(pixel: Pixel): IntColorComponent =
(pixel.r * 0.299f + pixel.g * 0.587f + pixel.b * 0.114f).toInt()
override fun fromGrayscale(
grayscale: IntColorComponent,
alpha: IntColorComponent,
): Pixel = Pixel.rgba(grayscale, grayscale, grayscale, alpha)
override fun distance2(
rgb1: Pixel,
rgb2: Pixel,
): Float {
if (rgb1.r == rgb2.r && rgb1.g == rgb2.g && rgb1.b == rgb2.b) {
return 0f
}
val (l1, a1, b1) = toLab(toXYZ(rgb1))
val (l2, a2, b2) = toLab(toXYZ(rgb2))
return (l1 - l2) * (l1 - l2) + (a1 - a2) * (a1 - a2) + (b1 - b2) * (b1 - b2)
}
// Code extracted from: http://www.easyrgb.com/en/math.php
private fun toXYZ(rgb: Pixel): Triple<Float, Float, Float> {
var r = rgb.r.toFloat() / 255f
var g = rgb.g.toFloat() / 255f
var b = rgb.b.toFloat() / 255f
r = if (r > 0.04045f) ((r + 0.055f) / 1.055f).pow(2.4f) else r / 12.92f
g = if (g > 0.04045f) ((g + 0.055f) / 1.055f).pow(2.4f) else g / 12.92f
b = if (b > 0.04045f) ((b + 0.055f) / 1.055f).pow(2.4f) else b / 12.92f
r *= 100
g *= 100
b *= 100
return Triple(
r * 0.4124f + g * 0.3576f + b * 0.1805f,
r * 0.2126f + g * 0.7152f + b * 0.0722f,
r * 0.0193f + g * 0.1192f + b * 0.9505f,
)
}
// Code extracted from: http://www.easyrgb.com/en/math.php
private fun toLab(xyz: Triple<Float, Float, Float>): Triple<Float, Float, Float> {
var (x, y, z) = xyz
// Using D65
x /= 94.811f
y /= 100
z /= 107.304f
x = if (x > 0.008856) x.pow(1f / 3f) else (7.787f * x) + (16f / 116f)
y = if (y > 0.008856) y.pow(1f / 3f) else (7.787f * y) + (16f / 116f)
z = if (z > 0.008856) z.pow(1f / 3f) else (7.787f * z) + (16f / 116f)
return Triple(
(116 * y) - 16,
500 * (x - y),
200 * (y - z),
)
}
override val servicePriority: Int
get() = Int.MIN_VALUE
}
| 0 | null | 0 | 2 | f7b768d8f927515f8f6bb39acfb3063b1498e9f3 | 3,399 | kge | MIT License |
app/projfair/src/main/java/me/progneo/projfair/data/service/ProjectsService.kt | imysko | 498,018,609 | false | {"Kotlin": 862247} | package me.progneo.projfair.data.service
import me.progneo.projfair.domain.model.Project
import me.progneo.projfair.domain.model.ProjectsResponse
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Path
import retrofit2.http.Query
internal interface ProjectsService {
@GET("api/projects/filter")
suspend fun getProjectList(
@Header("Cookie") token: String = "",
@Query("title") title: String = "",
@Query("page") page: Int = 0,
@Query("difficulty") difficulties: String = "",
@Query("state") states: String = "",
@Query("specialties") specialties: String = "",
@Query("skills") skills: String = "",
@Query("order") order: String = "asc",
@Query("sortBy") sortBy: String = "state"
): Response<ProjectsResponse>
@GET("api/projects/{id}")
suspend fun getProject(
@Path("id") id: Int = 0
): Response<Project>
@GET("api/activeProject")
suspend fun getActiveProject(
@Header("Cookie") token: String = "token="
): Response<Project>
@GET("api/arhiveProjects")
suspend fun getArchiveProjectList(
@Header("Cookie") token: String = "token="
): Response<List<Project>>
}
| 1 | Kotlin | 1 | 2 | ebc331edebae2f6f38569a29c9c0b16773f7ede3 | 1,259 | Schedule-ISTU | MIT License |
papa-safetrace/src/main/java/papa/internal/SafeTraceMainThreadMessages.kt | square | 407,688,593 | false | {"Kotlin": 175981} | package papa.internal
import android.os.Handler
import android.os.Looper
import com.squareup.papa.safetrace.R
import papa.MainThreadMessageSpy
import papa.SafeTrace
import papa.SafeTraceSetup
internal object SafeTraceMainThreadMessages {
private val traceMainThreadMessages: Boolean
get() {
if (!SafeTraceSetup.initDone) {
return false
}
val resources = SafeTraceSetup.application.resources
return resources.getBoolean(R.bool.papa_trace_main_thread)
}
@Volatile
private var enabled = false
fun enableMainThreadMessageTracing() {
val mainLooper = Looper.getMainLooper()
if (mainLooper === Looper.myLooper()) {
enableOnMainThread()
} else {
Handler(mainLooper).post {
enableOnMainThread()
}
}
}
private fun enableOnMainThread() {
if (!enabled && SafeTrace.isTraceable && traceMainThreadMessages) {
enabled = true
var currentlyTracing = false
MainThreadMessageSpy.startTracing { messageAsString, before ->
if (!currentlyTracing) {
if (SafeTrace.isCurrentlyTracing &&
before &&
// Don't add a trace section for Choreographer#doFrame, as that messes up
// Macrobenchmark: https://issuetracker.google.com/issues/340206285
"android.view.Choreographer\$FrameDisplayEventReceiver" !in messageAsString) {
val traceSection = SafeTraceSetup.mainThreadSectionNameMapper.mapSectionName(messageAsString)
SafeTrace.beginSection(traceSection)
currentlyTracing = true
}
} else {
currentlyTracing = false
SafeTrace.endSection()
}
}
}
}
} | 13 | Kotlin | 15 | 353 | 2ce2018099c2acda7f50a8bd37061865c3dfe5e8 | 1,700 | papa | Apache License 2.0 |
cinescout/utils/kotlin/src/commonMain/kotlin/cinescout/utils/kotlin/list.kt | 4face-studi0 | 280,630,732 | false | null | package cinescout.utils.kotlin
import arrow.core.Either
import arrow.core.NonEmptyList
import arrow.core.Option
fun <T> List<T>.nonEmpty(): Option<NonEmptyList<T>> =
NonEmptyList.fromList(this)
fun <T, A> List<T>.nonEmpty(ifEmpty: () -> A): Either<A, NonEmptyList<T>> =
NonEmptyList.fromList(this)
.toEither(ifEmpty)
| 24 | Kotlin | 1 | 3 | dabd9284655ead17314e871530a9664aa6965953 | 336 | CineScout | Apache License 2.0 |
appholder/src/main/java/com/android/identity/wallet/documentdata/DrivingLicense.kt | openwallet-foundation-labs | 248,844,077 | false | null | package com.android.identity.wallet.documentdata
import com.android.identity.documenttype.DocumentAttributeType
import com.android.identity.documenttype.StringOption
object DrivingLicense {
const val MDL_NAMESPACE = "org.iso.18013.5.1"
const val AAMVA_NAMESPACE = "org.iso.18013.5.1.aamva"
fun getMdocComplexTypes() = MdocComplexTypes.Builder("org.iso.18013.5.1.mDL")
.addDefinition(
MDL_NAMESPACE,
hashSetOf("driving_privileges"),
true,
"vehicle_category_code",
"Vehicle Category Code",
DocumentAttributeType.StringOptions(
listOf(
StringOption(null, "(not set)"),
StringOption("A", "Motorcycles (A)"),
StringOption("AEU", "Motorcycles (AEU)"),
StringOption("B", "Light vehicles (B"),
StringOption("C", "Goods vehicles (C)"),
StringOption("D", "Passenger vehicles (D)"),
StringOption("BE", "Light vehicles with trailers (BE)"),
StringOption("CE", "Goods vehicles with trailers (CE)"),
StringOption("DE", "Passenger vehicles with trailers (DE)"),
StringOption("AM", "Mopeds (AM)"),
StringOption("A1", "Light motorcycles (A1)"),
StringOption("A1EU", "Light motorcycles (A1EU)"),
StringOption("A2", "Medium motorcycles (A2)"),
StringOption("B1", "Light vehicles (B1)"),
StringOption("B1EU", "Light vehicles (B1EU)"),
StringOption("C1", "Medium sized goods vehicles (C1)"),
StringOption("D1", "Medium sized passenger vehicles (e.g. minibuses) (D1)"),
)
)
)
.addDefinition(
MDL_NAMESPACE,
hashSetOf("driving_privileges"),
true,
"issue_date",
"Date of Issue",
DocumentAttributeType.Date
)
.addDefinition(
MDL_NAMESPACE,
hashSetOf("driving_privileges"),
true,
"expiry_date",
"Date of Expiry",
DocumentAttributeType.Date
)
.addDefinition(
MDL_NAMESPACE,
hashSetOf("driving_privileges"),
true,
"codes",
"Codes of Driving Privileges",
DocumentAttributeType.ComplexType,
)
// details of DrivingPrivilege.codes
.addDefinition(
MDL_NAMESPACE,
hashSetOf("codes"),
true,
"code",
"Code",
DocumentAttributeType.StringOptions(
listOf(
StringOption(null, "(not set)"),
StringOption(
"01",
"Licence holder requires eye sight correction and/or protection"
),
StringOption(
"03",
"Licence holder requires prosthetic device for the limbs"
),
StringOption(
"78",
"Licence holder restricted to vehicles with automatic transmission"
),
StringOption(
"S01",
"The vehicle's maximum authorized mass (kg) shall be"
),
StringOption(
"S02",
"The vehicle's authorized passenger seats, excluding the driver's seat, shall be"
),
StringOption(
"S03",
"The vehicle's cylinder capacity (cm3) shall be"
),
StringOption(
"S04",
"The vehicle's power (kW) shall be"
),
StringOption(
"S05",
"Licence holder restricted to vehicles adapted for physically disabled"
)
)
)
)
.addDefinition(
MDL_NAMESPACE,
hashSetOf("codes"),
true,
"sign",
"Sign",
DocumentAttributeType.StringOptions(
listOf(
StringOption(null, "(not set)"),
StringOption("=", "Equals (=)"),
StringOption(">", "Greater than (>)"),
StringOption("<", "Less than (<)"),
StringOption(">=", "Greater than or equal to (≥)"),
StringOption("<=", "Less than or equal to (≤)")
)
)
)
.addDefinition(
MDL_NAMESPACE,
hashSetOf("codes"),
true,
"value",
"Value",
DocumentAttributeType.String
).
// details of domestic_driving_privileges
addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_driving_privileges"),
true,
"domestic_vehicle_class",
"Domestic Vehicle Class",
DocumentAttributeType.ComplexType,
)
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_driving_privileges"),
true,
"domestic_vehicle_restrictions",
"Domestic Vehicle Restrictions",
DocumentAttributeType.ComplexType
)
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_driving_privileges"),
true,
"domestic_vehicle_endorsements",
"Domestic Vehicle Endorsements",
DocumentAttributeType.ComplexType
)
// details of DomesticDrivingPrivilege.domestic_vehicle_class
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_vehicle_class"),
false,
"domestic_vehicle_class_code",
"Domestic Vehicle Class Code",
DocumentAttributeType.String
)
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_vehicle_class"),
false,
"domestic_vehicle_class_description",
"Domestic Vehicle Class Description",
DocumentAttributeType.String
)
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_vehicle_class"),
false,
"issue_date",
"Date of Issue",
DocumentAttributeType.Date
)
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_vehicle_class"),
false,
"expiry_date",
"Date of Expiry",
DocumentAttributeType.Date
)
// details of DomesticDrivingPrivilege.domestic_vehicle_restrictions
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_vehicle_restrictions"),
true,
"domestic_vehicle_restriction_code",
"Restriction Code",
DocumentAttributeType.String
)
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_vehicle_restrictions"),
true,
"domestic_vehicle_restriction_description",
"Vehicle Category Description",
DocumentAttributeType.String
)
// details of DomesticDrivingPrivilege.domestic_vehicle_endorsements
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_vehicle_endorsements"),
true,
"domestic_vehicle_endorsement_code",
"Endorsement Code",
DocumentAttributeType.String
)
.addDefinition(
AAMVA_NAMESPACE,
hashSetOf("domestic_vehicle_endorsements"),
true,
"domestic_vehicle_endorsement_description",
"Vehicle Endorsement Description",
DocumentAttributeType.String
)
.build()
} | 99 | null | 83 | 163 | e6bf25766985521b9a39d4ed7999f22d57064db5 | 8,209 | identity-credential | Apache License 2.0 |
app/src/main/java/com/example/root/graduation_app/ui/activity/MusicPlayActivity.kt | jiwenjie | 161,740,682 | false | null | package com.example.root.graduation_app.ui.activity
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.support.v4.content.ContextCompat
import android.view.animation.LinearInterpolator
import android.widget.SeekBar
import android.widget.Toast
import com.example.base_library.base_utils.LogUtils
import com.example.base_library.base_views.BaseActivity
import com.example.root.graduation_app.MusicPlayService
import com.example.root.graduation_app.R
import com.example.root.graduation_app.bean.Song
import com.example.root.graduation_app.utils.MusicUtils
import com.jaeger.library.StatusBarUtil
import kotlinx.android.synthetic.main.activity_music_player.*
import java.io.Serializable
/**
* author:Jiwenjie
* email:<EMAIL>
* time:2019/02/23
* desc:
* version:1.0
*/
class MusicPlayActivity : BaseActivity() {
private var song: Song? = null
private var beanList: ArrayList<Song>? = null
private var runing: Boolean = false // 是否当前音乐是否在运行
private var rotation: ObjectAnimator? = null
private var currentProgress = -1 // 当前播放进度
private var currentIndex = -1 // 歌曲当前在列表中的位置
/**
* 获取 Service,使用 bind 方式绑定;
*/
private var binder: MusicPlayService.MusicServiceBinder? = null
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
binder = service as MusicPlayService.MusicServiceBinder
}
override fun onServiceDisconnected(name: ComponentName?) {
}
}
private val handler = @SuppressLint("HandlerLeak")
object : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
1 -> {
try {
if (binder != null) {
activity_music_player_seekBar.max = binder!!.getProgress()
activity_music_player_seekBar.progress = binder!!.getPlayPosition()
activity_music_player_currentTimeText.text =
MusicUtils.formatTime(binder!!.getPlayPosition())
activity_music_player_totalTimeText.text =
MusicUtils.formatTime(binder!!.getProgress()) // 获取歌曲的长度
} else {
Toast.makeText(baseContext, "null", Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
e.printStackTrace()
}
this.sendEmptyMessageDelayed(1, 500)
}
}
}
}
companion object {
private const val KEY_index = "key_index"
private const val KEY_LIST = "key_list"
@JvmStatic
fun runActivity(activity: Activity, currentIndex: Int, beanList: ArrayList<Song>) {
val intent = Intent(activity, MusicPlayActivity::class.java).apply {
putExtra(KEY_index, currentIndex)
putExtra(KEY_LIST, beanList as Serializable)
}
activity.startActivity(intent)
}
}
@SuppressLint("CheckResult")
override fun initActivity(savedInstanceState: Bundle?) {
StatusBarUtil.setColor(
this@MusicPlayActivity,
ContextCompat.getColor(this@MusicPlayActivity, R.color.alpha_70_black)
)
currentIndex = intent.getIntExtra(KEY_index, -1)
beanList = intent.getSerializableExtra(KEY_LIST) as ArrayList<Song>
if (currentIndex == -1 || beanList == null || beanList?.size == 0) return
song = beanList!![currentIndex]
createBindService() // 创建绑定 Service
// activity_music_player_albumIng.setImageBitmap(MusicUtils.setArtwork(this@MusicPlayActivity, song?.path!!))
startAlbumAnimation(0f)
if (!runing) {
runing = true
}
initView()
initEvent()
Thread(Runnable {
val message = handler.obtainMessage()
message.what = 1
handler.sendMessage(message)
}).start()
}
private fun initView() {
activity_music_player_toolbarName.title = song?.name
if (runing) { // 如果表示正在运行
activity_music_player_playImg.setImageDrawable(
ContextCompat.getDrawable(
this@MusicPlayActivity,
R.drawable.pause
)
)
} else {
activity_music_player_playImg.setImageDrawable(
ContextCompat.getDrawable(
this@MusicPlayActivity,
R.drawable.music_start
)
)
}
if (binder != null) {
LogUtils.e("需要设置的最大值" + binder?.getProgress())
activity_music_player_seekBar.max = binder!!.getProgress()
activity_music_player_totalTimeText.text = binder?.getProgress().toString() // 获取歌曲的长度
}
activity_music_player_seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
// binder?.seekToPositon(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
binder?.seekToPositon(seekBar?.progress!!) // 手指拖动
}
})
}
private fun initEvent() {
activity_music_player_playImg.setOnClickListener {
if (runing) {
binder?.pause()
currentProgress = binder?.getPlayPosition()!!
if (rotation?.isRunning!!) {
rotation?.pause()
}
activity_music_player_playImg.setImageDrawable(
ContextCompat.getDrawable(
this@MusicPlayActivity,
R.drawable.music_start
)
)
runing = false
} else {
binder?.playMusic(song!!)
if (currentProgress != -1) {
binder?.seekToPositon(currentProgress)
}
rotation?.start()
activity_music_player_playImg.setImageDrawable(
ContextCompat.getDrawable(
this@MusicPlayActivity,
R.drawable.pause
)
)
runing = true
}
// RxBus.mBus.post(MusicPlayEvent(song!!, runing))
}
activity_music_player_nextImg.setOnClickListener {
// 下一曲
if (currentIndex == -1) return@setOnClickListener
if (currentIndex == (beanList!!.size - 1)) { // 说明已经是最后一首歌曲
currentIndex = 0
} else {
currentIndex++
}
updateMusicAndUI()
}
activity_music_player_previousImg.setOnClickListener {
// 上一曲
if (currentIndex == -1) return@setOnClickListener
if (currentIndex == 0) { // 当前已经是第一首歌曲
currentIndex = beanList!!.size - 1
} else {
currentIndex--
}
updateMusicAndUI()
}
}
/**
* 点击上一曲下一曲之后重新播放歌曲并且更新 UI
*/
private fun updateMusicAndUI() {
song = beanList!![currentIndex]
binder?.playMusic(song!!)
Thread(Runnable {
val message = handler.obtainMessage()
message.what = 1
handler.sendMessage(message)
}).start()
activity_music_player_toolbarName.title = song?.name // 更新 title
activity_music_player_albumIng.setImageBitmap(
MusicUtils.setArtwork(
this@MusicPlayActivity,
song?.path!!
)
) // 获取专辑封面图片
// RxBus.mBus.post(MusicPlayEvent(song!!, runing))
}
/**
* 进入播放界面之后开启专辑旋转动画
*/
private fun startAlbumAnimation(start: Float) {
if (start != 0f) {
} else {
rotation = ObjectAnimator.ofFloat(
activity_music_player_contentRyt,
"rotation", 0f, 359f
) // 最好是 0f 到 359f,0f 和 360f 的位置是重复的
}
rotation?.repeatCount = ObjectAnimator.INFINITE
rotation?.interpolator = LinearInterpolator()
rotation?.duration = 9000
rotation?.start()
}
override fun loadData() {
}
private fun createBindService() {
val intent = Intent(this, MusicPlayService::class.java)
// intent.putExtra(MusicPlayService.KEY_MUSIC, beanList)
bindService(intent, connection, Context.BIND_AUTO_CREATE) // 创建并绑定了 Service
}
override fun onDestroy() {
unbindService(connection)
super.onDestroy()
}
override fun getLayoutId(): Int = R.layout.activity_music_player
} | 0 | Kotlin | 3 | 9 | a3730f1758f8fe8d13cdd1d53045fa229f7e166d | 9,343 | Graduation_App | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/mpp/external/KotlinSourceSetExtensions.kt | vmichalak | 364,875,385 | true | {"Kotlin": 69686329, "Java": 7040677, "Swift": 4240529, "C": 2633594, "C++": 2415282, "Objective-C": 580704, "JavaScript": 209639, "Objective-C++": 165277, "Groovy": 103211, "Python": 43460, "Shell": 31275, "TypeScript": 22854, "Lex": 18369, "Batchfile": 11692, "CSS": 11259, "EJS": 5241, "Ruby": 4878, "HTML": 4793, "CMake": 4448, "Dockerfile": 2787, "Pascal": 1698, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2022 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.gradle.plugin.mpp.external
import org.jetbrains.kotlin.gradle.ExternalKotlinTargetApi
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.plugin.sources.internal
import org.jetbrains.kotlin.tooling.core.MutableExtras
@ExternalKotlinTargetApi
val KotlinSourceSet.extras: MutableExtras get() = this.internal.extras
| 7 | Kotlin | 1 | 1 | 6614714c9465ed122ad8f36b6e8149dbcfcd41bb | 595 | kotlin | Apache License 2.0 |
tulip/libtulip-ui-api/src/commonMain/kotlin/com/tajmoti/libtulip/ui/player/VideoPlayerUtils.kt | Tajmoti | 391,138,914 | false | null | package com.tajmoti.libtulip.ui.player
import com.tajmoti.libtulip.dto.EpisodeInfoDto
import com.tajmoti.libtulip.dto.SeasonEpisodeDto
import com.tajmoti.libtulip.dto.StreamableInfoDto
import com.tajmoti.libtulip.dto.TulipMovieDto
import kotlin.jvm.JvmStatic
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
object VideoPlayerUtils {
@JvmStatic
fun streamableToDisplayName(info: StreamableInfoDto?): String {
return when (info) {
is EpisodeInfoDto -> showToDisplayName(info)
is TulipMovieDto -> info.name
null -> ""
}
}
@JvmStatic
fun episodeToLabel(episodeInfo: SeasonEpisodeDto): String {
val name = episodeInfo.name ?: ""
return "${episodeInfo.episodeNumber}. $name"
}
@JvmStatic
fun showToDisplayName(item: EpisodeInfoDto): String {
val showSeasonEpNum = "${item.tvShowName} S${item.seasonNumber}:E${item.episodeNumber}"
val episodeName = item.name?.let { " '$it'" } ?: ""
return showSeasonEpNum + episodeName
}
@JvmStatic
private fun timePad(time: Long): String {
return time.toString().padStart(2, '0')
}
@JvmStatic
fun formatTimeForDisplay(timeMs: Long): String {
var mutableTimeMs = timeMs
val hours = mutableTimeMs.milliseconds.inWholeHours
mutableTimeMs -= hours.hours.inWholeMilliseconds
val minutes = mutableTimeMs.milliseconds.inWholeMinutes
mutableTimeMs -= minutes.minutes.inWholeMilliseconds
val seconds = mutableTimeMs.milliseconds.inWholeSeconds
return when {
hours > 0 -> hours.toString() + ':' + timePad(minutes) + ':' + timePad(seconds)
minutes > 0 -> timePad(minutes) + ':' + timePad(seconds)
else -> "0:" + timePad(seconds)
}
}
} | 6 | Kotlin | 0 | 0 | 5f1a6a4a5432981535313710f0037726c80118b8 | 1,910 | Tulip | MIT License |
ok-workoutapp-common/src/commonMain/kotlin/models/WktState.kt | ermolaevalexey | 583,599,964 | false | null | package ru.otus.otuskotlin.workoutapp.common.models
enum class WktState {
NONE,
RUNNING,
FAILING,
FINISHING
} | 0 | Kotlin | 1 | 0 | 3edcc4fb4067109216c76d50d7f6d2329a49f069 | 118 | 202212-ok-workoutapp | Apache License 2.0 |
src/main/kotlin/com/zhipuchina/wxpay/repository/Repository.kt | markrenChina | 327,533,120 | false | null | package com.zhipuchina.wxpay.repository
import com.zhipuchina.wxpay.repository.network.ApiConfig
import com.zhipuchina.wxpay.repository.network.ServiceCreator
import com.zhipuchina.wxpay.repository.network.model.wxrequest.UnifiedOrder
import com.zhipuchina.wxpay.repository.network.model.wxresponse.UnifiedOrderWxResponse
import org.springframework.stereotype.Repository
/**
* api调用实现
* Repository应该负责返回数据,
* 内部处理是否是网络还是数据库
* @author markrenChina
*/
@Repository
class Repository: IRepository {
private val netService = ServiceCreator.create<ApiConfig>()
override suspend fun unifiedOrder(unifiedOrder: UnifiedOrder): UnifiedOrderWxResponse
= netService.unifiedOrder(unifiedOrder)
} | 0 | Kotlin | 0 | 0 | eec75ba85112754607f12791b8df1919ef444b55 | 703 | wxpay | MIT License |
app/src/main/kotlin/com/thoughtbot/tropos/extensions/ContextExtensions.kt | thoughtbot | 78,581,829 | false | null | package com.thoughtbot.tropos.extensions
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
fun Context.hasPermission(permission: String): Boolean {
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
}
inline fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Unit) {
val editor = edit()
editor.func()
editor.apply()
}
| 5 | null | 21 | 132 | f78bf3c84ea91c08d200da6ad851920fcc259f82 | 493 | tropos-android | MIT License |
domain/src/main/java/com/cmc/curtaincall/domain/repository/ReviewRepository.kt | CurtainCall-App | 659,971,351 | false | {"Kotlin": 1298142} | package com.cmc.curtaincall.domain.repository
import androidx.paging.PagingData
import com.cmc.curtaincall.domain.enums.ReviewSortType
import com.cmc.curtaincall.domain.model.review.CreateReviewModel
import com.cmc.curtaincall.domain.model.review.LikeReviewModel
import com.cmc.curtaincall.domain.model.review.ShowReviewModel
import com.cmc.curtaincall.domain.model.show.CheckCreateReviewModel
import kotlinx.coroutines.flow.Flow
interface ReviewRepository {
fun createShowReview(
showId: String,
grade: Int,
content: String
): Flow<CreateReviewModel>
fun fetchShowReviewList(
showId: String,
sortType: ReviewSortType
): Flow<PagingData<ShowReviewModel>>
fun requestShowReviewList(
showId: String,
page: Int,
size: Int,
sortType: ReviewSortType
): Flow<List<ShowReviewModel>>
fun deleteShowReview(
reviewId: Int
): Flow<Boolean>
fun updateShowReview(
reviewId: Int,
content: String,
grade: Int
): Flow<Boolean>
fun checkCreatedReview(
showId: String
): Flow<CheckCreateReviewModel>
fun requestLikeReview(
reviewId: Int
): Flow<Boolean>
fun requestDislikeReview(
reviewId: Int
): Flow<Boolean>
fun checkLikeReviews(
reviewIds: List<Int>
): Flow<List<LikeReviewModel>>
}
| 4 | Kotlin | 1 | 5 | c9f51916e3acbb292f364b3a3191991506d76580 | 1,388 | CurtainCall-AOS | Apache License 2.0 |
subprojects/emcee/queue-client-api/src/main/kotlin/com/avito/emcee/queue/ScheduleTestsBody.kt | avito-tech | 230,265,582 | false | null | package com.avito.emcee.queue
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
public data class ScheduleTestsBody(
val prioritizedJob: Job,
val scheduleStrategy: ScheduleStrategy,
@Json(name = "testEntryConfigurations")
val tests: List<TestRequest>
)
| 6 | Kotlin | 36 | 327 | b8d12a06a169ae60d89d24f66978a7dc23833282 | 323 | avito-android | MIT License |
plugin/src/main/kotlin/org/jetbrains/spek/idea/SpekRunConfigurationType.kt | gajwani | 94,574,458 | true | {"Kotlin": 54318} | package org.jetbrains.spek.idea
import com.intellij.execution.configurations.ConfigurationTypeBase
import com.intellij.icons.AllIcons
/**
* @author <NAME>
*/
class SpekRunConfigurationType: ConfigurationTypeBase(
"spek-run-configuration",
"Spek",
"Run Spek tests",
AllIcons.RunConfigurations.Junit
) {
init {
addFactory(SpekConfigurationFactory(this))
}
}
| 0 | Kotlin | 0 | 0 | 1945181edeee8bf9b0871286ef1e42b105b8242e | 392 | spek-idea-plugin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.