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
android-app/koloretako/app/src/main/java/com/apps/kpa/kotlinphpauth/Model/AddressResponse.kt
patrice-pi
162,725,653
false
{"CSS": 177814, "PHP": 93795, "HTML": 81617, "Kotlin": 42936, "Python": 38862, "JavaScript": 1780, "Vue": 565}
package com.apps.kpa.koloretako.Model class AddressResponse { var id:Int?=null var ip_address:String?=null var machine:String?=null }
0
CSS
0
0
060d95d9aea5eaec8e9c471db7b82b1464cfb42c
146
api-koloretako
MIT License
src/main/kotlin/com/ivieleague/dejanko/orm/Query.kt
UnknownJoe796
340,833,944
false
null
package com.ivieleague.dejanko.orm import com.github.jasync.sql.db.ResultSet import com.github.jasync.sql.db.RowData import com.github.jasync.sql.db.SuspendingConnection import com.ivieleague.dejanko.forEachBetween import kotlin.reflect.KClass import kotlin.reflect.KProperty1 data class Query<T>( val select: List<DBColumn<*>>, val from: DBTable, val joins: List<Join> = listOf(), val where: DBExpression<Boolean>? = null, val orderBy: List<Sort> = listOf(), val limit: Int? = null, val offset: Int? = null, val distinct: Boolean = false, val groupBy: DBExpression<*>? = null, val parse: RowDataParser<T> ) { fun write(to: QueryWriter){ to.append("SELECT ") if(distinct){ to.append("DISTINCT ") } select.forEachBetween( action = { it.writeSelect(to) }, between = { to.append(", ") } ) to.append(" FROM ") to.emitTable(from) to.append(' ') joins.forEach { it.write(to) } if(where != null){ to.append("WHERE ") where.write(to) to.append(' ') } if(groupBy != null){ to.append("GROUP BY ") groupBy.write(to) } if(orderBy.isNotEmpty()){ to.append("ORDER BY ") orderBy.forEachBetween( action = { it.write(to) }, between = { to.append(", ") } ) to.append(' ') } if(limit != null){ to.append("LIMIT $limit ") } if(offset != null){ to.append("OFFSET $offset ") } } override fun toString(): String { val writer = QueryWriter() this.write(writer) return writer.builder.toString() } suspend fun execute(db: SuspendingConnection = Settings.defaultDb): TypedResultSet<T> { val writer = QueryWriter() this.write(writer) val data = db.sendPreparedStatement(writer.toString(), writer.variables).rows return TypedResultSet(data, parse(data)) } } data class Sort( val expression: DBExpression<*>, val ascending: Boolean = true, val nullsFirst: Boolean = false ) { fun write(to: QueryWriter){ expression.write(to) if(ascending) to.append(" ASC ") else to.append(" DESC ") if(nullsFirst) to.append("NULLS FIRST") else to.append("NULLS LAST") } } enum class JoinKind(val sql: String) { LEFT("LEFT OUTER"), RIGHT("OUTER RIGHT"), INNER("INNER"), OUTER("OUTER") } data class Join( val table: DBAliasTable, val on: DBExpression<Boolean>, val kind: JoinKind = JoinKind.INNER ) { fun write(to: QueryWriter){ to.append(kind.sql) to.append(" JOIN ") to.emitTable(table) to.append(" ON ") on.write(to) to.append(' ') } }
0
Kotlin
0
0
831febf88f9def35107cf8379fd88c16e677a72d
2,946
dejanko
MIT License
src/main/kotlin/StatusbarView.kt
dutta-anirban
658,581,216
false
null
import javafx.beans.binding.Bindings import javafx.geometry.Insets import javafx.geometry.Orientation import javafx.scene.control.Label import javafx.scene.control.Separator import javafx.scene.layout.HBox class StatusbarView(val viewController: ViewController, val model: Model) : HBox() { init { padding = Insets(5.0) children.addAll( Label().apply { textProperty().bind( Bindings.createStringBinding({ model.imageCountProperty.value.toString() }, model.imageCountProperty) ) }, Label(" images loaded"), Separator(Orientation.VERTICAL).apply { padding = Insets(0.0, 3.0, 0.0, 7.0) }, Label().apply { textProperty().bind( Bindings.createStringBinding({ when (model.selectedImageProperty.value?.image?.url) { null -> "Select an image" else -> model.selectedImageProperty.value?.image?.url } }, model.selectedImageProperty) ) }, ) } }
0
Kotlin
0
0
01acfd35536a275ce9a1b4f53d28f6e418e55c4e
1,210
lightbox
Apache License 2.0
features/product/data/src/test/kotlin/dev/chulwoo/nb/order/features/category/data/repository/ProductsRepositoryImplTest.kt
chulwoo-park
323,356,084
false
null
package dev.chulwoo.nb.order.features.category.data.repository import com.nhaarman.mockitokotlin2.* import dev.chulwoo.nb.order.features.category.data.source.ProductLocalSource import dev.chulwoo.nb.order.features.category.data.source.ProductRemoteSource import dev.chulwoo.nb.order.features.product.domain.model.Product import kotlinx.coroutines.runBlocking import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertThrows import org.junit.Test class ProductsRepositoryImplTest { private val p1 = Product(1, 1, 0.0, "1", "") private val p2 = Product(2, 1, 0.0, "2", "") private val p3 = Product(3, 2, 0.0, "3", "") @Test fun `Given local data When invoke get Then use local data only`() { runBlocking { val localSource = mock<ProductLocalSource> { onBlocking { getProducts(1) } doAnswer { listOf(p1, p2, p3) } } val remoteSource = mock<ProductRemoteSource>() val repository = ProductRepositoryImpl(localSource, remoteSource) repository.get(1) inOrder(localSource, remoteSource) { verify(localSource).getProducts(1) verify(remoteSource, never()).getProducts() } } } @Test fun `Given local error When invoke get Then use remote data`() { runBlocking { val localSource = mock<ProductLocalSource> { onBlocking { getProducts(1) } doAnswer { throw Exception() } onBlocking { setProducts(any(), any()) } doAnswer {} } val remoteSource = mock<ProductRemoteSource> { onBlocking { getProducts() } doAnswer { listOf(p1, p2, p3) } } val repository = ProductRepositoryImpl(localSource, remoteSource) val result = repository.get(1) inOrder(localSource, remoteSource) { verify(localSource).getProducts(1) verify(remoteSource).getProducts() } assertThat(result, equalTo(listOf(p1, p2))) } } @Test fun `Given local error When invoke get Then save data from remote to local`() { runBlocking { val localSource = mock<ProductLocalSource> { onBlocking { getProducts(1) } doAnswer { throw Exception() } } val remoteSource = mock<ProductRemoteSource> { onBlocking { getProducts() } doAnswer { listOf(p1, p2, p3) } } val repository = ProductRepositoryImpl(localSource, remoteSource) repository.get(1) inOrder(localSource, remoteSource) { verify(localSource).getProducts(1) verify(remoteSource).getProducts() verify(localSource).setProducts(1, listOf(p1, p2)) } verify(localSource).setProducts(2, listOf(p3)) } } @Test fun `Given empty data in category id When invoke get Then save empty list that category id`() { runBlocking { val localSource = mock<ProductLocalSource> { onBlocking { getProducts(any()) } doAnswer { throw Exception() } onBlocking { setProducts(any(), any()) } doAnswer { } } val remoteSource = mock<ProductRemoteSource> { onBlocking { getProducts() } doAnswer { listOf(p1, p2, p3) } } val repository = ProductRepositoryImpl(localSource, remoteSource) repository.get(3) verify(localSource).setProducts(3, listOf()) } } @Test fun `Given save error When invoke get Then use remote data without error`() { runBlocking { val localSource = mock<ProductLocalSource> { onBlocking { getProducts(1) } doAnswer { throw Exception() } onBlocking { setProducts(any(), any()) } doAnswer { throw Exception() } } val remoteSource = mock<ProductRemoteSource> { onBlocking { getProducts() } doAnswer { listOf(p1, p2, p3) } } val repository = ProductRepositoryImpl(localSource, remoteSource) val result = repository.get(1) inOrder(localSource, remoteSource) { verify(localSource).getProducts(1) verify(remoteSource).getProducts() } assertThat(result, equalTo(listOf(p1, p2))) } } @Test fun `Given local error and remote error When invoke get Then throw error`() { runBlocking { val localSource = mock<ProductLocalSource> { onBlocking { getProducts(1) } doAnswer { throw Exception() } } val remoteSource = mock<ProductRemoteSource> { onBlocking { getProducts() } doAnswer { throw Exception() } } val repository = ProductRepositoryImpl(localSource, remoteSource) assertThrows(Exception::class.java) { runBlocking { repository.get(1) } } inOrder(localSource, remoteSource) { verify(localSource).getProducts(1) verify(remoteSource).getProducts() } } } }
0
Kotlin
0
0
c5b0e437ffe1328a2cbfc882c2da42eb24f4dff5
5,268
nb-order
Apache License 2.0
core/src/main/java/com/alvayonara/mealsfood/core/domain/repository/IFoodRepository.kt
alvayonara
307,544,464
false
null
package com.alvayonara.mealsfood.core.domain.repository import com.alvayonara.mealsfood.core.data.source.Resource import com.alvayonara.mealsfood.core.data.source.remote.network.ApiResponse import com.alvayonara.mealsfood.core.domain.model.Food import com.alvayonara.mealsfood.core.domain.model.FoodRecentSearch import io.reactivex.Flowable interface IFoodRepository { fun getPopularFood(): Flowable<Resource<List<Food>>> fun getListFoodByCategory(strCategory: String): Flowable<Resource<List<Food>>> fun getListFoodByArea(strArea: String): Flowable<Resource<List<Food>>> fun getFoodDetailById(idMeal: String): Flowable<Resource<List<Food>>> fun searchFood(meal: String): Flowable<ApiResponse<List<Food>>> fun getFavoriteFood(): Flowable<List<Food>> fun checkIsFavoriteFood(idMeal: String): Flowable<Int> fun insertFavoriteFood(food: Food) fun deleteFavoriteFood(food: Food) fun getRecentSearchFood(): Flowable<List<FoodRecentSearch>> fun insertRecentSearchFood(search: FoodRecentSearch) }
0
Kotlin
2
4
52a46f41c396db5b35c8bd7888f930ace320836b
1,046
MealsFood
Apache License 2.0
src/main/kotlin/com/expedia/graphql/schema/exceptions/NestingNonNullTypeException.kt
brennantaylor
150,492,799
true
{"Kotlin": 66904, "Shell": 1006}
package com.expedia.graphql.schema.exceptions import graphql.schema.GraphQLType import kotlin.reflect.KType class NestingNonNullTypeException(gType: GraphQLType, kType: KType) : RuntimeException("Already non null, don't need to nest, $gType, $kType")
0
Kotlin
0
0
54d5ba02e971c5d96d50716a2a0efcc361e2058f
257
graphql-kotlin
Apache License 2.0
android/app/src/main/java/com/sicariusnoctis/collaborativeintelligence/MainActivity.kt
YodaEmbedding
208,207,262
false
null
package com.sicariusnoctis.collaborativeintelligence import android.hardware.camera2.CameraCharacteristics import android.os.Bundle import android.renderscript.RenderScript import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.sicariusnoctis.collaborativeintelligence.processor.* import com.sicariusnoctis.collaborativeintelligence.ui.ModelUiController import com.sicariusnoctis.collaborativeintelligence.ui.OptionsUiController import com.sicariusnoctis.collaborativeintelligence.ui.PostencoderUiController import com.sicariusnoctis.collaborativeintelligence.ui.StatisticsUiController import io.fotoapparat.parameter.Resolution import io.fotoapparat.preview.Frame import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.disposables.CompositeDisposable import io.reactivex.internal.schedulers.IoScheduler import io.reactivex.processors.PublishProcessor import io.reactivex.rxkotlin.subscribeBy import io.reactivex.rxkotlin.zipWith import kotlinx.android.synthetic.main.activity_main.* import java.time.Duration import java.time.Instant import java.util.concurrent.CompletableFuture class MainActivity : AppCompatActivity() { private val TAG = MainActivity::class.qualifiedName private lateinit var camera: Camera private lateinit var clientProcessor: ClientProcessor private lateinit var networkManager: NetworkManager private lateinit var previewResolution: Resolution private lateinit var rs: RenderScript private lateinit var modelUiController: ModelUiController private lateinit var optionsUiController: OptionsUiController private lateinit var postencoderUiController: PostencoderUiController private lateinit var statisticsUiController: StatisticsUiController private var prevFrameTime: Instant? = null private val frameProcessor: PublishProcessor<Frame> = PublishProcessor.create() private val statistics = Statistics() private val subscriptions = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) rs = RenderScript.create(this) camera = Camera(this, cameraView) { frame -> this.frameProcessor.onNext(frame) } modelUiController = ModelUiController( modelSpinner, layerSeekBar, compressionSpinner ) optionsUiController = OptionsUiController( uploadRateLimitSeekBar ) postencoderUiController = PostencoderUiController( modelUiController.modelConfig, modelUiController.modelConfigEvents, postencoderSpinner, postencoderQualitySeekBar ) statisticsUiController = StatisticsUiController( statistics, predictionsText, fpsText, uploadText, uploadAvgText, preprocessText, clientInferenceText, encodingText, // networkReadText, serverInferenceText, // networkWriteText, totalText, totalAvgText, framesProcessedText, lineChart ) } override fun onStart() { super.onStart() clientProcessor = ClientProcessor(rs, statistics) networkManager = NetworkManager(statistics, statisticsUiController) val cameraReady = CompletableFuture<Unit>() camera.start() camera.getCurrentParameters().whenAvailable { this.previewResolution = it!!.previewResolution cameraReady.complete(Unit) } Completable .mergeArray( Completable.fromFuture(cameraReady), clientProcessor.initInference(), networkManager.connectNetworkAdapter() ) .subscribeOn(IoScheduler()) .andThen(initPreprocessor()) .andThen(networkManager.subscribeNetworkIo()) .andThen(networkManager.subscribePingGenerator()) .andThen( switchModel( modelUiController.modelConfig, postencoderUiController.postencoderConfig ) ) .andThen(subscribeFrameProcessor()) .subscribeBy({ it.printStackTrace() }) } override fun onStop() { super.onStop() camera.stop() clientProcessor.close() networkManager.close() networkManager.dispose() } override fun onDestroy() { subscriptions.dispose() super.onDestroy() } private fun initPreprocessor() = Completable.fromRunnable { val rotationCompensation = CameraPreviewPreprocessor.getRotationCompensation( this, CameraCharacteristics.LENS_FACING_BACK ) clientProcessor.initPreprocesor( previewResolution.width, previewResolution.height, rotationCompensation ) } // TODO this is kind of using references to things that stop existing after onStop private fun subscribeFrameProcessor() = Completable.fromRunnable { val frameRequests = frameProcessor .subscribeOn(IoScheduler()) .onBackpressureDrop() .observeOn(IoScheduler(), false, 1) .map { val info = FrameRequestInfo( -1, modelUiController.modelConfig, postencoderUiController.postencoderConfig ) FrameRequest(it, info) } .onBackpressureLimitRate( onDrop = { statistics[it.info.modelConfig].frameDropped() }, limit = { shouldProcessFrame(it.info.modelConfig, it.info.postencoderConfig) } ) .zipWith(Flowable.range(0, Int.MAX_VALUE)) { (frame, info), frameNumber -> prevFrameTime = Instant.now() statistics[info.modelConfig].makeSample(frameNumber) FrameRequest(frame, info.replace(frameNumber)) } val clientRequests = clientProcessor.mapFrameRequests(frameRequests) val clientRequestsSubscription = clientRequests .observeOn(networkManager.networkWriteScheduler, false, 1) .doOnNext { networkManager.uploadLimitRate = optionsUiController.uploadRateLimit } .doOnNextTimed(statistics, ModelStatistics::setNetworkWrite) { networkManager.writeFrameRequest(it) } .doOnNext { statistics[it.info.modelConfig].setUpload(it.info.frameNumber, it.obj.size) } .subscribeBy({ it.printStackTrace() }) subscriptions.add(clientRequestsSubscription) } // TODO deal with unnecessary ProcessorConfig constructions... // TODO clean up using .log() extension method private fun switchModel(modelConfig: ModelConfig, postencoderConfig: PostencoderConfig) = Completable .fromRunnable { Log.i(TAG, "Switching model begin") } .andThen( Completable.mergeArray( clientProcessor.switchModelInference( ProcessorConfig( modelConfig, postencoderConfig ) ), networkManager.switchModelServer( ProcessorConfig( modelConfig, postencoderConfig ) ) ) ) .doOnComplete { Log.i(TAG, "Switching model end") } // TODO extract gate... maybe split into two filters (second half handled by stats only) private fun shouldProcessFrame( modelConfig: ModelConfig, postencoderConfig: PostencoderConfig ): Boolean { val stats = statistics[modelConfig] // Load new model if config changed if (modelConfig != clientProcessor.modelConfig) { // Wait till latest sample has been processed client-side first if (clientProcessor.state == ClientProcessorState.BusyReconfigure) { Log.i(TAG, "Dropped frame because waiting to switch models") return false } // TODO remove blockingAwait by setting a mutex? switchModel(modelConfig, postencoderConfig).blockingAwait() statistics[modelConfig] = ModelStatistics() Log.i(TAG, "Dropped frame after switching model") return false } // Load new postencoder if config changed if (postencoderConfig != clientProcessor.postencoderConfig) { // Wait till latest sample has been processed client-side first if (clientProcessor.state == ClientProcessorState.BusyReconfigure) { Log.i(TAG, "Dropped frame because waiting to switch postencoders") return false } // switchPostencoder(postencoderConfig).blockingAwait() switchModel(modelConfig, postencoderConfig).blockingAwait() statistics[modelConfig] = ModelStatistics() Log.i(TAG, "Dropped frame after switching postencoder") return false } if (!stats.isFirstExist) return true // If first server response is not yet received, drop frame if (stats.isEmpty) { Log.i(TAG, "Dropped frame because waiting for first server response") return false } // TODO watch out for encoding time... if (stats.currentSample?.inferenceEnd == null) { Log.i(TAG, "Dropped frame because frame is currently being processed") return false } if (stats.currentSample?.networkWriteEnd == null) { Log.i(TAG, "Dropped frame because frame is currently being written over network") return false } if (stats.currentSample?.networkReadEnd == null) { // Log.i(TAG, "Dropped frame because frame is currently being processed by server") return false } val sample = stats.sample val enoughTime = Duration.ofMillis(0) if (networkManager.timeUntilWriteAvailable > enoughTime) { Log.i(TAG, "Dropped frame because of slow upload speed!") return false } val timeSinceLastFrameRequest = Duration.between(prevFrameTime, Instant.now()) if (timeSinceLastFrameRequest < sample.clientInference) { Log.i(TAG, "Dropped frame because of slow client inference time!") return false } if (timeSinceLastFrameRequest < sample.serverInference) { Log.i(TAG, "Dropped frame because of slow server inference time!") return false } return true } }
4
Kotlin
0
6
53d3ea010861e1fc539cf38f14fca50476dee196
11,008
collaborative-intelligence
MIT License
app/src/main/java/com/skyyo/template/application/models/local/InputWrapper.kt
Skyyo
325,519,535
false
null
package com.skyyo.template.application.models.local import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class InputWrapper( var value: String = "", var errorId: Int? = null ) : Parcelable
0
Kotlin
6
21
e56cd417b29334be2ed1487042b4d89d923bf027
226
android-template
MIT License
tracker/tracker_data/src/main/java/com/tochukwumunonye/tracker_data/local/TrackerDatabase.kt
tochukwumunonye
477,165,264
false
null
package com.plcoding.tracker_data.local import androidx.room.Database import androidx.room.RoomDatabase import com.plcoding.tracker_data.local.entity.TrackedFoodEntity @Database( entities = [TrackedFoodEntity::class], version = 1 ) abstract class TrackerDatabase: RoomDatabase() { abstract val dao: TrackerDao }
0
Kotlin
1
0
6e781eca7ef5a0e7a6fdae1a3e612026997628f1
326
CaloriesTracker
The Unlicense
korge/src/commonMain/kotlin/com/soywiz/korge/service/storage/Storage.kt
Wolwer1nE
268,762,840
true
{"Kotlin": 1972890, "Java": 182026, "Shell": 1955, "Batchfile": 1618}
package com.soywiz.korge.service.storage import com.soywiz.korinject.* //@Singleton open class Storage : IStorage by NativeStorage
0
null
0
0
bc4cfa3914518e8588f1146eec6ea9bf76ca1095
133
korge
Apache License 2.0
korge/src/commonMain/kotlin/com/soywiz/korge/view/fast/FastSpriteContainer.kt
korlibs
80,095,683
false
null
package com.soywiz.korge.view.fast import com.soywiz.kds.FastArrayList import com.soywiz.korge.render.BatchBuilder2D import com.soywiz.korge.render.RenderContext import com.soywiz.korge.view.Container import com.soywiz.korge.view.View import com.soywiz.korge.view.ViewDslMarker import com.soywiz.korge.view.addTo import kotlin.math.* inline fun Container.fastSpriteContainer( useRotation: Boolean = false, smoothing: Boolean = true, callback: @ViewDslMarker FastSpriteContainer.() -> Unit = {} ): FastSpriteContainer = FastSpriteContainer(useRotation, smoothing).addTo(this, callback) class FastSpriteContainer(val useRotation: Boolean = false, var smoothing: Boolean = true) : View() { private val sprites = FastArrayList<FastSprite>() val numChildren get() = sprites.size fun addChild(sprite: FastSprite) { if(sprite.useRotation != useRotation) { sprite.useRotation = useRotation // force update the sprite just in case the FastSprite properties were updated before being // added to the container sprite.forceUpdate() } sprite.container = this this.sprites.add(sprite) } // alias for addChild fun alloc(sprite: FastSprite) = addChild(sprite) fun removeChild(sprite: FastSprite) { this.sprites.remove(sprite) sprite.container = null } // alias for removeChild fun delete(sprite: FastSprite) = removeChild(sprite) // 65535 is max vertex index in the index buffer (see ParticleRenderer) // so max number of particles is 65536 / 4 = 16384 // and max number of element in the index buffer is 16384 * 6 = 98304 // Creating a full index buffer, overhead is 98304 * 2 = 196Ko // let numIndices = 98304; override fun renderInternal(ctx: RenderContext) { val colorMul = this.renderColorMul.value val colorAdd = this.renderColorAdd.value val sprites = this.sprites if (sprites.isEmpty()) return ctx.flush() val bb = ctx.batch val fsprite = sprites.first() val bmp = fsprite.tex.bmpBase bb.setViewMatrixTemp(globalMatrix) { //////////////////////////// bb.setStateFast(bmp, smoothing, blendMode.factors, null) //////////////////////////// val batchSize = min(sprites.size, bb.maxQuads) addQuadIndices(bb, batchSize) bb.vertexCount = 0 bb.uploadIndices() val realIndexPos = bb.indexPos //////////////////////////// //var batchCount = 0 //var spriteCount = 0 //for (m in 0 until sprites.size step bb.maxQuads) { // @TODO: Not optimized on Kotlin/JS for (m2 in 0 until (sprites.size divCeil bb.maxQuads)) { val m = m2 * bb.maxQuads //batchCount++ bb.indexPos = realIndexPos renderInternalBatch(bb, m, batchSize, colorMul, colorAdd) flush(bb) } //println("batchCount: $batchCount, spriteCount: $spriteCount") } } private fun addQuadIndices(bb: BatchBuilder2D, batchSize: Int) { bb.addQuadIndicesBatch(batchSize) } private fun renderInternalBatch(bb: BatchBuilder2D, m: Int, batchSize: Int, colorMul: Int, colorAdd: Int) { val sprites = this.sprites var vp = bb.vertexPos val vd = bb.verticesFast32 val mMax = min(sprites.size, m + batchSize) var count = mMax - m for (n in m until mMax) { //spriteCount++ val sprite = sprites[n] if (!sprite.visible) { count-- continue } if (useRotation) { vp = bb._addQuadVerticesFastNormal( vp, vd, sprite.x0, sprite.y0, sprite.x1, sprite.y1, sprite.x2, sprite.y2, sprite.x3, sprite.y3, sprite.tx0, sprite.ty0, sprite.tx1, sprite.ty1, sprite.color.value, colorAdd ) } else { vp = bb._addQuadVerticesFastNormalNonRotated( vp, vd, sprite.x0, sprite.y0, sprite.x1, sprite.y1, sprite.tx0, sprite.ty0, sprite.tx1, sprite.ty1, sprite.color.value, colorAdd ) } } bb.vertexPos = vp bb.vertexCount = count * 4 bb.indexPos = count * 6 } private fun flush(bb: BatchBuilder2D) { bb.flush(uploadVertices = true, uploadIndices = false) } } private infix fun Int.divCeil(other: Int): Int { val res = this / other if (this % other != 0) return res + 1 return res }
102
Kotlin
64
1,192
7fa8c9981d09c2ac3727799f3925363f1af82f45
4,801
korge
Apache License 2.0
file-attribute-caching/src/test/kotlin/com/pkware/filesystem/forwarding/StubFileSystem.kt
pkware
546,308,610
false
null
package com.pkware.filesystem.forwarding import java.nio.file.FileSystem /** * Does nothing except forward calls to the [delegate]. Will not compile if [ForwardingFileSystem] does not implement * all members. */ class StubFileSystem(delegate: FileSystem) : ForwardingFileSystem(delegate)
0
Kotlin
0
0
e415f06164eebe83d59be0c730f3217dad66dd96
293
AttributeCachingFileSystem
MIT License
app/src/main/java/com/melissa/simpletodo/MainActivity.kt
melissa-perez
434,761,605
false
null
package com.melissa.simpletodo import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.apache.commons.io.FileUtils import java.io.File import java.io.IOException import java.nio.charset.Charset // handles the user interactions class MainActivity : AppCompatActivity() { var listOfTasks = mutableListOf<String>() // Create adapter lateinit var adapter : TaskItemAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) /*val onClickListener = object :TaskItemAdapter.OnClickListener{ }*/ val onLongClickListener = object :TaskItemAdapter.OnLongClickListener{ override fun onItemLongClicked(position: Int) { // 1. Remove the item from the list listOfTasks.removeAt(position) // 2. Notify the adapter of the change adapter.notifyDataSetChanged() saveItems() } } loadItems() // View Ids val recyclerView = findViewById<RecyclerView>(R.id.recyclerView) val inputTextField = findViewById<EditText>(R.id.addTaskField) adapter = TaskItemAdapter(listOfTasks, onLongClickListener) // Attach the adapter to the recyclerview to populate items recyclerView.adapter = adapter // Set layout manager to position the items recyclerView.layoutManager = LinearLayoutManager(this) // Set up button and text field listener findViewById<Button>(R.id.addTaskButton).setOnClickListener{ // 1. Grab the user text val userInputTask = inputTextField.text.toString() // 2. Add that string to listOfTasks listOfTasks.add(userInputTask) // Notifies the adapter and updates the app to reflect changes adapter.notifyItemInserted(listOfTasks.size - 1) // 3. Reset text field to empty for next input inputTextField.setText("") saveItems() } } // Save the data and persist it using File I/0 // Create a method to get the file we need fun getDataFile(): File { // Every line is a specific task return File(filesDir, "data.txt") } // Load the items by reading every line the data file fun loadItems() { try { listOfTasks = FileUtils.readLines(getDataFile(), Charset.defaultCharset()) } catch (ioException: IOException) { ioException.printStackTrace() } } // Save the data to file fun saveItems() { try { FileUtils.writeLines(getDataFile(), listOfTasks) } catch(ioException: IOException) { ioException.printStackTrace() } } // Launch Edit Intent fun launchEditView() { //first parameter is the context, second is the class of the activity to launch val i = Intent(this@MainActivity, EditActivity::class.java) } }
1
Kotlin
0
0
baa83db7cfafc78604377ad02c4bca7fa7d1f698
3,266
codepath-android-kotlin-prework
Apache License 2.0
app/src/main/java/com/aesuriagasalazar/competenciadigitalespracticum3_2/data/service/RemoteStorageService.kt
AngelEduSuri
514,696,509
false
null
package com.aesuriagasalazar.competenciadigitalespracticum3_2.data.service import com.aesuriagasalazar.competenciadigitalespracticum3_2.domain.TestScore import kotlinx.coroutines.flow.Flow interface RemoteStorageService { suspend fun saveResultTest(uid: String, result: TestScore): Flow<Boolean> suspend fun getResultTest(): Flow<List<TestScore>> }
0
Kotlin
0
0
a97e0821b59d1bdc7d5274fc62bf61f23473c082
358
Competencias-Digitales-Practicum-3.2
Apache License 2.0
core/network/src/main/kotlin/com/weather/core/network/model/geosearch/GeoSearchItemDto.kt
aarash709
605,957,736
false
{"Kotlin": 364629, "Shell": 694}
package com.weather.core.network.model.geosearch import com.weather.model.geocode.GeoSearchItem import kotlinx.serialization.Serializable @Serializable data class GeoSearchItemDto( val country: String? = null, val lat: Double? = null, val local_names: LocalNamesDto? = null, val lon: Double? = null, val name: String? = null, val state: String? = null, ) { fun toGeoSearchItem(): GeoSearchItem { return GeoSearchItem( country = country, lat = lat, local_names = local_names?.toLocalNames(), lon, name, state ) } }
2
Kotlin
2
5
009100603473a56044ede5c43b74c5e3e9fcfd67
635
Weather
Apache License 2.0
core/src/main/java/org/futo/circles/core/feature/workspace/SpacesTreeAccountDataSource.kt
circles-project
615,347,618
false
{"Kotlin": 1307644, "C": 137821, "C++": 12364, "Shell": 3202, "CMake": 1680, "Ruby": 922}
package org.futo.circles.core.feature.workspace import org.futo.circles.core.model.CIRCLES_SPACE_ACCOUNT_DATA_KEY import org.futo.circles.core.provider.MatrixSessionProvider import org.futo.circles.core.utils.getJoinedRoomById import javax.inject.Inject class SpacesTreeAccountDataSource @Inject constructor() { private fun getSpacesTreeConfig() = MatrixSessionProvider.currentSession?.accountDataService() ?.getUserAccountDataEvent(SPACES_CONFIG_KEY)?.content ?: emptyMap() suspend fun updateSpacesConfigAccountData(key: String, roomId: String) { val currentConfig = getSpacesTreeConfig().toMutableMap() currentConfig[key] = roomId saveSpacesTreeConfig(currentConfig) } fun getRoomIdByKey(key: String) = getSpacesTreeConfig()[key]?.toString() fun getJoinedCirclesIds(): List<String> { val circlesSpaceId = getRoomIdByKey(CIRCLES_SPACE_ACCOUNT_DATA_KEY) ?: return emptyList() val ids = getJoinedRoomById(circlesSpaceId)?.roomSummary()?.spaceChildren ?.map { it.childRoomId } ?.filter { getJoinedRoomById(it) != null } return ids ?: emptyList() } private suspend fun saveSpacesTreeConfig(configMap: Map<String, Any>) { MatrixSessionProvider.getSessionOrThrow().accountDataService() .updateUserAccountData(SPACES_CONFIG_KEY, configMap) } companion object { private const val SPACES_CONFIG_KEY = "org.futo.circles.config" } }
8
Kotlin
4
29
7edec708f9c491a7b6f139fc2f2aa3e2b7149112
1,490
circles-android
Apache License 2.0
bot/src/main/kotlin/me/y9san9/prizebot/actors/telegram/sender/GiveawaySender.kt
nullcookies
354,393,208
true
{"Kotlin": 113608}
package me.y9san9.prizebot.actors.telegram.sender import me.y9san9.prizebot.actors.storage.giveaways_storage.Giveaway import me.y9san9.prizebot.actors.storage.giveaways_storage.GiveawaysStorage import me.y9san9.prizebot.actors.storage.participants_storage.ParticipantsStorage import me.y9san9.prizebot.resources.content.giveawayContent import me.y9san9.telegram.updates.extensions.send_message.sendMessage import me.y9san9.telegram.updates.hierarchies.FromChatLocalizedBotUpdate import me.y9san9.telegram.updates.primitives.DIUpdate import me.y9san9.telegram.updates.primitives.HasTextUpdate object GiveawaySender { suspend fun <TUpdate, TDI> send(update: TUpdate) where TUpdate : FromChatLocalizedBotUpdate, TUpdate : HasTextUpdate, TUpdate : DIUpdate<TDI>, TDI : ParticipantsStorage, TDI: GiveawaysStorage { val (entities, markup) = giveawayContent(update) ?: return update.sendMessage(entities, replyMarkup = markup) } suspend fun send(update: FromChatLocalizedBotUpdate, giveaway: Giveaway, participantsCount: Int, demo: Boolean = false) { val (entities, markup) = giveawayContent(update, giveaway, participantsCount, demo) update.sendMessage(entities, replyMarkup = markup) } }
0
null
0
0
a06f7c2fb5193b07e645ca2f848e8242f609a2fb
1,260
prizebot
MIT License
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/ExpressionBodySyntaxTest.kt
snowe2010
110,291,619
true
{"Kotlin": 481755, "Groovy": 1433}
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.test.RuleTest import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test /** * @author <NAME> */ internal class ExpressionBodySyntaxTest : RuleTest { override val rule: Rule = ExpressionBodySyntax() @Test fun returnStmtWithConstant() { assertThat(rule.lint(""" fun stuff(): Int { return 5 } """ )).hasSize(1) } @Test fun returnStmtWithMethodChain() { assertThat(rule.lint(""" fun stuff(): Int { return moreStuff().getStuff().stuffStuff() } """ )).hasSize(1) } @Test fun returnStmtWithMultilineChain() { assertThat(rule.lint(""" fun stuff(): Int { return moreStuff() .getStuff() .stuffStuff() } """)).hasSize(1) } @Test fun returnStmtWithConditionalStmt() { assertThat(rule.lint(""" fun stuff(): Int { return if (true) return 5 else return 3 } fun stuff(): Int { return try { return 5 } catch (e: Exception) { return 3 } } """)).hasSize(2) } @Test fun multipleReturnStmt() { assertThat(rule.lint(""" fun stuff(): Int { if (true) return true return false } """)).hasSize(0) } }
0
Kotlin
0
0
b9f7b6e7c8cd86e84b5cb88a04c92111d76df6ad
1,295
detekt
Apache License 2.0
app/src/main/java/com/example/moviesappcompose/data/model/Movies.kt
abhineshchandra1234
725,040,567
false
{"Kotlin": 18971}
package com.example.moviesappcompose.data.model data class Movies( val page: Int?, val results: List<Results?>? ) { data class Results( val id:Long?, val original_title:String?, val overview:String?, val poster_path:String?, val vote_average:Float? ) }
0
Kotlin
0
0
ee84e93417b79ce61965f96f54a3ab2d09a4eef4
310
Movies_App_Compose
Apache License 2.0
data/src/main/java/mobdao/com/openquiz/data/repositories/opentriviarepository/OpenTriviaRepository.kt
diegohkd
209,090,263
false
null
package mobdao.com.openquiz.data.repositories.opentriviarepository import mobdao.com.openquiz.models.Question interface OpenTriviaRepository { suspend fun fetchQuestions(nOfQuestions: Int): List<Question> }
0
Kotlin
0
0
3ba3f957840711869af81c9a63c5495111cbe817
213
OpenQuizAndroid
Apache License 2.0
app/src/main/java/xyz/thaihuynh/tmdb/data/Movie.kt
thaihuynhxyz
696,823,267
false
{"Kotlin": 70305}
package xyz.thaihuynh.tmdb.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import com.google.gson.annotations.SerializedName import xyz.thaihuynh.tmdb.data.db.TmdbTypeConverters @Entity @TypeConverters(TmdbTypeConverters::class) data class Movie( @PrimaryKey val id: Int, val adult: Boolean? = null, val budget: Int? = null, val revenue: Int? = null, val runtime: Int? = null, val status: String? = null, val tagline: String? = null, val homepage: String? = null, @ColumnInfo(name = "imdb_id") @field:SerializedName("imdb_id") val imdbId: String? = null, @ColumnInfo(name = "backdrop_path") @field:SerializedName("backdrop_path") val backdropPath: String? = null, val title: String? = null, @ColumnInfo(name = "original_language") @field:SerializedName("original_language") val originalLanguage: String? = null, @ColumnInfo(name = "original_title") @field:SerializedName("original_title") val originalTitle: String? = null, val overview: String? = null, @ColumnInfo(name = "poster_path") @field:SerializedName("poster_path") val posterPath: String? = null, @ColumnInfo(name = "media_type") @field:SerializedName("media_type") val mediaType: String? = null, @ColumnInfo(name = "genre_ids") @field:SerializedName("genre_ids") val genreIds: List<Int>? = null, val popularity: Double? = null, @ColumnInfo(name = "release_date") @field:SerializedName("release_date") val releaseDate: String? = null, val video: Boolean? = null, @ColumnInfo(name = "vote_average") @field:SerializedName("vote_average") val voteAverage: Double? = null, @ColumnInfo(name = "vote_count") @field:SerializedName("vote_count") val voteCount: Int? = null, )
0
Kotlin
0
0
8b74aa4e73eaae44dd680d1bd431ed5792947304
1,882
tmdb-app
MIT License
library/src/main/kotlin/dev/jahir/blueprint/ui/fragments/IconsCategoriesFragment.kt
MarcusMaximus
341,450,526
true
{"Kotlin": 196706}
package dev.jahir.blueprint.ui.fragments import android.content.Intent import android.graphics.drawable.Drawable import android.os.Bundle import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import dev.jahir.blueprint.R import dev.jahir.blueprint.data.models.Icon import dev.jahir.blueprint.data.models.IconsCategory import dev.jahir.blueprint.extensions.defaultLauncher import dev.jahir.blueprint.extensions.pickIcon import dev.jahir.blueprint.ui.activities.BlueprintActivity import dev.jahir.blueprint.ui.activities.IconsCategoryActivity import dev.jahir.blueprint.ui.adapters.IconsCategoriesAdapter import dev.jahir.frames.extensions.resources.dpToPx import dev.jahir.frames.extensions.resources.hasContent import dev.jahir.frames.extensions.resources.lower import dev.jahir.frames.extensions.views.setPaddingBottom import dev.jahir.frames.ui.activities.base.BaseSystemUIVisibilityActivity import dev.jahir.frames.ui.fragments.base.BaseFramesFragment class IconsCategoriesFragment : BaseFramesFragment<IconsCategory>() { private val iconsCategoriesAdapter: IconsCategoriesAdapter by lazy { IconsCategoriesAdapter(::onOpenCategory, ::onIconClick) } private val fabHeight: Int get() { (activity as? BlueprintActivity)?.let { return if (it.initialItemId == R.id.icons && it.defaultLauncher != null) it.fabBtn?.measuredHeight ?: 0 else 0 } ?: return 0 } private val extraHeight: Int get() = if (fabHeight > 0) 16.dpToPx else 0 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerView?.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false).apply { isItemPrefetchEnabled = true } recyclerView?.adapter = iconsCategoriesAdapter recyclerView?.setHasFixedSize(true) loadData() } override fun setupContentBottomOffset(view: View?) { (view ?: getView())?.let { v -> v.post { val bottomNavigationHeight = (context as? BaseSystemUIVisibilityActivity<*>)?.bottomNavigation?.measuredHeight ?: 0 v.setPaddingBottom(bottomNavigationHeight) recyclerView?.setupBottomOffset(fabHeight + extraHeight) } } } override fun loadData() { (activity as? BlueprintActivity)?.loadIconsCategories() } override fun getFilteredItems( originalItems: ArrayList<IconsCategory>, filter: String ): ArrayList<IconsCategory> { if (!filter.hasContent()) return originalItems val filteredItems: ArrayList<IconsCategory> = ArrayList() originalItems.forEach { val filteredIcons = it.getIcons().filter { icon -> icon.name.lower().contains(filter.lower()) } if (it.title.lower().contains(filter.lower()) || filteredIcons.isNotEmpty()) { val pair: Pair<ArrayList<Icon>, Boolean> = if (filteredIcons.isNotEmpty()) Pair(ArrayList(filteredIcons), true) else Pair(it.getIcons(), false) filteredItems.add(IconsCategory(it.title, pair.first, pair.second)) } } return filteredItems } override fun updateItemsInAdapter(items: ArrayList<IconsCategory>) { iconsCategoriesAdapter.categories = items } internal fun notifyShapeChange() { iconsCategoriesAdapter.notifyDataSetChanged() } private fun onOpenCategory(category: IconsCategory) { val pickerKey = (activity as? BlueprintActivity)?.pickerKey ?: 0 startActivityForResult( Intent(context, IconsCategoryActivity::class.java).apply { putExtra(IconsCategoryActivity.CATEGORY_KEY, category) putExtra(IconsCategoryActivity.PICKER_KEY, pickerKey) }, if (pickerKey != 0) 55 else 54 ) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 55) { activity?.let { it.setResult(resultCode, data) it.finish() } } } private fun onIconClick(icon: Icon, drawable: Drawable?) { val pickerKey = (activity as? BlueprintActivity)?.pickerKey ?: 0 if (pickerKey != 0) activity?.pickIcon(icon, drawable, pickerKey) else (activity as? BlueprintActivity)?.showIconDialog(icon) } companion object { const val TAG = "icons_categories_fragment" } }
0
null
0
0
7873d9ba2289868e078f57265635bbbbe1bc4fd7
4,805
papirusadaptive
Apache License 2.0
feature/assistant/src/main/java/com/memorati/feature/assistant/worker/AssistantScheduler.kt
HeidelX
640,943,698
false
{"Kotlin": 321937, "Ruby": 1925}
package com.memorati.feature.assistant.worker import android.content.Context import android.util.Log import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import com.memorati.core.common.di.ApplicationScope import com.memorati.core.datastore.PreferencesDataSource import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes import kotlin.time.toJavaDuration @Singleton class AssistantScheduler @Inject constructor( preferencesDataSource: PreferencesDataSource, @ApplicationScope applicationScope: CoroutineScope, @ApplicationContext private val context: Context, ) { init { preferencesDataSource.userData .map { it.reminderInterval } .distinctUntilChanged() .onEach { schedule(it) }.launchIn(applicationScope) } fun schedule(duration: Duration = 15.minutes) { Log.d(TAG, "schedule(duration=$duration)") WorkManager.getInstance(context) .enqueueUniquePeriodicWork( AssistantWorker.NAME, ExistingPeriodicWorkPolicy.UPDATE, PeriodicWorkRequestBuilder<DelegatingWorker>( repeatInterval = duration.toJavaDuration(), ).setInputData(AssistantWorker::class.delegatedData()).build(), ) } companion object { private const val TAG = "AssistantScheduler" } }
3
Kotlin
0
0
5ac9dede4828f246f2d32fdc9bce571b711f8f57
1,801
Memorati
MIT License
scheduling/src/main/java/com/nabla/sdk/scheduling/LoggerExtensions.kt
nabla
478,468,099
false
{"Kotlin": 1146406, "Java": 20507}
package com.nabla.sdk.scheduling import com.nabla.sdk.core.domain.boundary.Logger internal class SchedulingDomain { val UI = "Scheduling-UI" } internal val Logger.Companion.SCHEDULING_DOMAIN: SchedulingDomain get() = SchedulingDomain()
0
Kotlin
2
18
57e42d4bfc7bbb5202cf472e8c9279a23de090cc
247
nabla-android
MIT License
app/src/main/java/nl/hva/emergencyexitapp/MainActivity.kt
mgyanku
876,678,304
false
{"Kotlin": 42009}
package nl.hva.emergencyexitapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import nl.hva.emergencyexitapp.ui.theme.EmergencyExitAppTheme import nl.hva.emergencyexitapp.ui.theme.coralPink import nl.hva.emergencyexitapp.ui.theme.screens.AddScreen import nl.hva.emergencyexitapp.ui.theme.screens.AppScreens import nl.hva.emergencyexitapp.ui.theme.screens.HomeScreen import nl.hva.emergencyexitapp.ui.theme.screens.InstructionScreen import nl.hva.emergencyexitapp.ui.theme.screens.SearchScreen import nl.hva.emergencyexitapp.ui.theme.screens.SettingsScreen import nl.hva.emergencyexitapp.ui.theme.white import nl.hva.emergencyexitapp.viewmodel.SituationViewModel class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { installSplashScreen() super.onCreate(savedInstanceState) setContent { EmergencyExitAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { // Call base scaffold AppScaffold() } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun AppScaffold() { val navController = rememberNavController() Scaffold( topBar = { TopAppBar( title = { Text( text = stringResource(id = R.string.app_name), color = white ) }, colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = coralPink) ) }, bottomBar = { BottomNav(navController) }, content = { innerPadding -> AppNavHost( navController, modifier = Modifier.padding(innerPadding) ) }, ) } /** * You can see this as a nav_graph.xml in compose environment. */ @Composable private fun AppNavHost(navController: NavHostController, modifier: Modifier) { val viewModel: SituationViewModel = viewModel() NavHost( navController = navController, startDestination = AppScreens.HomeScreen.route, modifier = modifier ) { composable(route = AppScreens.HomeScreen.route) { HomeScreen(navController) } composable(route = AppScreens.SearchScreen.route) { SearchScreen(navController, viewModel) println(viewModel.backlog.value) } composable(route = "${AppScreens.InstructionScreen.route}/{situationId}") { backStackEntry -> val situation = backStackEntry.arguments?.getString("situationId") if (situation != null) { InstructionScreen(navController, viewModel, situation.toInt()-1) } else { // Screen will catch this error InstructionScreen(navController, viewModel, -1) } } composable(route = AppScreens.AddScreen.route) { AddScreen(navController, viewModel) } composable(route = AppScreens.SettingsScreen.route) { SettingsScreen(navController, viewModel) } } } @Composable fun BottomNav(navController: NavHostController) { val items = listOf( AppScreens.HomeScreen, AppScreens.SearchScreen, AppScreens.AddScreen, AppScreens.SettingsScreen) BottomNavigation( modifier = Modifier, backgroundColor = coralPink ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry?.destination items.forEach { screen -> BottomNavigationItem( icon = { Icon( painter = painterResource(id = screen.icon), contentDescription = null ) }, label = { Text(stringResource(screen.resourceId)) }, selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true, selectedContentColor = white, unselectedContentColor = coralPink, onClick = { navController.navigate(screen.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } } ) } } }
0
Kotlin
0
0
785eb7e19e65ce11c135a81343a8257b4a09857e
6,116
emergency-exit-app
MIT License
flt_umengpush_common/android/src/main/kotlin/dev/bughub/plugin/flt_umengpush_common/FltUmengpushCommonPlugin.kt
RandyWei
229,167,419
false
null
package dev.bughub.plugin.flt_umengpush_common import android.content.Context import android.text.TextUtils import android.util.Log import com.umeng.commonsdk.UMConfigure import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import io.flutter.plugin.common.PluginRegistry.Registrar class FltUmengpushCommonPlugin: MethodCallHandler,FlutterPlugin { var flutterPluginBinding: FlutterPlugin.FlutterPluginBinding? = null companion object { @JvmStatic fun init(context: Context, appKey:String, secret:String, channel:String="Umeng", deviceType:Int=UMConfigure.DEVICE_TYPE_PHONE){ if (TextUtils.isEmpty(secret)){ Log.e("UmengpushCommonPlugin","secret is null") return } if (TextUtils.isEmpty(appKey)){ Log.e("UmengpushCommonPlugin","appKey is null") return } UMConfigure.setLogEnabled(true) UMConfigure.init(context, appKey, channel, deviceType, secret) } } override fun onMethodCall(call: MethodCall, result: Result) { /** * 设置组件化的Log开关 * 参数: boolean 默认为false,如需查看LOG设置为true */ when (call.method) { "setLogEnabled" -> { val enabled = call.argument<Boolean>("enabled") ?: false UMConfigure.setLogEnabled(enabled) result.success(null) } "init" -> { val appKey = call.argument<String>("appKey") val secret = call.argument<String>("secret") val channel = call.argument<String>("channel") ?: "Umeng" val deviceType = call.argument<Int>("deviceType") ?: UMConfigure.DEVICE_TYPE_PHONE if (TextUtils.isEmpty(secret)){ result.error("0001","secret is null",null) return } if (TextUtils.isEmpty(appKey)){ result.error("0002","appKey is null",null) return } UMConfigure.init(flutterPluginBinding?.applicationContext, appKey, channel, deviceType, secret) result.success(null) } else -> { result.notImplemented() } } } override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { flutterPluginBinding = binding val channel = MethodChannel(binding.binaryMessenger, "plugin.bughub.dev/flt_umengpush_common") channel.setMethodCallHandler(this) } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { } }
1
Kotlin
1
3
200858f7d3d841671e680737747239fc4c779334
2,622
flt_umengpush
MIT License
examples/user/verifyToken/verifyAToken/main.kt
GWT-M3O-TEST
485,009,715
false
null
package examples.user.verifyToken import com.m3o.m3okotlin.M3O import com.m3o.m3okotlin.services.user suspend fun main() { M3O.initialize(System.getenv("M3O_API_TOKEN")) val req = UserVerifyTokenRequest(Token = "EdsUiidouJJJLldjlloofUiorkojflsWWdld",) try { val response = UserServ.verifyToken(req) println(response) } catch (e: Exception) { println(e) } }
1
Kotlin
1
0
54158b584ba47bd7323a484804dcd78c55ef7f69
392
m3o-kotlin
Apache License 2.0
teamcity-kotlin-trigger-server/src/main/kotlin/jetbrains/buildServer/buildTriggers/remote/FindProjectByRequest.kt
JetBrains
307,772,250
false
null
/* * Copyright 2000-2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.buildTriggers.remote import com.intellij.openapi.diagnostic.Logger import jetbrains.buildServer.serverSide.ProjectManager import jetbrains.buildServer.serverSide.SProject import javax.servlet.http.HttpServletRequest private const val BT_PREFIX = "buildType:" private const val TEMPLATE_PREFIX = "template:" fun ProjectManager.findProjectByRequest(request: HttpServletRequest, logger: Logger): SProject? { val projectId = request.getParameter("projectId") if (projectId != null) { val project = findProjectByExternalId(projectId) if (project != null) return project else logger.warn("No project found by project id '$projectId'") } val id = request.getParameter("id") ?: return null return when { id.startsWith(BT_PREFIX) -> { val buildTypeId = id.substring(BT_PREFIX.length) val buildType = findBuildTypeByExternalId(buildTypeId) buildType?.project ?: run { logger.warn("No build type found by id '$buildTypeId'") null } } id.startsWith(TEMPLATE_PREFIX) -> { val templateId = id.substring(TEMPLATE_PREFIX.length) val template = findBuildTypeTemplateByExternalId(templateId) template?.project ?: run { logger.warn("No template found by id '$templateId'") null } } else -> { val buildType = findBuildTypeByExternalId(id) val template = findBuildTypeTemplateByExternalId(id) buildType?.project ?: template?.project ?: run { logger.warn("Cannot obtain current project: id '$id' does not belong to neither project, build type, nor template") null } } } }
2
Kotlin
1
1
5c509dc7be3599a0c993b7e88e8efa4e1e2a0219
2,528
teamcity-kotlin-trigger
Apache License 2.0
framework/src/main/java/com/mpapps/marvelcompose/framework/datasources/cloud/response/map/Map.kt
Erickjhoel
856,824,213
false
{"Kotlin": 72528}
package com.mpapps.marvelcompose.framework.datasources.cloud.response.map import com.mpapps.marvelcompose.data.model.CharactersDto import com.mpapps.marvelcompose.data.model.ComicDto import com.mpapps.marvelcompose.framework.datasources.cloud.response.MarvelApiResponse import com.mpapps.marvelcompose.framework.datasources.cloud.response.comics.MarvelComicApiResponse const val HTTP = "http" const val HTTPS = "https" fun MarvelApiResponse.toDto(): List<CharactersDto> = this.data.results.map { CharactersDto( id = it.id, name = it.name, description = it.description, thumbnail = (it.thumbnail.path + "." + it.thumbnail.extension).replace(HTTP, HTTPS) ) } fun MarvelComicApiResponse.toDto(): List<ComicDto> = this.data.results.map { ComicDto( title = it.title, thumbnail = (it.thumbnail.path + "." + it.thumbnail.extension).replace(HTTP, HTTPS) ) }
0
Kotlin
0
0
4e6140ca82dbe9e143f6aa3ea9aa2d64fefce1af
917
skeleton-Compose
Apache License 2.0
model/src/commonMain/kotlin/EnvironmentConfig.kt
eclipse-apoapsis
760,319,414
false
{"Kotlin": 2994047, "Dockerfile": 24090, "Shell": 6277}
/* * Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.eclipse.apoapsis.ortserver.model import kotlinx.serialization.Serializable /** * Type definition the generic map with environment definitions. */ typealias RepositoryEnvironmentDefinitions = Map<String, List<Map<String, String>>> /** * A data class describing the environment configuration of a specific repository. */ @Serializable data class EnvironmentConfig( /** The list of infrastructure services declared for this repository. */ val infrastructureServices: List<InfrastructureServiceDeclaration> = emptyList(), /** A map with environment definitions of different types. */ val environmentDefinitions: RepositoryEnvironmentDefinitions = emptyMap(), /** A list with declarations for environment variables for this repository. */ val environmentVariables: List<EnvironmentVariableDeclaration> = emptyList(), /** A flag that determines how semantic errors in the configuration file should be treated. */ val strict: Boolean = true )
18
Kotlin
2
9
0af70d6382a86f0ebc35d9b377f4229c6a71637a
1,745
ort-server
Apache License 2.0
app/src/main/java/fr/groggy/racecontrol/tv/core/season/SeasonRepository.kt
Groggy
281,733,730
false
null
package fr.groggy.racecontrol.tv.core.season import fr.groggy.racecontrol.tv.f1tv.F1TvSeason import fr.groggy.racecontrol.tv.f1tv.F1TvSeasonId import kotlinx.coroutines.flow.Flow interface SeasonRepository { fun observe(id: F1TvSeasonId): Flow<F1TvSeason?> suspend fun save(season: F1TvSeason) }
0
Kotlin
31
22
2a1f20090c34bda5db47ed8528ac54dcd49e5e8e
308
race-control-tv
MIT License
src/main/kotlin/http/paths/HTTPPathDocument.kt
GoodDamn
790,314,479
false
{"Kotlin": 59283, "HTML": 1590}
package good.damn.filesharing.http.paths import good.damn.filesharing.http.HTTPHeaders import good.damn.filesharing.http.HTTPPath import good.damn.filesharing.utils.FileUtils import java.io.File import java.io.FileInputStream import java.io.OutputStream class HTTPPathDocument( docPath: String, private val mimeType: String ): HTTPPathAction() { companion object { private val SERVER_DIR = FileUtils .getDocumentsFolder() } private val mFile = File( "$SERVER_DIR/$docPath" ) override fun execute( to: OutputStream, httpPath: HTTPPath ) { if (!mFile.exists()) { HTTPHeaders.error( to ) return } val inp = FileInputStream( mFile ) val contentSize = mFile.length() .toInt() HTTPHeaders.document( to, mimeType, contentSize ) FileUtils.copyBytes( inp, to ) } }
0
Kotlin
0
0
929fc116da36cfd0f46954243c1ef8d30512dd19
1,051
DesktopServer
MIT License
ui/src/commonMain/kotlin/kosh/ui/navigation/listdetails/DefaultListDetailRouter.kt
niallkh
855,100,709
false
{"Kotlin": 1942525, "Swift": 25802}
package kosh.ui.navigation.listdetails import androidx.compose.runtime.Composable import androidx.compose.runtime.DisallowComposableCalls import com.arkivanov.decompose.Child import com.arkivanov.decompose.router.children.SimpleNavigation import com.arkivanov.decompose.router.children.children import com.arkivanov.decompose.value.Value import com.arkivanov.essenty.backhandler.BackCallback import kosh.presentation.core.UiContext import kosh.presentation.di.rememberOnRoute import kosh.ui.navigation.RouteResult import kosh.ui.navigation.routes.Route import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.serializer class DefaultListDetailRouter<R : Route>( uiContext: UiContext, serializer: KSerializer<R>, initial: () -> ListDetailState<R>, private val onResult: ListDetailRouter<R>.(RouteResult<R>) -> Unit, ) : ListDetailRouter<R>, UiContext by uiContext { private val navigation = SimpleNavigation<ListDetailEvent<R>>() private val backCallback = BackCallback { pop() } init { backHandler.register(backCallback) } override val children: Value<ListDetailRouter.Children<R>> = children( source = navigation, stateSerializer = ListDetailState.serializer(serializer), initialState = { initial() }, key = "ListDetailRouter", navTransformer = { navState, event -> event.transform(navState) }, onEventComplete = { event, newState, oldState -> event.onComplete(newState, oldState) }, stateMapper = { navState, children -> ListDetailRouter.Children( multipane = navState.multipane, list = children[0] as Child.Created<R, UiContext>, detail = children.getOrNull(1) as Child.Created<R, UiContext>?, ) }, childFactory = { _, ctx -> ctx }, ) override fun multipane(multipane: Boolean) { navigation.multipane(multipane) } override fun push(route: R) { navigation.push(route) } override fun pop(result: RouteResult<R>) { navigation.popOr { onResult(result) } } override fun pop() { navigation.popOr { onResult(RouteResult.Result()) } } override fun result(redirect: String?) { onResult(RouteResult.Result()) } override fun navigateUp() { onResult(RouteResult.Up(null)) } override fun handle(link: R?) { } } @Composable inline fun <reified R : @Serializable Route> rememberListDetailRouter( link: R? = null, noinline onResult: ListDetailRouter<R>.(RouteResult<R>) -> Unit, serializer: KSerializer<R> = serializer(), noinline list: @DisallowComposableCalls () -> R, ): ListDetailRouter<R> { val stackRouter = rememberOnRoute<ListDetailRouter<R>> { DefaultListDetailRouter( uiContext = this, serializer = serializer, initial = { // TODO check if deeplink ListDetailState( list = list(), detail = link.takeIf { it != list() } ) }, onResult = { onResult(it) }, ) } return stackRouter }
0
Kotlin
0
3
e0149252019f8b47ceede5c0c1eb78c0a1e1c203
3,247
kosh
MIT License
sample/src/main/java/com/dylanc/mmkv/sample/MainActivity.kt
DylanCaiCoding
409,925,969
false
null
package com.dylanc.mmkv.sample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.dylanc.mmkv.MMKVOwner import com.tencent.mmkv.MMKV class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val dir = filesDir.absolutePath + "/mmkv_2" MMKV.initialize(this, dir) } }
3
Kotlin
11
99
898b3413ba46b21a0a8e0657867cf7b5e360a7af
434
MMKV-KTX
Apache License 2.0
data/src/main/java/com/yazan98/wintrop/data/database/ConditionDatabase.kt
Yazan98
233,426,806
false
null
package com.yazan98.wintrop.data.database import androidx.room.Database import androidx.room.RoomDatabase import com.yazan98.wintrop.data.database.daos.ConditionDao import com.yazan98.wintrop.data.database.daos.ConditionMonthDao import com.yazan98.wintrop.data.database.daos.DaysDao import com.yazan98.wintrop.data.database.models.ConditionDay import com.yazan98.wintrop.data.database.models.ConditionEntity import com.yazan98.wintrop.data.database.models.ConditionMonth @Database( entities = [ConditionEntity::class, ConditionDay::class, ConditionMonth::class], version = 2 ) abstract class ConditionDatabase : RoomDatabase() { abstract fun conditionsDao(): ConditionDao abstract fun daysDao(): DaysDao abstract fun monthsDao(): ConditionMonthDao }
0
Kotlin
0
1
c961e10d37bfb1e7787b5f608050b2983964eb86
774
Wintrop
Apache License 2.0
subprojects/dsl/src/main/kotlin/co/uzzu/structurizr/ktx/dsl/view/ViewSetDsl.kt
uzzu
291,060,647
false
null
@file:Suppress("FunctionName") package co.uzzu.structurizr.ktx.dsl.view import co.uzzu.structurizr.ktx.dsl.ApplyBlock import co.uzzu.structurizr.ktx.dsl.applyIfNotNull import com.structurizr.model.Container import com.structurizr.model.SoftwareSystem import com.structurizr.view.ComponentView import com.structurizr.view.ContainerView import com.structurizr.view.DeploymentView import com.structurizr.view.DynamicView import com.structurizr.view.FilterMode import com.structurizr.view.FilteredView import com.structurizr.view.StaticView import com.structurizr.view.Styles import com.structurizr.view.SystemContextView import com.structurizr.view.SystemLandscapeView import com.structurizr.view.ViewSet class ViewSetScope( private val views: ViewSet ) { /** * @see [ViewSet.createSystemLandscapeView] */ fun SystemLandscapeView( key: String, description: String? = null, block: ApplyBlock<ViewScope<SystemLandscapeView>>? = null ): SystemLandscapeView = views.createSystemLandscapeView(key, description) .apply { block?.let { ViewScope(this).apply(it) } } /** * @see [ViewSet.createSystemContextView] */ fun SystemContextView( softwareSystem: SoftwareSystem, key: String, description: String? = null, block: ApplyBlock<ViewScope<SystemContextView>>? = null ): SystemContextView = views.createSystemContextView(softwareSystem, key, description) .apply { block?.let { ViewScope<SystemContextView>(this).apply(it) } } /** * @see [ViewSet.createContainerView] */ fun ContainerView( softwareSystem: SoftwareSystem, key: String, description: String? = null, block: ApplyBlock<ViewScope<ContainerView>>? = null ): ContainerView = views.createContainerView(softwareSystem, key, description) .apply { block?.let { ViewScope(this).apply(it) } } /** * @see [ViewSet.createComponentView] */ fun ComponentView( container: Container, key: String, description: String? = null, block: ApplyBlock<ViewScope<ComponentView>>? = null ): ComponentView = views.createComponentView(container, key, description) .apply { block?.let { ViewScope(this).apply(it) } } /** * @see [ViewSet.createDynamicView] */ fun DynamicView( key: String, description: String? = null, block: ApplyBlock<ViewScope<DynamicView>>? = null ): DynamicView = views.createDynamicView(key, description) .apply { block?.let { ViewScope(this).apply(it) } } /** * @see [ViewSet.createDynamicView] */ fun DynamicView( softwareSystem: SoftwareSystem, key: String, description: String? = null, block: ApplyBlock<ViewScope<DynamicView>>? = null ): DynamicView = views.createDynamicView(softwareSystem, key, description) .apply { block?.let { ViewScope(this).apply(it) } } /** * @see [ViewSet.createDynamicView] */ fun DynamicView( container: Container, key: String, description: String? = null, block: ApplyBlock<ViewScope<DynamicView>>? = null ): DynamicView = views.createDynamicView(container, key, description) .apply { block?.let { ViewScope(this).apply(it) } } /** * @see [ViewSet.createDeploymentView] */ fun DeploymentView( key: String, description: String? = null, block: ApplyBlock<ViewScope<DeploymentView>>? = null ): DeploymentView = views.createDeploymentView(key, description) .apply { block?.let { ViewScope(this).apply(it) } } /** * @see [ViewSet.createDeploymentView] */ fun DeploymentView( softwareSystem: SoftwareSystem, key: String, description: String? = null, block: ApplyBlock<ViewScope<DeploymentView>>? = null ): DeploymentView = views.createDeploymentView(softwareSystem, key, description) .apply { block?.let { ViewScope(this).apply(it) } } /** * @see [ViewSet.createFilteredView] */ fun FilteredView( staticView: StaticView, key: String, description: String? = null, mode: FilterMode, vararg tags: String, block: ApplyBlock<FilteredView>? = null ): FilteredView = views.createFilteredView(staticView, key, description, mode, *tags) .applyIfNotNull(block) /** * @see [ViewSet.createDefaultViews] */ fun defaultViews() { views.createDefaultViews() } /** * @see [ViewSet.configuration] * @param block [StylesScope] */ fun styles(block: ApplyBlock<StylesScope>): Styles = views.configuration.styles.apply { StylesScope(this).apply(block) } }
0
Kotlin
0
0
a198f0b9aefe662f216f6182eb7fcfa45a20a05e
4,917
structurizr-ktx
Apache License 2.0
src/main/kotlin/br/com/zup/register/bccclient/request/CreatePixKeyRequest.kt
andersonzup
407,183,392
true
{"Kotlin": 26996}
package br.com.zup.register.bccclient.request import io.micronaut.core.annotation.Introspected @Introspected data class CreatePixKeyRequest( val keyType: String, val key: String, val bankAccount: BankAccountRequest, val owner: OwnerRequest ) { }
0
Kotlin
0
0
15ec8e2fd8d0a9996eff2965adc1837330db6ecf
265
orange-talents-07-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/com/atanana/sicounter/Exceptions.kt
atanana
60,375,826
false
null
package com.atanana.sicounter open class SiCounterException(message: String) : RuntimeException(message) class UnknownId(val id: Int) : SiCounterException("Unknown id $id!")
0
Kotlin
0
0
ca5f715ef3a5c5acb893a3fc9e57f03299676e89
175
si_counter
MIT License
app/src/main/java/com/nafanya/mp3world/core/listManagers/ListManager.kt
AlexSoWhite
445,900,000
false
null
package com.nafanya.mp3world.core.listManagers import com.nafanya.mp3world.core.mediaStore.MediaStoreReader interface ListManager { suspend fun populate(mediaStoreReader: MediaStoreReader) }
0
Kotlin
0
0
f962a7a8ae30fa12ffc7d81a65ca292af4cd9b6e
198
mp3world
MIT License
app/src/main/java/com/example/recipekeeper/utils/ItemTouchHelperCallback.kt
Esce-gh
823,855,564
false
{"Kotlin": 91850, "Java": 8040}
package com.example.recipekeeper.utils import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.example.recipekeeper.adapters.ItemAdapterEdit class ItemTouchHelperCallback( private val adapter: ItemAdapterEdit ) : ItemTouchHelper.Callback() { override fun getMovementFlags( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder ): Int { val position = viewHolder.adapterPosition return if (position == 0) { 0 // Disable movement for default group header } else { val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN val swipeFlags = 0 makeMovementFlags(dragFlags, swipeFlags) } } override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val fromPosition = viewHolder.adapterPosition val toPosition = target.adapterPosition adapter.onItemMove(fromPosition, toPosition) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { // Not needed for drag and drop } override fun isLongPressDragEnabled(): Boolean { return true } override fun isItemViewSwipeEnabled(): Boolean { return false } }
0
Kotlin
0
0
5560f8a2d000f7e0e93fda95d34abdb1e459d0dd
1,403
RecipeKeeper
MIT License
app/src/main/java/com/daigorian/epcltvapp/SettingsActivity.kt
daig0rian
374,248,298
false
null
package com.daigorian.epcltvapp import android.app.Activity import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE import android.os.Build import android.os.Bundle class SettingsActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) { requestedOrientation = SCREEN_ORIENTATION_LANDSCAPE } } }
0
Kotlin
10
37
a2995bf7d2b03435c4da6cc9397612a87c1266cf
512
epcltvapp
MIT License
lib/src/commonMain/kotlin/xyz/mcxross/ksui/util/Extension.kt
mcxross
611,172,630
false
{"Kotlin": 202859, "Shell": 2264}
package xyz.mcxross.ksui.util import xyz.mcxross.ksui.model.Argument import xyz.mcxross.ksui.model.ProgrammableTransactionBuilder import xyz.mcxross.ksui.model.SuiAddress import xyz.mcxross.ksui.model.TransactionDigest /** Extension function to create a [TransactionDigest] from a [String]. */ fun String.toTxnDigest(): TransactionDigest = TransactionDigest(this) /** Extension function to create a [SuiAddress] from a [String]. */ fun String.toSuiAddress(): SuiAddress = SuiAddress(this) /** Extension functions to create [Argument.Input]s from various types. */ inline fun <reified T : Any> ProgrammableTransactionBuilder.inputs( vararg inputs: T ): List<Argument.Input> { return inputs.map { input(it) } }
3
Kotlin
2
4
eec1a6f41e0c3d8a41528608a433fd2b3322d5c2
717
ksui
Apache License 2.0
lib_imagepick/src/main/kotlin/com/imagepick/model/MediaType.kt
yudengwei
818,541,459
false
{"Kotlin": 310654}
package com.imagepick.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize sealed interface MediaType : Parcelable { @Parcelize data object ImageOnly : MediaType @Parcelize data object VideoOnly : MediaType @Parcelize data object ImageAndVideo : MediaType @Parcelize data class MultipleMimeType(val mimeTypes : Set<String>) : MediaType }
0
Kotlin
0
0
283dedc4b1005c72730c63efb8218730a6348535
403
composedemo
Apache License 2.0
app/src/main/java/com/exner/tools/meditationtimer/data/persistence/MeditationTimerDataIdAndName.kt
janexner
739,122,813
false
{"Kotlin": 151003}
package com.exner.tools.meditationtimer.data.persistence class MeditationTimerDataIdAndName( var uuid: String, var name: String )
1
Kotlin
0
2
48be01570a9fd156521114c7c02e12b8aea230e4
138
MeditationTimerAndroid
Apache License 2.0
delegate/src/main/java/com/yesferal/hornsapp/delegate/delegate/DividerDelegate.kt
Yesferal
320,718,330
false
{"Kotlin": 24293}
package com.yesferal.hornsapp.delegate.delegate import android.view.View import android.widget.FrameLayout import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import com.yesferal.hornsapp.delegate.R import com.yesferal.hornsapp.delegate.util.convertDpToPixel data class DividerDelegate( private val width: Int = 0, private val height: Int = 0, @ColorRes private val background: Int? = null ) : NonInteractiveDelegate { override fun onBindViewDelegate(view: View) { view.findViewById<View>(R.id.view).let { dividerView -> val widthAsPixels = convertDpToPixel(width.toFloat(), view.context) val heightAsPixels = convertDpToPixel(height.toFloat(), view.context) dividerView.layoutParams = FrameLayout.LayoutParams(widthAsPixels, heightAsPixels) background?.let { dividerView.setBackgroundColor(ContextCompat.getColor(view.context, it)) } } } override val layout: Int get() = R.layout.item_divider }
0
Kotlin
0
1
b0ea776de0a0020553f0fb0fdf29d3d2794156f6
1,051
DelegateAdapter
Apache License 2.0
src/main/kotlin/indi/midreamsheep/app/tre/model/render/listener/TRERenderListener.kt
Simple-Markdown
744,897,915
false
{"Kotlin": 178878, "Java": 67578}
package indi.midreamsheep.app.tre.model.render.listener import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.type import indi.midreamsheep.app.tre.context.editor.TREEditorContext import indi.midreamsheep.app.tre.model.render.style.styletext.TREStyleTextTree abstract class TRERenderListener{ abstract fun keyEvent( key:KeyEvent, context: TREEditorContext, styleTextTree: TREStyleTextTree ):Boolean fun handleKeyEvent( key:KeyEvent, context: TREEditorContext, styleTextTree: TREStyleTextTree ):Boolean { context.treTextFieldShortcutKeyManager.update((key)) if(key.type != KeyEventType.KeyDown){ return false } if (keyEvent(key,context,styleTextTree)){ return true } return context.treTextFieldShortcutKeyManager.keyEvent(key,context) } open fun setStartIndex(startIndex: Int) { } open fun getStartIndex(): Int { return 0 } }
0
Kotlin
0
3
3a2c5dde66af9f8c4fbe45c456c8eaf9af9b9825
1,058
SMarkdown
Apache License 2.0
base/src/main/kotlin/com/github/otakusenpai/alohachat/base/message_parse/ChatMsg.kt
OtakuSenpai
173,485,288
false
null
package com.github.otakusenpai.alohachat.base.message_parse import com.github.otakusenpai.alohachat.base.helpers.* class ChatMsg() { constructor(msg: String) : this() { originalMsg = msg msgdata = parseStrToMsgData(msg) receiverPrefix = msgdata.receiverPrefix } constructor(msgData: MsgData) : this() { originalMsg = msgData.toString() receiverPrefix = msgdata.receiverPrefix } override fun toString(): String = msgDataToStr(msgdata) fun print() { println("Receiver Address: ${msgdata.receiverPrefix.originalPrefix}") println("Sender Address: ${msgdata.senderPrefix.originalPrefix}") println("Msg TYPE: ${msgdata.numeric}") println("Chat or DM: ${msgdata.channelMsg}") println("Data: ${msgdata.data} ") } var msgdata = MsgData() lateinit var receiverPrefix: Prefix var originalMsg: String = "" }
0
Kotlin
0
1
c5714d57568eee0234026ce8b7a4f16ad3bffa81
927
AlohaChatSystem
MIT License
app/src/main/java/com/mioamorefsm/features/stockAddCurrentStock/api/ShopAddStockRepository.kt
DebashisINT
524,006,838
false
null
package com.mioamorefsm.features.stockAddCurrentStock.api import com.mioamorefsm.base.BaseResponse import com.mioamorefsm.features.location.model.ShopRevisitStatusRequest import com.mioamorefsm.features.location.shopRevisitStatus.ShopRevisitStatusApi import com.mioamorefsm.features.stockAddCurrentStock.ShopAddCurrentStockRequest import com.mioamorefsm.features.stockAddCurrentStock.model.CurrentStockGetData import com.mioamorefsm.features.stockCompetetorStock.model.CompetetorStockGetData import io.reactivex.Observable class ShopAddStockRepository (val apiService : ShopAddStockApi){ fun shopAddStock(shopAddCurrentStockRequest: ShopAddCurrentStockRequest?): Observable<BaseResponse> { return apiService.submShopAddStock(shopAddCurrentStockRequest) } fun getCurrStockList(sessiontoken: String, user_id: String, date: String): Observable<CurrentStockGetData> { return apiService.getCurrStockListApi(sessiontoken, user_id, date) } }
0
Kotlin
0
0
b18c8515f404ca5e51c60c85c22676ef77712104
970
SwitzFood
Apache License 2.0
src/main/kotlin/com/nurkiewicz/tsclass/parser/visitors/ExpressionVisitor.kt
nurkiewicz
91,668,257
false
null
package com.nurkiewicz.tsclass.parser.visitors import com.nurkiewicz.tsclass.antlr.parser.TypeScriptBaseVisitor import com.nurkiewicz.tsclass.antlr.parser.TypeScriptParser import com.nurkiewicz.tsclass.parser.ast.Expression import com.nurkiewicz.tsclass.parser.ast.Relational internal object ExpressionVisitor : TypeScriptBaseVisitor<Expression>() { override fun visitRelationalExpression(ctx: TypeScriptParser.RelationalExpressionContext): Expression { return if (ctx.relationalOperator() != null) { val left = ctx.relationalExpression().accept(this) val right = ctx.shiftExpression().accept(AdditiveExpressionVisitor()) val operator = Relational.Operator.of(ctx.relationalOperator().text) Relational(left, operator, right) } else { ctx.accept(AdditiveExpressionVisitor()) } } }
23
Kotlin
1
9
6690986077ade8f154165dc51fbb99657fe372f6
874
ts.class
Apache License 2.0
src/main/kotlin/no/nav/pensjon/simulator/core/domain/regler/gomregning/KravFaktoromregningResultat.kt
navikt
753,551,695
false
{"Kotlin": 1507098, "Java": 133600, "Dockerfile": 144}
package no.nav.pensjon.simulator.core.domain.regler.gomregning import no.nav.pensjon.simulator.core.domain.regler.BatchStatus class KravFaktoromregningResultat( var kravId: Long? = null, var batchStatus: BatchStatus? = null, var persongrunnlagOmregningResultatListe: MutableList<PersongrunnlagOmregningResultat> = mutableListOf() ) { fun beregningResultatListe(): Array<PersongrunnlagOmregningResultat> { return persongrunnlagOmregningResultatListe.toTypedArray() } }
0
Kotlin
0
0
32ef34837491247c078a5052e9124fed6e99517d
498
pensjonssimulator
MIT License
feature-home/src/main/java/com/agb/feature_home/ui/transactions/TransactionsDiffUtils.kt
AlmostGreatBand
302,001,051
false
null
package com.agb.feature_home.ui.transactions import androidx.recyclerview.widget.DiffUtil class TransactionsDiffUtils( private val old: List<TransactionRecyclerItem>, private val new: List<TransactionRecyclerItem>, ) : DiffUtil.Callback() { override fun getOldListSize() = old.size override fun getNewListSize() = new.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return old[oldItemPosition] === new[newItemPosition] } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return old[oldItemPosition] == new[newItemPosition] } }
3
Kotlin
0
0
572651e3aa89b6e4ce51e4676fe514be9c1d550f
658
lemon-android
MIT License
src/main/kotlin/dev/syoritohatsuki/deathcounter/event/PlayerDeathEvents.kt
syorito-hatsuki
551,977,804
false
{"Kotlin": 25036, "Java": 3061}
package dev.syoritohatsuki.deathcounter.event import dev.syoritohatsuki.deathcounter.event.PlayerDeathEvents.Death import net.fabricmc.fabric.api.event.Event import net.fabricmc.fabric.api.event.EventFactory import net.minecraft.server.network.ServerPlayerEntity object PlayerDeathEvents { val DEATH: Event<Death> = EventFactory.createArrayBacked(Death::class.java) { callbacks: Array<Death> -> Death { player -> callbacks.forEach { it.onDie(player) } } } fun interface Death { fun onDie(player: ServerPlayerEntity) } }
1
Kotlin
1
3
331423c8e24e6315b40ab6d049c07b51e3f5bb19
602
death-counter
MIT License
rest/src/main/kotlin/builder/interaction/PublicInteractionBuilder.kt
lost-illusi0n
383,626,467
true
{"Kotlin": 1390604}
package dev.kord.rest.builder.interaction import dev.kord.common.annotation.KordDsl import dev.kord.common.annotation.KordPreview import dev.kord.common.entity.InteractionResponseType import dev.kord.common.entity.optional.* import dev.kord.common.entity.optional.delegate.delegate import dev.kord.rest.builder.component.MessageComponentBuilder import dev.kord.rest.builder.message.AllowedMentionsBuilder import dev.kord.rest.builder.message.EmbedBuilder import dev.kord.rest.json.request.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.InputStream import java.nio.file.Files import java.nio.file.Path @KordPreview @KordDsl class PublicInteractionResponseCreateBuilder : BaseInteractionResponseCreateBuilder { private var _content: Optional<String> = Optional.Missing() override var content: String? by ::_content.delegate() override var embeds: MutableList<EmbedBuilder> = mutableListOf() private var _allowedMentions: Optional<AllowedMentionsBuilder> = Optional.Missing() override var allowedMentions: AllowedMentionsBuilder? by ::_allowedMentions.delegate() private var _tts: OptionalBoolean = OptionalBoolean.Missing var tts: Boolean? by ::_tts.delegate() override val components: MutableList<MessageComponentBuilder> = mutableListOf() val files: MutableList<Pair<String, InputStream>> = mutableListOf() fun addFile(name: String, content: InputStream) { files += name to content } suspend fun addFile(path: Path) = withContext(Dispatchers.IO) { addFile(path.fileName.toString(), Files.newInputStream(path)) } override fun toRequest(): MultipartInteractionResponseCreateRequest { val type = if (files.isEmpty() && content == null && embeds.isEmpty()) InteractionResponseType.DeferredChannelMessageWithSource else InteractionResponseType.ChannelMessageWithSource return MultipartInteractionResponseCreateRequest( InteractionResponseCreateRequest( type, InteractionApplicationCommandCallbackData( content = _content, embeds = Optional.missingOnEmpty(embeds.map { it.toRequest() }), allowedMentions = _allowedMentions.map { it.build() }, tts = _tts, components = Optional.missingOnEmpty(components.map { it.build() }) ).optional() ), files ) } } @KordPreview @KordDsl class PublicInteractionResponseModifyBuilder : BaseInteractionResponseModifyBuilder { private var _content: Optional<String?> = Optional.Missing() override var content: String? by ::_content.delegate() private var _embeds: Optional<MutableList<EmbedBuilder>> = Optional.Missing() override var embeds: MutableList<EmbedBuilder>? by ::_embeds.delegate() private var _allowedMentions: Optional<AllowedMentionsBuilder?> = Optional.Missing() override var allowedMentions: AllowedMentionsBuilder? by ::_allowedMentions.delegate() val files: MutableList<Pair<String, InputStream>> = mutableListOf() private var _components: Optional<MutableList<MessageComponentBuilder>> = Optional.Missing() override var components: MutableList<MessageComponentBuilder>? by ::_components.delegate() fun addFile(name: String, content: InputStream) { files += name to content } suspend fun addFile(path: Path) = withContext(Dispatchers.IO) { addFile(path.fileName.toString(), Files.newInputStream(path)) } override fun toRequest(): MultipartInteractionResponseModifyRequest { return MultipartInteractionResponseModifyRequest( InteractionResponseModifyRequest( content = _content, embeds = Optional(embeds).coerceToMissing().mapList { it.toRequest() }, allowedMentions = _allowedMentions.map { it.build() }, components = Optional(components).coerceToMissing().mapList { it.build() }, ), files ) } }
0
Kotlin
0
1
e3d97c249cd0c058c22a1b0a6cd1ddc729a3ea7c
4,121
kord
MIT License
TicketBookingService/src/main/kotlin/com/github/saboteur/ticketbookingsystem/ticketbookingservice/dto/UserInDto.kt
5aboteur
269,710,213
false
null
package com.github.saboteur.ticketbookingsystem.ticketbookingservice.dto import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty @ApiModel(value = "User") data class UserInDto( @ApiModelProperty(value = "login") val login: String, @ApiModelProperty(value = "email") val email: String, @ApiModelProperty(value = "category") val category: String ) { companion object { val empty = UserInDto( login = "", email = "", category = "" ) } }
0
Kotlin
0
0
a8ecf2160c3d33a15b4912ad4d8fb5eed677c107
553
ticket-booking-system
MIT License
app/src/main/java/org/koreader/launcher/utils/ScreenUtils.kt
jimman2003
366,837,844
true
{"Kotlin": 131381, "Lua": 112519, "C": 44705, "C++": 20547, "Makefile": 8230, "Shell": 4923}
package org.koreader.launcher.utils import android.app.Activity import android.graphics.PixelFormat import android.graphics.Point import android.graphics.Rect import android.os.Build import android.util.DisplayMetrics import android.view.WindowManager import org.koreader.launcher.Logger import java.util.Locale import java.util.concurrent.CountDownLatch @Suppress("DEPRECATION") object ScreenUtils { private const val TAG = "ScreenUtils" fun getScreenAvailableWidth(activity: Activity): Int { return getScreenSizeWithConstraints(activity).x } fun getScreenAvailableHeight(activity: Activity): Int { return getScreenSizeWithConstraints(activity).y } fun getScreenWidth(activity: Activity): Int { return getScreenSize(activity).x } fun getScreenHeight(activity: Activity): Int { return getScreenSize(activity).y } // DEPRECATED: returns 0 on API16+ fun getStatusBarHeight(activity: Activity): Int { val rectangle = Rect() val window = activity.window window.decorView.getWindowVisibleDisplayFrame(rectangle) return rectangle.top } fun isFullscreenDeprecated(activity: Activity): Boolean { return (activity.window.attributes.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN != 0) } fun setFullscreenDeprecated(activity: Activity, fullscreen: Boolean) { val cd = CountDownLatch(1) activity.runOnUiThread { try { val window = activity.window if (fullscreen) { window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } } catch (e: Exception) { Logger.w(TAG, e.toString()) } cd.countDown() } try { cd.await() } catch (ex: InterruptedException) { Logger.e(TAG, ex.toString()) } } fun pixelFormatName(format: Int): String { return when(format) { PixelFormat.OPAQUE -> "OPAQUE" PixelFormat.RGBA_1010102 -> "RGBA_1010102" PixelFormat.RGBA_8888 -> "RGBA_8888" PixelFormat.RGBA_F16 -> "RGBA_F16" PixelFormat.RGBX_8888 -> "RGBX_8888" PixelFormat.RGB_888 -> "RGB_888" PixelFormat.RGB_565 -> "RGB_565" PixelFormat.TRANSLUCENT -> "TRANSLUCENT" PixelFormat.TRANSPARENT -> "TRANSPARENT" else -> String.format(Locale.US, "Unknown: %d", format) } } private fun getScreenSize(activity: Activity): Point { val size = Point() val display = activity.windowManager.defaultDisplay if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { val metrics = DisplayMetrics() display.getRealMetrics(metrics) size.set(metrics.widthPixels, metrics.heightPixels) } else { display.getSize(size) } return size } private fun getScreenSizeWithConstraints(activity: Activity): Point { val size = Point() val display = activity.windowManager.defaultDisplay val metrics = DisplayMetrics() display.getMetrics(metrics) size.set(metrics.widthPixels, metrics.heightPixels) return size } }
0
Kotlin
0
0
ae2b003a1bc39042fbfefc87f22b28043d36b051
3,436
android-luajit-launcher
MIT License
sources/app/src/main/java/com/mikyegresl/valostat/features/agent/AgentsRouter.kt
sergey-lvovich-kim
629,918,357
false
null
package com.mikyegresl.valostat.features.agent import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import com.mikyegresl.valostat.navigation.GlobalNavItem import com.mikyegresl.valostat.navigation.NavigationItem import kotlinx.coroutines.flow.StateFlow fun agentsRouter( state: StateFlow<AgentsScreenState>, navController: NavController, builder: NavGraphBuilder ) { with(builder) { composable(GlobalNavItem.Agents.route) { AgentsScreen(state) { navController.navigate("${NavigationItem.AgentDetails.route}/$it") { navController.graph.startDestinationRoute?.let { screenRoute -> popUpTo(screenRoute) } launchSingleTop = true restoreState = true } } } } }
0
Kotlin
1
8
43d703892b9b21824508ab11762f3ad6b04b511b
931
ValoStat
Apache License 2.0
stream-chat-android-ui-components/src/main/kotlin/io/getstream/chat/android/ui/feature/gallery/AttachmentGalleryItem.kt
GetStream
177,873,527
false
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
/* * Copyright (c) 2014-2022 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-chat-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.chat.android.ui.feature.gallery import io.getstream.chat.android.models.Attachment import io.getstream.chat.android.models.User import java.util.Date public data class AttachmentGalleryItem( val attachment: Attachment, val user: User, val createdAt: Date, val messageId: String, val cid: String, val isMine: Boolean, )
24
Kotlin
273
1,451
8e46f46a68810d8086c48a88f0fff29faa2629eb
989
stream-chat-android
FSF All Permissive License
app/src/main/java/com/anibalbastias/android/marvelapp/ui/series/adapter/SeriesListAdapter.kt
anibalbastiass
173,621,278
false
null
package com.anibalbastias.android.marvelapp.ui.series.adapter import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.anibalbastias.android.marvelapp.base.api.data.dataStoreFactory.series.model.SeriesItemData import com.anibalbastias.android.marvelapp.databinding.ViewItemSeriesBinding import com.anibalbastias.android.marvelapp.ui.series.adapter.viewholder.SeriesListItemViewHolder class SeriesListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var items: MutableList<SeriesItemData>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val binding = ViewItemSeriesBinding .inflate(LayoutInflater.from(parent.context), parent, false) return SeriesListItemViewHolder(binding) } override fun getItemCount(): Int = items?.size ?: 0 override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val holderItem = holder as? SeriesListItemViewHolder holderItem?.bind(items, position) } }
0
Kotlin
1
5
6dc4765788e5a83aa4337034a5cca97d703e5a75
1,105
AAD-Prepare-Exam
MIT License
applications/ssikit/volumes/src/main/kotlin/id/walt/services/did/composers/models/DocumentComposerParameter.kt
PabloMarrtinez
798,128,699
false
{"Kotlin": 1345647, "JavaScript": 27705, "CSS": 18679, "Java": 9175, "HTML": 7117, "Open Policy Agent": 3145, "Smarty": 3032, "Mustache": 1386, "Shell": 1306}
package id.walt.services.did.composers.models import com.nimbusds.jose.jwk.JWK import id.walt.crypto.Key import id.walt.model.DidUrl open class DocumentComposerBaseParameter( open val didUrl: DidUrl ) open class DocumentComposerJwkParameter( override val didUrl: DidUrl, open val jwk: JWK, ) : DocumentComposerBaseParameter(didUrl) open class DocumentComposerKeyJwkParameter( override val didUrl: DidUrl, override val jwk: JWK, open val key: Key ) : DocumentComposerJwkParameter(didUrl, jwk) open class DocumentComposerBaseFabric( override val didUrl: DidUrl, open val publicKey58: String, open val id: String ): DocumentComposerBaseParameter(didUrl)
0
Kotlin
0
0
8ae775ad185695232aee064465212e278b4cbc41
692
conector
MIT License
feature/books/src/main/kotlin/dev/yacsa/books/screen/list/content/ContentFetched.kt
andrew-malitchuk
589,720,124
false
null
package dev.yacsa.books.screen.list.content import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material.pullrefresh.rememberPullRefreshState import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.paging.LoadState import androidx.paging.PagingData import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import com.google.accompanist.systemuicontroller.rememberSystemUiController import dev.yacsa.books.screen.composable.ListToolbar import dev.yacsa.books.screen.list.content.fetched.ContentFetchedGrid import dev.yacsa.books.screen.list.content.fetched.ContentFetchedList import dev.yacsa.model.model.BookUiModel import dev.yacsa.ui.composable.fab.ScrollUpFab import dev.yacsa.ui.theme.YacsaTheme import io.github.serpro69.kfaker.Faker import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.launch @OptIn(ExperimentalMaterialApi::class, ExperimentalFoundationApi::class) @Composable fun ContentFetched( onBookClicked: (Int) -> Unit, lazyPagingItems: LazyPagingItems<BookUiModel>, onSearch: () -> Unit, onSettings: () -> Unit, onFavourite: () -> Unit, ) { val listState = rememberLazyListState() val gridState = rememberLazyGridState() val isGridSelected = remember { mutableStateOf(false) } val pullRefreshState = rememberPullRefreshState( refreshing = lazyPagingItems.loadState.refresh is LoadState.Loading, onRefresh = { lazyPagingItems.refresh() }, ) val coroutineScope = rememberCoroutineScope() val systemUiController = rememberSystemUiController() with(systemUiController) { setSystemBarsColor( color = dev.yacsa.ui.theme.YacsaTheme.colors.background, ) setNavigationBarColor( color = dev.yacsa.ui.theme.YacsaTheme.colors.surface, ) } Column { ListToolbar( state = listState, searchClick = onSearch, settingsClick = onSettings, favouriteClick = onFavourite, ) Box( modifier = Modifier .background(YacsaTheme.colors.background) .pullRefresh(pullRefreshState), ) { if (isGridSelected.value) { ContentFetchedGrid( lazyPagingItems = lazyPagingItems, onBookClicked = onBookClicked, listState = gridState, ) } else { ContentFetchedList( lazyPagingItems = lazyPagingItems, onBookClicked = onBookClicked, listState = listState, ) } ScrollUpFab( modifier = Modifier .align(Alignment.BottomEnd) .padding(YacsaTheme.spacing.medium), isVisibleBecauseOfScrolling = if (isGridSelected.value) { !gridState.isScrollInProgress && gridState.canScrollBackward } else { !listState.isScrollInProgress && listState.canScrollBackward }, ) { coroutineScope.launch { if (isGridSelected.value) { gridState.animateScrollToItem(0) } else { listState.animateScrollToItem(0) } } } PullRefreshIndicator( lazyPagingItems.loadState.refresh is LoadState.Loading, pullRefreshState, Modifier.align(Alignment.TopCenter), ) } } } @Preview(showBackground = true) @Composable fun Preview_ContentFetched_Light() { val faker = Faker() YacsaTheme(false) { ContentFetched( onBookClicked = {}, lazyPagingItems = flowOf(PagingData.empty<BookUiModel>()).collectAsLazyPagingItems(), onSearch = {}, onSettings = {}, onFavourite = {}, ) } } @Preview(showBackground = true) @Composable fun Preview_ContentFetched_Dark() { val faker = Faker() YacsaTheme(true) { ContentFetched( onBookClicked = {}, lazyPagingItems = flowOf(PagingData.empty<BookUiModel>()).collectAsLazyPagingItems(), onSearch = {}, onSettings = {}, onFavourite = {}, ) } }
0
Kotlin
0
0
e35620cf1c66b4f76f0ed30d9c6d499acd134403
5,258
yet-another-compose-showcase-app
MIT License
app/src/main/java/com/worker8/autoadapter/rows/FooterRow.kt
worker8
290,935,958
false
null
package com.worker8.autoadapter.rows import android.view.View import android.widget.TextView import com.worker8.auto.adapter.library.AutoData import com.worker8.auto.adapter.library.ListItem import com.worker8.autoadapter.R class FooterRow(override val data: Data) : ListItem<FooterRow.Data>() { override val layoutResId = R.layout.footer_row override fun bind(itemView: View, position: Int) { itemView.findViewById<TextView>(R.id.footerText).text = data.privacyMessage } data class Data(override val id: Long, val privacyMessage: String) : AutoData { override fun isContentSame(other: AutoData): Boolean { return this == other } } }
1
null
2
10
21b07266662942d28fac2e4de17d6fbe9768a66e
696
AutoAdapter
The Unlicense
app/src/main/java/com/gabrielfv/biller/nav/BillerRoutes.kt
gfreivasc
286,602,068
false
null
/* * Copyright 2020 Gabriel Freitas Vasconcelos * * 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.gabrielfv.biller.nav import com.gabrielfv.biller.R import com.gabrielfv.core.nav.Routes class BillerRoutes : Routes { override val addBill: Int get() = R.id.action_home_to_addBill }
0
Kotlin
0
1
00faf2da270e51d85e4a836cc314aac01bfbe6e4
817
biller-fragment
Apache License 2.0
compose/ui-layout-custom/src/commonMain/kotlin/com/bselzer/ktx/compose/ui/layout/image/async/AsyncImageResult.kt
Woody230
388,189,330
false
{"Kotlin": 3122765}
package com.bselzer.ktx.compose.ui.layout.image.async import androidx.compose.ui.graphics.painter.Painter sealed interface AsyncImageResult { object Loading : AsyncImageResult object Failed : AsyncImageResult data class Success(val painter: Painter) : AsyncImageResult }
2
Kotlin
0
7
5ad55d66bbb58a12bf3a8b436ea1ea4d8e9737bc
284
KotlinExtensions
Apache License 2.0
thirdparty/controlsfx-layouts/src/ktfx/controlsfx/layouts/_NotificationPane.kt
hendraanggrian
102,934,147
false
null
@file:JvmMultifileClass @file:JvmName("ControlsFxLayoutsKt") @file:OptIn(ExperimentalContracts::class) package ktfx.controlsfx.layouts import ktfx.layouts.KtfxLayoutDslMarker import ktfx.layouts.NodeManager import org.controlsfx.control.NotificationPane import kotlin.String import kotlin.Unit import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind.EXACTLY_ONCE import kotlin.contracts.contract import kotlin.jvm.JvmMultifileClass import kotlin.jvm.JvmName /** * Add a [NotificationPane] to this manager. * * @return the control added. */ public fun NodeManager.notificationPane(): NotificationPane = notificationPane() { } /** * Create a [NotificationPane] with configuration block. * * @param configuration the configuration block. * @return the control created. */ public inline fun notificationPane( configuration: (@KtfxLayoutDslMarker KtfxNotificationPane).() -> Unit ): NotificationPane { contract { callsInPlace(configuration, EXACTLY_ONCE) } val child = KtfxNotificationPane() child.configuration() return child } /** * Add a [NotificationPane] with configuration block to this manager. * * @param configuration the configuration block. * @return the control added. */ public inline fun NodeManager.notificationPane( configuration: ( @KtfxLayoutDslMarker KtfxNotificationPane ).() -> Unit ): NotificationPane { contract { callsInPlace(configuration, EXACTLY_ONCE) } val child = KtfxNotificationPane() child.configuration() return addChild(child) } /** * Create a styled [NotificationPane]. * * @param styleClass the CSS style class. * @param id the CSS id. * @return the styled control created. */ public fun styledNotificationPane(vararg styleClass: String, id: String? = null): NotificationPane = styledNotificationPane(styleClass = *styleClass, id = id) { } /** * Add a styled [NotificationPane] to this manager. * * @param styleClass the CSS style class. * @param id the CSS id. * @return the styled control added. */ public fun NodeManager.styledNotificationPane(vararg styleClass: String, id: String? = null): NotificationPane = styledNotificationPane(styleClass = *styleClass, id = id) { } /** * Create a styled [NotificationPane] with configuration block. * * @param styleClass the CSS style class. * @param id the CSS id. * @param configuration the configuration block. * @return the styled control created. */ public inline fun styledNotificationPane( vararg styleClass: String, id: String? = null, configuration: (@KtfxLayoutDslMarker KtfxNotificationPane).() -> Unit ): NotificationPane { contract { callsInPlace(configuration, EXACTLY_ONCE) } val child = KtfxNotificationPane() child.styleClass += styleClass child.id = id child.configuration() return child } /** * Add a styled [NotificationPane] with configuration block to this manager. * * @param styleClass the CSS style class. * @param id the CSS id. * @param configuration the configuration block. * @return the styled control added. */ public inline fun NodeManager.styledNotificationPane( vararg styleClass: String, id: String? = null, configuration: (@KtfxLayoutDslMarker KtfxNotificationPane).() -> Unit ): NotificationPane { contract { callsInPlace(configuration, EXACTLY_ONCE) } val child = KtfxNotificationPane() child.styleClass += styleClass child.id = id child.configuration() return addChild(child) }
1
Kotlin
2
15
ea4243fb75edb70d6710e7488fa08834084f6169
3,514
ktfx
Apache License 2.0
core/src/main/kotlin/me/kcra/takenaka/core/mapping/adapter/LegacySpigotMappingPrepender.kt
zlataovce
596,960,001
false
{"Kotlin": 581893, "Java": 88132, "CSS": 12009, "JavaScript": 8198}
/* * This file is part of takenaka, licensed under the Apache License, Version 2.0 (the "License"). * * Copyright (c) 2023 <NAME> * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.kcra.takenaka.core.mapping.adapter import me.kcra.takenaka.core.mapping.MappingContributor import me.kcra.takenaka.core.mapping.WrappingContributor import me.kcra.takenaka.core.mapping.toInternalName import net.fabricmc.mappingio.MappedElementKind import net.fabricmc.mappingio.MappingVisitor import net.fabricmc.mappingio.adapter.ForwardingMappingVisitor import net.fabricmc.mappingio.tree.MappingTreeView import org.objectweb.asm.commons.Remapper /** * A mapping visitor that prepends an implicit `net.minecraft.server.VVV` package prefix, if needed. * * Spigot mappings have had an implicit `net.minecraft.server.VVV` package, `VVV` being the CraftBukkit NMS version (e.g. 1_19_R2, you can get this from the CraftBukkit POM), until 1.17. * In one of the last 1.16.5 BuildData commits, packages were added to the mappings, even though they are not present in the distributed reobfuscated JARs. * To solve this, you can apply [LegacySpigotMappingPrepender] instances to both a [me.kcra.takenaka.core.mapping.resolve.impl.SpigotClassMappingResolver] and a [me.kcra.takenaka.core.mapping.resolve.impl.SpigotMemberMappingResolver], * using a linked prepender for the member resolver ([createLinked] or [Link]). * * @param next the visitor to delegate to * @property namespace the namespace, whose mappings are to be modified (most likely `spigot` or to be exact, [me.kcra.takenaka.core.mapping.resolve.impl.AbstractSpigotMappingResolver.targetNamespace]) * @property prependEverything whether every class should have its package replaced (useful for fixing 1.16.5), defaults to false * @property prependedClasses the classes that have been prepended and should be remapped in descriptors (only class names that are a package-replace candidate should be specified here, any class name without a package will have a prefix prepended implicitly) * @author <NAME> */ class LegacySpigotMappingPrepender private constructor( next: MappingVisitor, val namespace: String, val prependEverything: Boolean, private val prependedClasses: MutableSet<String> ) : ForwardingMappingVisitor(next) { /** * The remapper. */ private val remapper = PrependingRemapper(prependedClasses, prependEverything) /** * The [namespace]'s ID. */ private var namespaceId = MappingTreeView.NULL_NAMESPACE_ID /** * Constructs a new [LegacySpigotMappingPrepender]. * * @param next the visitor to delegate to * @param namespace the namespace, whose mappings are to be modified * @param prependEverything whether every class should have its package replaced, defaults to false */ constructor(next: MappingVisitor, namespace: String = "spigot", prependEverything: Boolean = false) : this(next, namespace, prependEverything, mutableSetOf()) /** * Creates a new linked prepender. * * @param next the visitor to delegate to, uses the same one by default * @param prependEverything whether every class should have its package replaced, defaults to false * @return the linked prepender */ fun createLinked(next: MappingVisitor = this.next, prependEverything: Boolean = false): LegacySpigotMappingPrepender { return LegacySpigotMappingPrepender(next, this.namespace, prependEverything, this.prependedClasses) } override fun visitNamespaces(srcNamespace: String, dstNamespaces: MutableList<String>) { val nsId = dstNamespaces.indexOf(this.namespace) if (nsId != -1) { this.namespaceId = nsId } super.visitNamespaces(srcNamespace, dstNamespaces) } override fun visitDstName(targetKind: MappedElementKind, namespace: Int, name: String?) { var name0 = name if (name0 != null && targetKind == MappedElementKind.CLASS && this.namespaceId == namespace) { name0 = remapper.map(name0.toInternalName()) } super.visitDstName(targetKind, namespace, name0) } override fun visitDstDesc(targetKind: MappedElementKind, namespace: Int, desc: String?) { var desc0 = desc if (desc0 != null && this.namespaceId == namespace) { desc0 = remapper.mapDesc(desc0) } super.visitDstDesc(targetKind, namespace, desc0) } /** * A [Remapper] that prepends class names with `net.minecraft.server.VVV`. * * @param prependedClasses the classes that have been prepended and should be remapped in descriptors (only class names that are a package-replace candidate should be specified here, any class name without a package will have a prefix prepended implicitly) * @param prependEverything whether every class should have its package replaced (useful for fixing 1.16.5) */ class PrependingRemapper(val prependedClasses: MutableSet<String>, val prependEverything: Boolean) : Remapper() { override fun map(internalName: String): String { val isPrependable = '/' !in internalName if (isPrependable) { prependedClasses += internalName } if (prependEverything || (isPrependable || internalName in prependedClasses)) { return "net/minecraft/server/VVV/${internalName.substringAfterLast('/')}" } return internalName } } /** * A utility class for linking prependers together in the case of multiple resolvers. */ class Link { /** * Currently prepended classes - the linking point. */ private val prependedClasses = mutableSetOf<String>() /** * Creates a new linked prepender. * * @param next the visitor to delegate to, uses the same one by default * @param namespace the namespace, whose mappings are to be modified; defaults to `spigot` * @param prependEverything whether every class should have its package replaced, defaults to false * @return the linked prepender */ fun createLinked(next: MappingVisitor, namespace: String = "spigot", prependEverything: Boolean = false): LegacySpigotMappingPrepender { return LegacySpigotMappingPrepender(next, namespace, prependEverything, this.prependedClasses) } /** * Creates a new prepending contributor with a linked prepender. * * @param contributor the mapping contributor to wrap * @param prependEverything whether every class should have its package replaced, defaults to false * @return the prepending contributor */ fun createPrependingContributor(contributor: MappingContributor, prependEverything: Boolean = false): MappingContributor { return WrappingContributor(contributor) { createLinked(it, contributor.targetNamespace, prependEverything) } } } }
4
Kotlin
2
24
281c7bd61dcfd593bc35113f8b8b2e9bf62a61ae
7,523
takenaka
Apache License 2.0
app/src/main/java/com/lindevhard/felia/ui/create_wallet/CreateWalletUi.kt
LinDevHard
467,245,166
false
null
package com.lindevhard.felia.ui.create_wallet import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.arkivanov.decompose.extensions.compose.jetbrains.subscribeAsState import com.google.accompanist.flowlayout.FlowMainAxisAlignment import com.google.accompanist.flowlayout.FlowRow import com.google.accompanist.insets.navigationBarsPadding import com.lindevhard.felia.R import com.lindevhard.felia.component.create_wallet.CreateWallet import com.lindevhard.felia.ui.components.appbar.AppBarScaffold import com.lindevhard.felia.ui.components.button.DialogFlushButton import com.lindevhard.felia.ui.components.button.PrimaryButton import com.lindevhard.felia.ui.components.dialog.FeliaAlertDialog import com.lindevhard.felia.ui.create_wallet.component.WordChip import com.lindevhard.felia.ui.theme.mainText import com.lindevhard.felia.utils.copyText import com.lindevhard.felia.utils.toast import com.lindevhard.felia.ui.R as CommonUI @Composable fun CreateWalletUi(component: CreateWallet) { val state by component.models.subscribeAsState() val context = LocalContext.current val copiedText = stringResource(id = R.string.msg_copied) Column() { if (state.isCreated) { FeliaAlertDialog( title = stringResource(id = R.string.msg_create_wallet_created), onDismissRequest = { component.onCompleteCreated() }, image = painterResource(id = CommonUI.drawable.ic_rocket_launch), buttonsContent = { PrimaryButton( text = stringResource(id = R.string.msg_ok), onClick = { component.onCompleteCreated() }, modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) ) } ) } AppBarScaffold( title = stringResource(id = R.string.msg_create_wallet), onBackPress = { component.onBackPressed() }, modifier = Modifier.weight(1f) ) { Text( text = stringResource(id = R.string.msg_user_create_wallet), style = MaterialTheme.typography.h4, textAlign = TextAlign.Center, color = MaterialTheme.colors.mainText, modifier = Modifier .fillMaxWidth() .padding(horizontal = 32.dp, vertical = 24.dp) ) FlowRow( mainAxisAlignment = FlowMainAxisAlignment.Center, mainAxisSpacing = 6.dp, crossAxisSpacing = 5.dp, modifier = Modifier .sizeIn(minHeight = 150.dp) .padding(horizontal = 16.dp, vertical = 16.dp) .fillMaxWidth() .background(MaterialTheme.colors.surface, MaterialTheme.shapes.medium) .padding(horizontal = 14.dp, vertical = 8.dp) ) { state.wordList.forEach { WordChip(title = it) } } DialogFlushButton( text = stringResource(id = R.string.msg_copy_seed), onClick = { context.copyText(state.seedPhrase) context.toast(copiedText) }, icon = painterResource(id = CommonUI.drawable.ic_copy), modifier = Modifier .padding(horizontal = 16.dp, vertical = 16.dp) ) } PrimaryButton( text = stringResource(id = R.string.msg_create_wallet), onClick = { component.onCreateWalletClicked() }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 8.dp) .navigationBarsPadding() ) } }
0
Kotlin
1
0
19871d912c4548b6cf643a1405988d8030e9ab9d
4,541
FeliaWallet
Apache License 2.0
app/src/main/java/com/example/noteit/Models/Note.kt
Catnatsuki
618,691,669
false
null
package com.example.noteit.Models import android.icu.text.CaseMap.Title import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "notes_table") data class Note( @PrimaryKey(autoGenerate = true) val id: Int?, @ColumnInfo(name= "title") val title: String?, @ColumnInfo(name= "note") val note: String, @ColumnInfo(name= "date") val date: String?, ) : java.io.Serializable
0
Kotlin
0
3
9dc00e26849cfb04c5dea19d631fd77216747a19
443
Note-It
MIT License
app/src/main/java/com/github/jayteealao/pastelmusic/app/di/dispatchers/DispatchersModule.kt
jayteealao
530,847,226
false
{"Kotlin": 194323}
/* * Copyright 2022 Maximillian Leonov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jayteealao.pastelmusic.app.di.dispatchers import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers @Module @InstallIn(SingletonComponent::class) object DispatchersModule { @Provides @Dispatcher(PastelDispatchers.DEFAULT) fun provideDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default @Provides @Dispatcher(PastelDispatchers.MAIN) fun provideMainDispatcher(): CoroutineDispatcher = Dispatchers.Main @Provides @Dispatcher(PastelDispatchers.UNCONFINED) fun provideUnconfinedDispatcher(): CoroutineDispatcher = Dispatchers.Unconfined @Provides @Dispatcher(PastelDispatchers.IO) fun provideIODispatcher(): CoroutineDispatcher = Dispatchers.IO }
0
Kotlin
0
0
34294059654b8fdbc194fe4df419f5118a523070
1,475
PastelMusic
MIT License
educational-core/src/com/jetbrains/edu/learning/serialization/converter/xml/To15VersionXmlConverter.kt
alexshcer
354,356,509
true
{"Kotlin": 3261790, "HTML": 573177, "Java": 552027, "CSS": 12158, "Python": 5553, "JavaScript": 315}
package com.jetbrains.edu.learning.serialization.converter.xml import com.jetbrains.edu.learning.EduNames import com.jetbrains.edu.learning.serialization.SerializationUtils import com.jetbrains.edu.learning.serialization.SerializationUtils.Xml.* import org.jdom.Element class To15VersionXmlConverter : BaseXmlConverter() { override fun convertCourseElement(course: Element) { val language = getChildWithName(course, LANGUAGE) if (language.getAttributeValue(VALUE) == EduNames.SCALA) { val environment = getChildWithName(course, SerializationUtils.ENVIRONMENT) if (environment.getAttributeValue(VALUE).isEmpty()) { environment.setAttribute(VALUE, "Gradle") } } } override fun convertTaskElement(task: Element) { if (task.name != "ChoiceTask") { return } val oldOptionsElement = getChildList(task, "choiceVariants") println() val newOptionElements = oldOptionsElement.map { val newElement = Element("ChoiceOption") addChildWithName(newElement, "text", it.getAttributeValue(VALUE)) newElement } addChildList(task, "choiceOptions", newOptionElements) } }
0
null
0
0
687e434cb8499476729c055d1e947a31491bb999
1,151
educational-plugin
Apache License 2.0
src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt
excelsior-esy
190,620,763
false
{"Gradle Kotlin DSL": 2, "INI": 5, "Shell": 3, "Text": 3, "Ignore List": 1, "Batchfile": 1, "AsciiDoc": 1, "YAML": 4, "JSON": 77, "Python": 28, "Java Properties": 4, "XML": 30, "Unity3D Asset": 7, "Kotlin": 184, "Velocity Template Language": 10, "Jinja": 1, "Java": 16, "Dockerfile": 1, "Groovy": 4}
/* * Copyright © 2017-2018 AT&T Intellectual Property. * * 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.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.ModifyAction import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfDatastore interface NetconfRpcService { /** * Lock * * @param configTarget running or candidate, default candidate * @return Device response */ fun lock(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse /** * Get-config * * @param filter filter content, default empty * @param configTarget running or candidate, default running * @return Device response */ fun getConfig(filter: String = "", configTarget: String = NetconfDatastore.RUNNING.datastore): DeviceResponse /** * Delete config * * @param configTarget running or candidate, default candidate * @return Device response */ fun deleteConfig(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse /** * Edit-config * * @param messageContent edit config content. * @param configTarget running or candidate, default candidate * @param editDefaultOperation, default set to none. Valid values: merge, replace, create, delete, none * @return Device response */ fun editConfig(messageContent: String, configTarget: String = NetconfDatastore.CANDIDATE.datastore, editDefaultOperation: String = ModifyAction.NONE.action): DeviceResponse /** * Invoke custom RPC as provided as input. * * Some use cases might required one to directly invoke a device * specific RPC. The RPC must be correctly formatted. * * Ex: in order to rollback last submitted configuration * for JUNOS devices, such RPC can be use: * <code> * &lt;rpc> * &lt;load-configuration rollback="1"/> * &lt;/rpc> * </code> * * @param rpc the rpc content. */ fun invokeRpc(rpc: String): DeviceResponse /** * Validate * * @param configTarget running or candidate, default candidate * @return Device response */ fun validate(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse /** * Commit * * @param confirmed Perform a confirmed <commit> operation. If flag set to true, * then it is expected to have a follow-up <commit> operation to confirm the request * @param confirmTimeout Timeout period for confirmed commit, in seconds. * @param persist Make the confirmed commit survive a session termination, and * set a token on the ongoing confirmed commit. * @param persistId Used to issue a follow-up confirmed commit or a confirming * commit from any session, with the token from the previous <commit> operation. * If unspecified, the confirm timeout defaults to 600 seconds. * @return Device response */ fun commit(confirmed: Boolean = false, confirmTimeout: Int = 60, persist: String = "", persistId: String = ""): DeviceResponse /** * Cancels an ongoing confirmed commit. If the <persist-id> parameter is not given, * the <cancel-commit> operation MUST be issued on the same session that issued * the confirmed commit. * * @param persistId Cancels a persistent confirmed commit. The value MUST be equal * to the value given in the <persist> parameter to the <commit> operation. * If the value does not match, the operation fails with an "invalid-value" error. */ fun cancelCommit(persistId: String = ""): DeviceResponse /** * Unlock * * @param configTarget running or candidate, default candidate * @return Device response */ fun unLock(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse /** * Discard config * * @return Device response */ fun discardConfig(): DeviceResponse /** * Close session * * @param force force closeSession * @return Device response */ fun closeSession(force: Boolean): DeviceResponse /** * Executes an RPC request to the netconf server. * * @param request the XML containing the RPC request for the server. * @return Device response */ fun asyncRpc(request: String, messageId: String): DeviceResponse }
1
null
1
1
8e5d445d627fb36106468fed1d8d21988f59f976
5,072
blueprintsprocessor
Apache License 2.0
app/src/main/java/android/example/health/fragments/medicineBox/MedicineBoxMainFragment.kt
HarshRaghav
543,518,159
false
{"Java": 155422, "Kotlin": 146387}
package android.example.health.fragments.medicineBox import android.example.health.R import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.example.health.utils.UtilsFragmentTransaction import androidx.annotation.Nullable import com.google.android.material.bottomnavigation.BottomNavigationView class MedicineBoxMainFragment : Fragment() { var rootView: View? = null var bottomNavigationView: BottomNavigationView? = null override fun onViewCreated(view: View, @Nullable savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) rootView = view bottomNavigationView = rootView!!.findViewById<View>(R.id.bottom_navigation) as BottomNavigationView UtilsFragmentTransaction.addFragmentTransaction( R.id.course_frame_layout, activity, MedicineDonationFragment(), MedicineDonationFragment::class.java.getSimpleName(), null ) bottomNavigationView!!.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.MedicineBox -> { UtilsFragmentTransaction.addFragmentTransaction( R.id.course_frame_layout, activity, MedicineDonationFragment(), MedicineDonationFragment::class.java.getSimpleName(), null ) return@OnNavigationItemSelectedListener true } R.id.MyMedicine -> { UtilsFragmentTransaction.addFragmentTransaction( R.id.course_frame_layout, activity, MyMedicinesFragment(), MyMedicinesFragment::class.java.getSimpleName(), null ) return@OnNavigationItemSelectedListener true } } false }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(android.example.health.R.layout.fragment_medicine_box, container, false) } }
1
null
1
1
8765c88b2d33ed7af77bb854dd59a7dc4ec0bddc
2,325
digicure
Apache License 2.0
app/src/main/java/com/poligran/medicalendar/ui/historial/HistorialFragment.kt
Ncamacho2
782,289,908
false
{"Kotlin": 25886}
package com.poligran.medicalendar.ui.historial import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListView import com.poligran.medicalendar.R // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val fecha= "<b><br>Fecha: </b>" private const val hora = "<b><br>Hora: </b>" private const val motivo = "<b><br>Motivo: </b>" private const val estado = "<b><br>Estado: </b>" private const val medico = "<b><br>Medico: </b>" private const val sede = "<b><br>Sede: </b>" /** * A simple [Fragment] subclass. * Use the [HistorialFragment.newInstance] factory method to * create an instance of this fragment. */ class HistorialFragment : Fragment() { private lateinit var listViewInformationH: ListView override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_historial, container, false) val listaHistorialC = listOf( InformacionItem("$fecha 12/04/2024", "$hora 10:00 AM", "$motivo Consulta", "$estado Pendiente", "$medico Dr. García", "$sede Sede Chapinero"), InformacionItem("$fecha 13/04/2024", "$hora 11:30 AM", "$motivo Examen", "$estado Realizado", "$medico Dra. Rodríguez", "$sede Sede Usaquén"), InformacionItem("$fecha 14/04/2024", "$hora 09:00 AM", "$motivo Control", "$estado Pendiente", "$medico Dr. Gómez", "$sede Sede Fontibón"), InformacionItem("$fecha 15/04/2024", "$hora 08:00 AM", "$motivo Consulta", "$estado Pendiente", "$medico Dr. Martínez", "$sede Sede Kennedy"), InformacionItem("$fecha 16/04/2024", "$hora 02:30 PM", "$motivo Examen", "$estado Realizado", "$medico Dra. Pérez", "$sede Sede Bosa"), InformacionItem("$fecha 17/04/2024", "$hora 03:45 PM", "$motivo Control", "$estado Pendiente", "$medico Dr. Sánchez", "$sede Sede Engativá"), InformacionItem("$fecha 18/04/2024", "$hora 11:15 AM", "$motivo Consulta", "$estado Pendiente", "$medico Dr. López", "$sede Sede Suba"), InformacionItem("$fecha 19/04/2024", "$hora 04:20 PM", "$motivo Examen", "$estado Realizado", "$medico Dra. González", "$sede Sede Teusaquillo"), InformacionItem("$fecha 20/04/2024", "$hora 01:00 PM", "$motivo Control", "$estado Pendiente", "$medico Dr. Ramírez", "$sede Sede Barrios Unidos") ) listViewInformationH = view.findViewById(R.id.listViewInformation) val adapter = InformationAdapter(requireContext(), listaHistorialC) listViewInformationH.adapter = adapter return view } }
0
Kotlin
0
0
11c215e0f43ccb1b340211e8cd7707178590622d
2,780
MediCalendar
MIT License
src/main/kotlin/io/github/dockyardmc/extentions/ExtendedDouble.kt
DockyardMC
650,731,309
false
{"Kotlin": 617736, "Java": 112198}
package io.github.dockyardmc.extentions fun Double.truncate(decimals: Int): String = String.format("%.${decimals}f", this) fun Float.truncate(decimals: Int): String = String.format("%.${decimals}f", this)
3
Kotlin
2
37
2829daa23ed5d10eb400ad5b3bef082b010f5de6
205
Dockyard
MIT License
CodeForces-Solution/1157D.kt
Tech-Intellegent
451,030,607
false
{"C++": 4709610, "Kotlin": 334907, "Go": 2237, "C": 1524, "Python": 639}
/** * Description: Kotlin tips for dummies * Source: * https://codeforces.com/blog/entry/71089 * Kotlin Reference * https://kotlinlang.org/docs/tutorials/competitive-programming.html */ /// episode 1: https://codeforces.com/contest/1170 /// episode 2: https://codeforces.com/contest/1211 /// episode 3: https://codeforces.com/contest/1297 import java.io.* import java.util.* // @JvmField val INPUT = File("input.txt").inputStream() // @JvmField val OUTPUT = File("output.txt").outputStream() /// https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-field/ class Kattio: PrintWriter { @JvmField val r: BufferedReader @JvmField var st = StringTokenizer("") constructor(): this(System.`in`,System.out) {} constructor(i: InputStream, o: OutputStream): super(o,false) { r = i.bufferedReader() } fun rLine(): String? = r.readLine() fun read(): String { // if no input left returns empty string while (st.hasMoreTokens().not()) st = StringTokenizer(rLine() ?: return "", " ") return st.nextToken() } fun strs(n: Int) = List(n){read()} fun ln() = rLine()!! fun lns(n: Int) = List(n){ln()} fun int() = read().toInt() fun ints(n: Int) = List(n){int()} fun db() = read().toDouble() fun rDbs(n: Int) = List(n){db()} fun long() = read().toLong() fun longs(n: Int) = List(n){long()} } val io = Kattio() const val MOD = 1000000007 const val INF = (1e18).toLong() const val SZ = 1 shl 17 fun YN(b: Boolean) : String { return if (b) "YES" else "NO" } fun add(a: Int, b: Int) = (a+b) % MOD // from tourist :o fun sub(a: Int, b: Int) = (a-b+MOD) % MOD fun mul(a: Int, b: Int) = ((a.toLong()*b)%MOD).toInt() fun gcd(a: Int, b: Int) : Int = if (b == 0) a else gcd(b,a%b) fun example() { println(String.format("%.8f", 5.25)) // print to 8 decimals val arr2D = Array<IntArray>(5,{IntArray(5,{5})}) var (x,y) = arrayOf(3,2) // or rInts(2) when (x) { // switch, can be used as expression 0,1 -> println("x <= 1") 2 -> println("x == 2") // Note the block else -> { println("x is neither 1 nor 2") } } x = y.also { y = x } // swap x and y println("${maxOf(x+2,y)}") // (x,y)=(4,3) -> 4 val h = HashMap<String,Int>() val s = "ababa" for (i in 0..s.length-2) { val w = s.substring(i,i+2) val c = h.getOrElse(w,{0}) h[w] = c+1 } for ((a,b) in h) println("${a} ${b}") // key,value val pq = PriorityQueue<Pair<Long,Int>>(){x,y -> x.first.compareTo(y.first)} // or compareBy{it.first} val A = arrayListOf(Pair(1,3),Pair(3,2),Pair(2,3)) val B = A.sortedWith(Comparator<Pair<Int,Int>>{x,y -> x.first.compareTo(y.first)}) // or sortBy{it.first} val list = arrayListOf('a','b','c','d','e') println(list.binarySearch('d')) // 3 list.remove('d') val actualInsertPoint = -(list.binarySearch('d')+1) // 3 list.add(actualInsertPoint, 'd') // [a,b,c,d,e] list.removeAt(1) // remove at index -> [a,c,d,e] } fun remZero(n: Int): Int = if (n%10 != 0) n else remZero(n/10) fun nex(n: Int) = remZero(n+1) fun getSum(start: Long, num: Long): Long { return (2*start+num-1)*num/2 } fun solve() { var (k,n) = io.longs(2) var (mn,mx) = listOf(1L,1e9.toLong()) val ans = ArrayList<Long>() for (i in 0..n-1) { var (lo,hi) = listOf(mn-1,mx) // println(getSum(1,6)) while (lo < hi) { val j = (lo+hi+1)/2 // println("${j} ${k} ${getSum(j,n-i)}") if (getSum(j,n-i) <= k) lo = j else hi = j-1 } if (lo == mn-1) { io.println("NO") return } // io.println("HA "+i+" "+lo) ans.add(lo) mn = lo+1 mx = 2*lo k -= lo } if (k != 0L) { io.println("NO") return } io.println("YES") for (x in ans) io.print("${x} ") } fun main() { // val t = io.int() val t = 1 repeat(t) { solve() } io.flush() }
0
C++
1
2
9f4f78728d111e8f206a7d96b4a7caae050d8e6c
4,029
CodeForces-Solution
MIT License
app/src/main/java/com/andruid/magic/customviewsample/ui/adapter/StringItemAdapter.kt
death14stroke
246,062,154
false
null
package com.andruid.magic.customviewsample.ui.adapter import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.andruid.magic.customviewsample.ui.viewholder.StringItemViewHolder class StringItemAdapter : ListAdapter<String, StringItemViewHolder>(StringDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = StringItemViewHolder.from(parent) override fun onBindViewHolder(holder: StringItemViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } } class StringDiffCallback : DiffUtil.ItemCallback<String>() { override fun areItemsTheSame(oldItem: String, newItem: String) = oldItem == newItem override fun areContentsTheSame(oldItem: String, newItem: String) = oldItem == newItem }
0
Kotlin
0
1
f3485ad7445b7321286ff4987ac5d8b1a20c1c29
874
custom-views
Apache License 2.0
src/main/kotlin/dev/voqal/assistant/tool/ide/ShowCodeTool.kt
voqal
716,228,492
false
{"Kotlin": 1209055, "Java": 493485, "JavaScript": 13007, "Go": 10765, "Python": 9638, "TypeScript": 828, "Groovy": 568, "PHP": 315, "Rust": 308}
package dev.voqal.assistant.tool.ide import com.aallam.openai.api.chat.Tool import com.aallam.openai.api.core.Parameters import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import dev.voqal.assistant.VoqalDirective import dev.voqal.assistant.tool.VoqalTool import dev.voqal.assistant.tool.system.AnswerQuestionTool import dev.voqal.services.* import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import kotlinx.coroutines.launch import kotlin.math.max class ShowCodeTool : VoqalTool() { companion object { const val NAME = "show_code" } override val name = NAME override suspend fun actionPerformed(args: JsonObject, directive: VoqalDirective) { val project = directive.project val log = project.getVoqalLogger(this::class) val resultText = args.getString("result") //todo: should be a tool? val question = Regex("Question: (.*)").find(resultText)?.groupValues?.get(1) if (question != null) { project.service<VoqalToolService>().blindExecute( AnswerQuestionTool(), JsonObject().put("answer", question) ) return } val qualifiedName = Regex("Qualified name: (.*)").find(resultText)?.groupValues?.get(1) val lineRange = Regex("Line range: (\\d+)-(\\d+)").find(resultText)?.groupValues?.let { it[1].toInt()..it[2].toInt() } log.debug("qualifiedName: $qualifiedName") log.debug("lineRange: $lineRange") //open file var file = project.service<VoqalSearchService>().findFile(qualifiedName!!) if (file == null) { val modifiedName = qualifiedName.substringBeforeLast('.') log.warn("Trying without last part of qualified name: $modifiedName") file = project.service<VoqalSearchService>().findFile(modifiedName) } if (file == null) { val modifiedName = qualifiedName.substringBeforeLast('#') log.warn("Trying without last part of qualified name: $modifiedName") file = project.service<VoqalSearchService>().findFile(modifiedName) } if (file != null) { project.invokeLater { val fileEditor = FileEditorManager.getInstance(project).openFile(file, true).first() val editor = (fileEditor as TextEditor).editor //jump to line val lineNumber = lineRange?.first ?: 0 ApplicationManager.getApplication().invokeAndWait { val logicalPosition = LogicalPosition(max(0, lineNumber - 1), 0) //intellij is 0-based editor.caretModel.moveToLogicalPosition(logicalPosition) editor.scrollingModel.scrollToCaret(ScrollType.CENTER) //highlight lines project.scope.launch { project.service<VoqalToolService>().blindExecute( SelectLinesTool(), JsonObject() .put("startLine", lineRange?.first) .put("endLine", lineRange?.last) ) } } } } else { log.warn("File not found for qualified name: $qualifiedName") } } override fun isVisible(directive: VoqalDirective): Boolean { return directive.assistant.promptSettings?.promptName?.lowercase() == "search mode" } override fun asTool(directive: VoqalDirective) = Tool.function( name = NAME, description = "Shows code (functions, variables, etc.) based on the fully qualified name.", parameters = Parameters.fromJsonString(JsonObject().apply { put("type", "object") put("properties", JsonObject().apply { put("qualifiedName", JsonObject().apply { put("type", "string") put("description", "The fully qualified name of the code to show.") }) }) put("required", JsonArray().add("qualifiedName")) }.toString()) ) }
1
Kotlin
8
90
1a4eac0c4907c44a88288d6af6a686b97b003583
4,408
coder
Apache License 2.0
src/test/kotlin/sorting/TimSortTest.kt
evitwilly
418,166,620
false
{"Kotlin": 177633}
package sorting import org.junit.Test import org.junit.jupiter.api.Assertions class TimSortTest { @Test fun test_reversed_array() { val expected = TestUtils.list(100000) val actual = expected.reversed().toTypedArray() actual.timSort() Assertions.assertEquals(expected, actual.toList()) } @Test fun test_random_array() { val actual = TestUtils.randomArray(50000) val expected = actual.sorted() actual.timSort() Assertions.assertEquals(expected, actual.toList()) } @Test fun test_shuffled_array() { val expected = TestUtils.sortedArray(100000) val actual = expected.copyOf() actual.shuffle() actual.timSort() Assertions.assertEquals(expected.toList(), actual.toList()) } @Test fun test_sorted_array() { val actual = TestUtils.sortedArray(100000) val expected = actual.toList() actual.timSort() Assertions.assertEquals(expected, actual.toList()) } }
0
Kotlin
130
729
c2254f2f6fb3976a746049e29523b950c35e56fb
1,047
Kotlin-Algorithms-and-Design-Patterns
MIT License
dsl/waf/src/main/kotlin/software/amazon/awscdk/dsl/services/waf/dsl.kt
aws-cdk-dsl
176,878,480
false
{"Kotlin": 3500307}
package software.amazon.awscdk.dsl.services.waf /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet */ fun software.amazon.awscdk.Construct.cfnSqlInjectionMatchSet(id: String, props: software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps? = null, init: (software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.() -> Unit)? = null) : software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet { val obj = software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSet */ fun software.amazon.awscdk.Construct.cfnXssMatchSet(id: String, props: software.amazon.awscdk.services.waf.CfnXssMatchSetProps? = null, init: (software.amazon.awscdk.services.waf.CfnXssMatchSet.() -> Unit)? = null) : software.amazon.awscdk.services.waf.CfnXssMatchSet { val obj = software.amazon.awscdk.services.waf.CfnXssMatchSet(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet */ fun software.amazon.awscdk.Construct.cfnByteMatchSet(id: String, props: software.amazon.awscdk.services.waf.CfnByteMatchSetProps? = null, init: (software.amazon.awscdk.services.waf.CfnByteMatchSet.() -> Unit)? = null) : software.amazon.awscdk.services.waf.CfnByteMatchSet { val obj = software.amazon.awscdk.services.waf.CfnByteMatchSet(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.waf.CfnIPSet */ fun software.amazon.awscdk.Construct.cfnIPSet(id: String, props: software.amazon.awscdk.services.waf.CfnIPSetProps? = null, init: (software.amazon.awscdk.services.waf.CfnIPSet.() -> Unit)? = null) : software.amazon.awscdk.services.waf.CfnIPSet { val obj = software.amazon.awscdk.services.waf.CfnIPSet(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.waf.CfnWebACL */ fun software.amazon.awscdk.Construct.cfnWebACL(id: String, props: software.amazon.awscdk.services.waf.CfnWebACLProps? = null, init: (software.amazon.awscdk.services.waf.CfnWebACL.() -> Unit)? = null) : software.amazon.awscdk.services.waf.CfnWebACL { val obj = software.amazon.awscdk.services.waf.CfnWebACL(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.waf.CfnRule */ fun software.amazon.awscdk.Construct.cfnRule(id: String, props: software.amazon.awscdk.services.waf.CfnRuleProps? = null, init: (software.amazon.awscdk.services.waf.CfnRule.() -> Unit)? = null) : software.amazon.awscdk.services.waf.CfnRule { val obj = software.amazon.awscdk.services.waf.CfnRule(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet */ fun software.amazon.awscdk.Construct.cfnSizeConstraintSet(id: String, props: software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps? = null, init: (software.amazon.awscdk.services.waf.CfnSizeConstraintSet.() -> Unit)? = null) : software.amazon.awscdk.services.waf.CfnSizeConstraintSet { val obj = software.amazon.awscdk.services.waf.CfnSizeConstraintSet(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder */ fun sizeConstraintProperty(init: software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty { val builder = software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.withFieldToMatch */ var software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.fieldToMatch: software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty get() = throw NoSuchFieldException("Get on fieldToMatch is not supported.") set(value) { this.withFieldToMatch(value) } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.withTextTransformation */ var software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.textTransformation: String get() = throw NoSuchFieldException("Get on textTransformation is not supported.") set(value) { this.withTextTransformation(value) } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.withSize */ var software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.size: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on size is not supported.") set(value) { this.withSize(value) } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.withComparisonOperator */ var software.amazon.awscdk.services.waf.CfnSizeConstraintSet.SizeConstraintProperty.Builder.comparisonOperator: String get() = throw NoSuchFieldException("Get on comparisonOperator is not supported.") set(value) { this.withComparisonOperator(value) } /** * @see software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder */ fun predicateProperty(init: software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnRule.PredicateProperty { val builder = software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder.withType */ var software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder.type: String get() = throw NoSuchFieldException("Get on type is not supported.") set(value) { this.withType(value) } /** * @see software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder.withNegated */ var software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder.negated: Boolean get() = throw NoSuchFieldException("Get on negated is not supported.") set(value) { this.withNegated(value) } /** * @see software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder.withDataId */ var software.amazon.awscdk.services.waf.CfnRule.PredicateProperty.Builder.dataId: String get() = throw NoSuchFieldException("Get on dataId is not supported.") set(value) { this.withDataId(value) } /** * @see software.amazon.awscdk.services.waf.CfnIPSetProps.Builder */ fun cfnIPSetProps(init: software.amazon.awscdk.services.waf.CfnIPSetProps.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnIPSetProps { val builder = software.amazon.awscdk.services.waf.CfnIPSetProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnIPSetProps.Builder.withIpSetDescriptors */ var software.amazon.awscdk.services.waf.CfnIPSetProps.Builder.ipSetDescriptors: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on ipSetDescriptors is not supported.") set(value) { this.withIpSetDescriptors(value) } /** * @see software.amazon.awscdk.services.waf.CfnIPSetProps.Builder.withName */ var software.amazon.awscdk.services.waf.CfnIPSetProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps.Builder */ fun cfnSizeConstraintSetProps(init: software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps { val builder = software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps.Builder.withName */ var software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps.Builder.withSizeConstraints */ var software.amazon.awscdk.services.waf.CfnSizeConstraintSetProps.Builder.sizeConstraints: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on sizeConstraints is not supported.") set(value) { this.withSizeConstraints(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder */ fun byteMatchTupleProperty(init: software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty { val builder = software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.withFieldToMatch */ var software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.fieldToMatch: software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty get() = throw NoSuchFieldException("Get on fieldToMatch is not supported.") set(value) { this.withFieldToMatch(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.withTextTransformation */ var software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.textTransformation: String get() = throw NoSuchFieldException("Get on textTransformation is not supported.") set(value) { this.withTextTransformation(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.withTargetString */ var software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.targetString: String get() = throw NoSuchFieldException("Get on targetString is not supported.") set(value) { this.withTargetString(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.withTargetStringBase64 */ var software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.targetStringBase64: String get() = throw NoSuchFieldException("Get on targetStringBase64 is not supported.") set(value) { this.withTargetStringBase64(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.withPositionalConstraint */ var software.amazon.awscdk.services.waf.CfnByteMatchSet.ByteMatchTupleProperty.Builder.positionalConstraint: String get() = throw NoSuchFieldException("Get on positionalConstraint is not supported.") set(value) { this.withPositionalConstraint(value) } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.FieldToMatchProperty.Builder */ fun fieldToMatchProperty(init: software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.FieldToMatchProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.FieldToMatchProperty { val builder = software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.FieldToMatchProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.FieldToMatchProperty.Builder.withData */ var software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.FieldToMatchProperty.Builder.data: String get() = throw NoSuchFieldException("Get on data is not supported.") set(value) { this.withData(value) } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.FieldToMatchProperty.Builder.withType */ var software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.FieldToMatchProperty.Builder.type: String get() = throw NoSuchFieldException("Get on type is not supported.") set(value) { this.withType(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSetProps.Builder */ fun cfnByteMatchSetProps(init: software.amazon.awscdk.services.waf.CfnByteMatchSetProps.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnByteMatchSetProps { val builder = software.amazon.awscdk.services.waf.CfnByteMatchSetProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSetProps.Builder.withName */ var software.amazon.awscdk.services.waf.CfnByteMatchSetProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSetProps.Builder.withByteMatchTuples */ var software.amazon.awscdk.services.waf.CfnByteMatchSetProps.Builder.byteMatchTuples: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on byteMatchTuples is not supported.") set(value) { this.withByteMatchTuples(value) } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty.Builder */ fun fieldToMatchProperty(init: software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty { val builder = software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty.Builder.withData */ var software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty.Builder.data: String get() = throw NoSuchFieldException("Get on data is not supported.") set(value) { this.withData(value) } /** * @see software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty.Builder.withType */ var software.amazon.awscdk.services.waf.CfnSizeConstraintSet.FieldToMatchProperty.Builder.type: String get() = throw NoSuchFieldException("Get on type is not supported.") set(value) { this.withType(value) } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.SqlInjectionMatchTupleProperty.Builder */ fun sqlInjectionMatchTupleProperty(init: software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.SqlInjectionMatchTupleProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.SqlInjectionMatchTupleProperty { val builder = software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.SqlInjectionMatchTupleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.SqlInjectionMatchTupleProperty.Builder.withFieldToMatch */ var software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.SqlInjectionMatchTupleProperty.Builder.fieldToMatch: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on fieldToMatch is not supported.") set(value) { this.withFieldToMatch(value) } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.SqlInjectionMatchTupleProperty.Builder.withTextTransformation */ var software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSet.SqlInjectionMatchTupleProperty.Builder.textTransformation: String get() = throw NoSuchFieldException("Get on textTransformation is not supported.") set(value) { this.withTextTransformation(value) } /** * @see software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder */ fun activatedRuleProperty(init: software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty { val builder = software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder.withAction */ var software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder.action: software.amazon.awscdk.services.waf.CfnWebACL.WafActionProperty get() = throw NoSuchFieldException("Get on action is not supported.") set(value) { this.withAction(value) } /** * @see software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder.withRuleId */ var software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder.ruleId: String get() = throw NoSuchFieldException("Get on ruleId is not supported.") set(value) { this.withRuleId(value) } /** * @see software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder.withPriority */ var software.amazon.awscdk.services.waf.CfnWebACL.ActivatedRuleProperty.Builder.priority: Number get() = throw NoSuchFieldException("Get on priority is not supported.") set(value) { this.withPriority(value) } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSet.XssMatchTupleProperty.Builder */ fun xssMatchTupleProperty(init: software.amazon.awscdk.services.waf.CfnXssMatchSet.XssMatchTupleProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnXssMatchSet.XssMatchTupleProperty { val builder = software.amazon.awscdk.services.waf.CfnXssMatchSet.XssMatchTupleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSet.XssMatchTupleProperty.Builder.withFieldToMatch */ var software.amazon.awscdk.services.waf.CfnXssMatchSet.XssMatchTupleProperty.Builder.fieldToMatch: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on fieldToMatch is not supported.") set(value) { this.withFieldToMatch(value) } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSet.XssMatchTupleProperty.Builder.withTextTransformation */ var software.amazon.awscdk.services.waf.CfnXssMatchSet.XssMatchTupleProperty.Builder.textTransformation: String get() = throw NoSuchFieldException("Get on textTransformation is not supported.") set(value) { this.withTextTransformation(value) } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSet.FieldToMatchProperty.Builder */ fun fieldToMatchProperty(init: software.amazon.awscdk.services.waf.CfnXssMatchSet.FieldToMatchProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnXssMatchSet.FieldToMatchProperty { val builder = software.amazon.awscdk.services.waf.CfnXssMatchSet.FieldToMatchProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSet.FieldToMatchProperty.Builder.withData */ var software.amazon.awscdk.services.waf.CfnXssMatchSet.FieldToMatchProperty.Builder.data: String get() = throw NoSuchFieldException("Get on data is not supported.") set(value) { this.withData(value) } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSet.FieldToMatchProperty.Builder.withType */ var software.amazon.awscdk.services.waf.CfnXssMatchSet.FieldToMatchProperty.Builder.type: String get() = throw NoSuchFieldException("Get on type is not supported.") set(value) { this.withType(value) } /** * @see software.amazon.awscdk.services.waf.CfnRuleProps.Builder */ fun cfnRuleProps(init: software.amazon.awscdk.services.waf.CfnRuleProps.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnRuleProps { val builder = software.amazon.awscdk.services.waf.CfnRuleProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnRuleProps.Builder.withMetricName */ var software.amazon.awscdk.services.waf.CfnRuleProps.Builder.metricName: String get() = throw NoSuchFieldException("Get on metricName is not supported.") set(value) { this.withMetricName(value) } /** * @see software.amazon.awscdk.services.waf.CfnRuleProps.Builder.withPredicates */ var software.amazon.awscdk.services.waf.CfnRuleProps.Builder.predicates: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on predicates is not supported.") set(value) { this.withPredicates(value) } /** * @see software.amazon.awscdk.services.waf.CfnRuleProps.Builder.withName */ var software.amazon.awscdk.services.waf.CfnRuleProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSetProps.Builder */ fun cfnXssMatchSetProps(init: software.amazon.awscdk.services.waf.CfnXssMatchSetProps.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnXssMatchSetProps { val builder = software.amazon.awscdk.services.waf.CfnXssMatchSetProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSetProps.Builder.withName */ var software.amazon.awscdk.services.waf.CfnXssMatchSetProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.waf.CfnXssMatchSetProps.Builder.withXssMatchTuples */ var software.amazon.awscdk.services.waf.CfnXssMatchSetProps.Builder.xssMatchTuples: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on xssMatchTuples is not supported.") set(value) { this.withXssMatchTuples(value) } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps.Builder */ fun cfnSqlInjectionMatchSetProps(init: software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps { val builder = software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps.Builder.withName */ var software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps.Builder.withSqlInjectionMatchTuples */ var software.amazon.awscdk.services.waf.CfnSqlInjectionMatchSetProps.Builder.sqlInjectionMatchTuples: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on sqlInjectionMatchTuples is not supported.") set(value) { this.withSqlInjectionMatchTuples(value) } /** * @see software.amazon.awscdk.services.waf.CfnWebACLProps.Builder */ fun cfnWebACLProps(init: software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnWebACLProps { val builder = software.amazon.awscdk.services.waf.CfnWebACLProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.withDefaultAction */ var software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.defaultAction: software.amazon.awscdk.services.waf.CfnWebACL.WafActionProperty get() = throw NoSuchFieldException("Get on defaultAction is not supported.") set(value) { this.withDefaultAction(value) } /** * @see software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.withMetricName */ var software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.metricName: String get() = throw NoSuchFieldException("Get on metricName is not supported.") set(value) { this.withMetricName(value) } /** * @see software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.withName */ var software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.withRules */ var software.amazon.awscdk.services.waf.CfnWebACLProps.Builder.rules: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on rules is not supported.") set(value) { this.withRules(value) } /** * @see software.amazon.awscdk.services.waf.CfnWebACL.WafActionProperty.Builder */ fun wafActionProperty(init: software.amazon.awscdk.services.waf.CfnWebACL.WafActionProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnWebACL.WafActionProperty { val builder = software.amazon.awscdk.services.waf.CfnWebACL.WafActionProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnWebACL.WafActionProperty.Builder.withType */ var software.amazon.awscdk.services.waf.CfnWebACL.WafActionProperty.Builder.type: String get() = throw NoSuchFieldException("Get on type is not supported.") set(value) { this.withType(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty.Builder */ fun fieldToMatchProperty(init: software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty.Builder.() -> Unit): software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty { val builder = software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty.Builder.withData */ var software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty.Builder.data: String get() = throw NoSuchFieldException("Get on data is not supported.") set(value) { this.withData(value) } /** * @see software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty.Builder.withType */ var software.amazon.awscdk.services.waf.CfnByteMatchSet.FieldToMatchProperty.Builder.type: String get() = throw NoSuchFieldException("Get on type is not supported.") set(value) { this.withType(value) }
2
Kotlin
0
31
054694dc9793b7455c517af6afd666ec742594d4
26,424
aws-cdk-kotlin-dsl
MIT License
app/src/main/java/com/binayshaw7777/readbud/components/ThemeSwitch.kt
binayshaw7777
658,927,354
false
null
package com.binayshaw7777.readbud.components import androidx.compose.material3.Switch import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.hilt.navigation.compose.hiltViewModel import com.binayshaw7777.readbud.viewmodel.ThemeViewModel @Composable fun ThemeSwitch() { val themeViewModel: ThemeViewModel = hiltViewModel() val themeState by themeViewModel.themeState.collectAsState() Switch( modifier = Modifier.semantics { contentDescription = "Theme Switch" }, checked = themeState.isDarkMode, onCheckedChange = { themeViewModel.toggleTheme() }) }
0
Kotlin
0
5
fa6ea2fde9965f32d2269c79da4803a23bfa6a48
820
ReadBud
The Unlicense
src/site/pegasis/ta/fetch/main.kt
PegasisForever
224,926,609
false
null
package site.pegasis.ta.fetch import picocli.CommandLine import picocli.CommandLine.* import site.pegasis.ta.fetch.modes.getMark import site.pegasis.ta.fetch.modes.server.LATEST_API_VERSION import site.pegasis.ta.fetch.modes.server.MIN_API_VERSION import site.pegasis.ta.fetch.modes.server.startServer import site.pegasis.ta.fetch.modes.server.storage.Config import site.pegasis.ta.fetch.modes.server.storage.initFiles import site.pegasis.ta.fetch.tools.getInput import site.pegasis.ta.fetch.tools.serverBuildNumber import java.util.concurrent.Callable suspend fun main(args: Array<String>) { initFiles() Config.load() CommandLine(FetchTa()) .addSubcommand(GetMark()) .addSubcommand(Server()) .execute(*args) } @Command( name = "fetchta", mixinStandardHelpOptions = true, version = ["BN$serverBuildNumber"] ) class FetchTa : Callable<Unit> { override fun call() {} } class ApiVersionConverter : ITypeConverter<Int> { override fun convert(p0: String): Int { val apiVersion = p0.toInt() if (apiVersion < MIN_API_VERSION || apiVersion > LATEST_API_VERSION) { error("Api version must between $MIN_API_VERSION and $LATEST_API_VERSION.") } return apiVersion } } @Command( description = ["Fetch a student's mark from YRDSB Teach Assist."], name = "getmark", mixinStandardHelpOptions = true, version = ["BN$serverBuildNumber"] ) class GetMark : Callable<Unit> { @Parameters(index = "0", defaultValue = "") private var studentNumber = "" @Parameters(index = "1", defaultValue = "") private var password = "" @Option( names = ["--api", "-a"], description = ["API Level of the output JSON, default to $LATEST_API_VERSION."], converter = [ApiVersionConverter::class] ) private var apiLevel = LATEST_API_VERSION @CommandLine.Option( names = ["--quiet", "-q"], description = ["Don't output logs."] ) private var quiet = false @CommandLine.Option( names = ["--raw", "-r"], description = ["Don't do calculations."] ) private var raw = false @CommandLine.Option( names = ["--interactive", "-i"], description = ["Ask for student number and password"] ) private var interactive = false override fun call() { if (interactive) { studentNumber = getInput("Student number: ") password = getInput("Password: ", password = true) } else if (studentNumber.isBlank() || password.isBlank()) { System.err.println("Please specify student number and password." + "") return } getMark(studentNumber, password, apiLevel, quiet, raw) } } @Command( description = ["Run as a server of unofficial YRDSB Teach Assist."], name = "server", mixinStandardHelpOptions = true, version = ["BN$serverBuildNumber"] ) class Server : Callable<Unit> { @Option( names = ["--enable-private", "-p"], description = ["Enable private server."] ) private var enablePrivate = false @Option( names = ["--private-port"], description = ["Port of private server, default to 5004."] ) private var privatePort = 5004 @Option( names = ["--control-port"], description = ["Control port of private server, default to 5006."] ) private var controlPort = 5006 @Option( names = ["--public-port"], description = ["Port of public server, default to 5005."] ) private var publicPort = 5005 @Option( names = ["--host", "--db-host"], description = ["Host of the database, default to localhost."] ) private var dbHost = "localhost" @Option( names = ["--port", "--db-port"], description = ["Host of the database, default to 27017."] ) private var dbPort = 27017 @Option( names = ["-u", "--db-user"], description = ["User of the database, default to root."] ) private var dbUser = "root" @Option( names = ["--password", "--db-password"], description = ["Password of the database, default to password."] ) private var dbPassword = "password" override fun call() = startServer(enablePrivate, privatePort, controlPort, publicPort, dbHost, dbPort, dbUser, dbPassword) }
1
Kotlin
0
5
61868641952ab6a8a4ba51ac34fe808c00c4dac3
4,396
Fetch-TA-Data
MIT License
domain/src/main/java/kekmech/ru/domain/SetIsShowedUpdateDialogUseCaseImpl.kt
NuvaltsevAA
249,189,732
true
{"Kotlin": 355287, "Shell": 46}
package kekmech.ru.domain import kekmech.ru.core.repositories.UserRepository import kekmech.ru.core.usecases.SetIsShowedUpdateDialogUseCase class SetIsShowedUpdateDialogUseCaseImpl constructor( private val userRepository: UserRepository ) : SetIsShowedUpdateDialogUseCase { override fun invoke(boolean: Boolean) { userRepository.isShowedUpdateDialog = boolean } }
0
null
0
0
94bd394725e495a13f818e94f674a5353dd29bcb
385
mpeiapp
MIT License
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/calendar/facade/rest/CalendarExportController.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.project.calendar.facade.rest import com.bosch.pt.csm.cloud.common.facade.rest.ApiVersion import com.bosch.pt.iot.smartsite.common.facade.rest.resource.response.JobResponseResource import com.bosch.pt.iot.smartsite.project.calendar.api.CalendarExportParameters import com.bosch.pt.iot.smartsite.project.calendar.facade.job.submitter.CalendarExportJobSubmitter import com.bosch.pt.iot.smartsite.project.project.ProjectId import jakarta.validation.Valid import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RestController @ApiVersion @RestController open class CalendarExportController( private val calendarExportJobSubmitter: CalendarExportJobSubmitter ) { @PostMapping(EXPORT_PDF_BY_PROJECT_ID_ENDPOINT) open fun exportPdf( @PathVariable(PATH_VARIABLE_PROJECT_ID) projectIdentifier: ProjectId, @RequestBody @Valid calendarExportResource: CalendarExportParameters, @RequestHeader(name = "Authorization") token: String ): ResponseEntity<JobResponseResource> { val jobIdentifier = calendarExportJobSubmitter.enqueuePdfExportJob( projectIdentifier, calendarExportResource, token) return ResponseEntity.accepted().body(JobResponseResource(jobIdentifier.toString())) } @PostMapping(EXPORT_JSON_BY_PROJECT_ID_ENDPOINT) open fun exportJson( @PathVariable(PATH_VARIABLE_PROJECT_ID) projectIdentifier: ProjectId, @RequestBody @Valid calendarExportResource: CalendarExportParameters ): ResponseEntity<JobResponseResource> { val jobIdentifier = calendarExportJobSubmitter.enqueueJsonExportJob(projectIdentifier, calendarExportResource) return ResponseEntity.accepted().body(JobResponseResource(jobIdentifier.toString())) } @PostMapping(EXPORT_CSV_BY_PROJECT_ID_ENDPOINT) open fun exportCsv( @PathVariable(PATH_VARIABLE_PROJECT_ID) projectIdentifier: ProjectId, @RequestBody @Valid calendarExportResource: CalendarExportParameters ): ResponseEntity<JobResponseResource> { val jobIdentifier = calendarExportJobSubmitter.enqueueCsvExportJob(projectIdentifier, calendarExportResource) return ResponseEntity.accepted().body(JobResponseResource(jobIdentifier.toString())) } companion object { const val PATH_VARIABLE_PROJECT_ID = "projectId" const val EXPORT_CSV_BY_PROJECT_ID_ENDPOINT = "/projects/{projectId}/calendar/export/csv" const val EXPORT_JSON_BY_PROJECT_ID_ENDPOINT = "/projects/{projectId}/calendar/export/json" const val EXPORT_PDF_BY_PROJECT_ID_ENDPOINT = "/projects/{projectId}/calendar/export/pdf" } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
3,095
bosch-pt-refinemysite-backend
Apache License 2.0
src/main/kotlin/cn/edu/gxust/jiweihuang/kotlin/math/function/univariate/UnivariateFunction.kt
jwhgxust
179,000,909
false
null
package cn.edu.gxust.jiweihuang.kotlin.math.function.univariate import org.hipparchus.analysis.differentiation.UnivariateDifferentiableFunction import org.hipparchus.analysis.UnivariateFunction import org.hipparchus.analysis.differentiation.DSFactory import org.hipparchus.analysis.integration.* /** * The interface [IUnivariateFunction] is used for representing univariate function. * * It inherits from [org.hipparchus.analysis.UnivariateFunction] interface of * hipparchus library which is powerful java math library. * * Create date:2019-02-17 * * Last revision date:2019-03-08 * * @author <NAME> * @since 1.0.0 * @see UnivariateFunction */ interface IUnivariateFunction : UnivariateFunction { /** * The string of univariate functional analytic expression. * for instance:`f(x)=a*x+b` */ val formula: String } /** * The interface [IUnivariateDerivativeFunction] is used for * representing analytic derivative function of univariate function. * * Create date:2019-02-17 * * Last revision date:2019-03-08 * * @author <NAME> * @since 1.0.0 * @see IUnivariateFunction */ interface IUnivariateDerivativeFunction : IUnivariateFunction { /** * Get the calculated value of derivative function * at independent variable `x`. */ fun derivative(x: Double): Double } /** * The interface [IUnivariateIntegralFunction] is used for * representing analytic integral function of univariate function. * * Create date:2019-02-17 * * Last revision date:2019-03-08 * * @author <NAME> * @since 1.0.0 * @see IUnivariateFunction */ interface IUnivariateIntegralFunction : IUnivariateFunction { /** * Get the calculated value of integral function * at independent variable `x`. * * The integral constant of integral function is set to `0.0` */ fun integral(x: Double): Double /** * Get the definite integral calculated value of univariate function at * interval of independent variables `[lowerX,upperX]`. * * @throws IllegalArgumentException if `lowerX` or `upperX` is not finite. */ fun integral(lowerX: Double, upperX: Double): Double { if (lowerX.isFinite() && upperX.isFinite()) { return integral(upperX) - integral(lowerX) } else { throw IllegalArgumentException("Expected the parameter {lowerX} and {upperX} is finite,but get {lowerX = $lowerX,upperX=$upperX}.") } } } /** * The interface [IUnivariateInverseFunction] is used for * representing inverse function of univariate function. * * Create date:2019-02-17 * * Last revision date:2019-03-06 * * @author <NAME> * @since 1.0.0 * @see IUnivariateFunction */ interface IUnivariateInverseFunction : IUnivariateFunction { /** * Get the calculated value of inverse function * at dependent variable `y`. */ fun inverse(y: Double): DoubleArray } /** * The interface [IUnivariateDifferentiableFunction] is used for * representing differential of univariate function with * Rall's Number described in Dan Kalman's paper * [Doubly Recursive Multivariate Automatic Differentiation](http://www1.american.edu/cas/mathstat/People/kalman/pdffiles/mmgautodiff.pdf) * * Create date:2019-02-17 * * Last revision date:2019-03-08 * * @author <NAME> * @since 1.0.0 * @see IUnivariateFunction * @see UnivariateDifferentiableFunction */ interface IUnivariateDifferentiableFunction : IUnivariateFunction, UnivariateDifferentiableFunction { /** * Get the calculated differential with specified order. */ fun differential(x: Double, order: Int = 1): Double { return value(DSFactory(1, order).variable(0, x)).getPartialDerivative(order) } } /** * The interface [IUnivariateIntegrableFunction] is used for * representing univariate integrable function with numerical * integration method . * * Create date:2019-02-17 * * Last revision date:2019-03-08 * * @author <NAME> * @since 1.0.0 * @see IUnivariateFunction * @see RombergIntegrator * @see SimpsonIntegrator * @see MidPointIntegrator * @see TrapezoidIntegrator * @see IterativeLegendreGaussIntegrator */ interface IUnivariateIntegrableFunction : IUnivariateFunction { /** * default integrate with optional integral algorithm specified with [String]. * * @throws IllegalArgumentException if method is not one of `{"romberg","simpson","midpoint" * "trapezoid","iterativelegendregauss"}` that ignore case. */ fun integrate(lowerX: Double, upperX: Double, method: String): Double { return when (method.toLowerCase()) { "romberg" -> integrateRomberg(lowerX, upperX) "simpson" -> integrateSimpson(lowerX, upperX) "midpoint" -> integrateMidPoint(lowerX, upperX) "trapezoid" -> integrateTrapezoid(lowerX, upperX) "iterativelegendregauss" -> integrateIterativeLegendreGauss(lowerX, upperX) else -> throw IllegalArgumentException("Integral methods are not supported for $method") } } /** * default integrate with optional integral algorithm specified with enum [IntegralMethods]. */ fun integrate(lowerX: Double, upperX: Double, methods: IntegralMethods = Companion.IntegralMethods.Romberg): Double { return when (methods) { Companion.IntegralMethods.Romberg -> integrateRomberg(lowerX, upperX) Companion.IntegralMethods.Simpson -> integrateSimpson(lowerX, upperX) Companion.IntegralMethods.MidPoint -> integrateMidPoint(lowerX, upperX) Companion.IntegralMethods.Trapezoid -> integrateTrapezoid(lowerX, upperX) Companion.IntegralMethods.IterativeLegendreGauss -> integrateIterativeLegendreGauss(lowerX, upperX) } } companion object { const val defaultMaxIter: Int = Int.MAX_VALUE const val defaultPointsNumberForIterativeLegendreGaussPointsNumber: Int = 32 /** * The enum for integral methods. */ enum class IntegralMethods { Romberg, Simpson, MidPoint, Trapezoid, IterativeLegendreGauss } } /** Romberg integral algorithm */ fun integrateRomberg(lowerX: Double, upperX: Double, maxIter: Int = defaultMaxIter, relativeAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_RELATIVE_ACCURACY, absoluteAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_ABSOLUTE_ACCURACY, minimalIterationCount: Int = BaseAbstractUnivariateIntegrator.DEFAULT_MIN_ITERATIONS_COUNT, maximalIterationCount: Int = RombergIntegrator.ROMBERG_MAX_ITERATIONS_COUNT): Double { return RombergIntegrator(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount).integrate(maxIter, this, lowerX, upperX) } /** Simpson integral algorithm */ fun integrateSimpson(lowerX: Double, upperX: Double, maxIter: Int = defaultMaxIter, relativeAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_RELATIVE_ACCURACY, absoluteAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_ABSOLUTE_ACCURACY, minimalIterationCount: Int = BaseAbstractUnivariateIntegrator.DEFAULT_MIN_ITERATIONS_COUNT, maximalIterationCount: Int = SimpsonIntegrator.SIMPSON_MAX_ITERATIONS_COUNT): Double { return SimpsonIntegrator(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount).integrate(maxIter, this, lowerX, upperX) } /** MidPoint integral algorithm */ fun integrateMidPoint(lowerX: Double, upperX: Double, maxIter: Int = defaultMaxIter, relativeAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_RELATIVE_ACCURACY, absoluteAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_ABSOLUTE_ACCURACY, minimalIterationCount: Int = BaseAbstractUnivariateIntegrator.DEFAULT_MIN_ITERATIONS_COUNT, maximalIterationCount: Int = MidPointIntegrator.MIDPOINT_MAX_ITERATIONS_COUNT): Double { return MidPointIntegrator(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount).integrate(maxIter, this, lowerX, upperX) } /** Trapezoid integral algorithm */ fun integrateTrapezoid(lowerX: Double, upperX: Double, maxIter: Int = defaultMaxIter, relativeAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_RELATIVE_ACCURACY, absoluteAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_ABSOLUTE_ACCURACY, minimalIterationCount: Int = BaseAbstractUnivariateIntegrator.DEFAULT_MIN_ITERATIONS_COUNT, maximalIterationCount: Int = TrapezoidIntegrator.TRAPEZOID_MAX_ITERATIONS_COUNT): Double { return TrapezoidIntegrator(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount).integrate(maxIter, this, lowerX, upperX) } /** Legendre-Gauss quadrature rule on sub-intervals of the integration range */ fun integrateIterativeLegendreGauss(lowerX: Double, upperX: Double, maxIter: Int = defaultMaxIter, integrationPointsNumber: Int = defaultPointsNumberForIterativeLegendreGaussPointsNumber, relativeAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_RELATIVE_ACCURACY, absoluteAccuracy: Double = BaseAbstractUnivariateIntegrator.DEFAULT_ABSOLUTE_ACCURACY, minimalIterationCount: Int = BaseAbstractUnivariateIntegrator.DEFAULT_MIN_ITERATIONS_COUNT, maximalIterationCount: Int = BaseAbstractUnivariateIntegrator.DEFAULT_MAX_ITERATIONS_COUNT): Double { return IterativeLegendreGaussIntegrator(integrationPointsNumber, relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount).integrate(maxIter, this, lowerX, upperX) } }
0
Kotlin
0
0
ce3efec8030f167647cab6f579f8acf47652ad34
10,359
bave-sizes
Apache License 2.0
android/src/main/java/com/marcosfuenmayor/expomultipleimagepicker/ImagePickerModule.kt
mdjfs
473,842,605
false
null
package com.marcosfuenmayor.expomultipleimagepicker import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule class ImagePickerModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName() = "ImagePickerModule" override fun getConstants(): MutableMap<String, Any> { return hashMapOf("count" to 1) } }
4
TypeScript
4
11
c2fc11a08eea216f6035e70fa4b553cdde70ba07
436
expo-image-multiple-picker
MIT License
composeApp/src/commonMain/kotlin/screens/common/use_cases/utils/RankingTableHelper.kt
ernestovega
820,493,782
false
{"Kotlin": 216083, "Swift": 621, "HTML": 341, "CSS": 102}
package screens.common.use_cases.utils import screens.common.model.PlayerRanking import screens.common.model.RankingData import screens.common.model.UiGame object RankingTableHelper { private const val FIRST_POSITION_POINTS = "4" private const val SECOND_POSITION_POINTS = "2" private const val THIRD_POSITION_POINTS = "1" private const val FOURTH_POSITION_POINTS = "0" private const val DRAW_4 = "1.75" private const val DRAW_FIRST_3 = "2.33" private const val DRAW_LAST_3 = "1" private const val DRAW_FIRST_2 = "3" private const val DRAW_SECOND_2 = "1.5" private const val DRAW_LAST_2 = "0.5" fun generateRankingTable(uiGame: UiGame?): RankingData? { if (uiGame == null) return null val sortedPlayersRankings = getSortedPlayersRankings(uiGame) val bestHand = uiGame.getBestHand() return RankingData( sortedPlayersRankings, if (bestHand.handValue == 0) "-" else bestHand.handValue.toString(), if (bestHand.handValue == 0) "-" else bestHand.playerName, uiGame.uiRounds.size, uiGame.uiRounds.size.toString() ) } private fun getSortedPlayersRankings(uiGame: UiGame): List<PlayerRanking> { var playersRankings = setPlayersNamesAndScores(uiGame) playersRankings = playersRankings.sortedByDescending { it.score } setPlayersTablePoints(playersRankings) return playersRankings } private fun setPlayersNamesAndScores(uiGame: UiGame): List<PlayerRanking> = listOf( PlayerRanking(uiGame.nameP1, uiGame.ongoingOrLastRound.totalPointsP1), PlayerRanking(uiGame.nameP2, uiGame.ongoingOrLastRound.totalPointsP2), PlayerRanking(uiGame.nameP3, uiGame.ongoingOrLastRound.totalPointsP3), PlayerRanking(uiGame.nameP4, uiGame.ongoingOrLastRound.totalPointsP4) ) private fun setPlayersTablePoints(sortedPlayers: List<PlayerRanking>): List<PlayerRanking> { sortedPlayers[0].points = FIRST_POSITION_POINTS sortedPlayers[1].points = SECOND_POSITION_POINTS sortedPlayers[2].points = THIRD_POSITION_POINTS sortedPlayers[3].points = FOURTH_POSITION_POINTS val scorePlayerFirst = sortedPlayers[0].score val scorePlayerSecond = sortedPlayers[1].score val scorePlayerThird = sortedPlayers[2].score val scorePlayerFourth = sortedPlayers[3].score if (scorePlayerFirst == scorePlayerSecond && scorePlayerSecond == scorePlayerThird && scorePlayerThird == scorePlayerFourth ) { sortedPlayers[0].points = DRAW_4 sortedPlayers[1].points = DRAW_4 sortedPlayers[2].points = DRAW_4 sortedPlayers[3].points = DRAW_4 return sortedPlayers } else if (scorePlayerFirst == scorePlayerSecond && scorePlayerSecond == scorePlayerThird) { sortedPlayers[0].points = DRAW_FIRST_3 sortedPlayers[1].points = DRAW_FIRST_3 sortedPlayers[2].points = DRAW_FIRST_3 return sortedPlayers } else if (scorePlayerSecond == scorePlayerThird && scorePlayerThird == scorePlayerFourth) { sortedPlayers[1].points = DRAW_LAST_3 sortedPlayers[2].points = DRAW_LAST_3 sortedPlayers[3].points = DRAW_LAST_3 return sortedPlayers } else { if (scorePlayerFirst == scorePlayerSecond) { sortedPlayers[0].points = DRAW_FIRST_2 sortedPlayers[1].points = DRAW_FIRST_2 } if (scorePlayerSecond == scorePlayerThird) { sortedPlayers[1].points = DRAW_SECOND_2 sortedPlayers[2].points = DRAW_SECOND_2 } if (scorePlayerThird == scorePlayerFourth) { sortedPlayers[2].points = DRAW_LAST_2 sortedPlayers[3].points = DRAW_LAST_2 } } return sortedPlayers } }
0
Kotlin
0
0
a1c1b5de82d6991e07bdded6f1de375d7a02425c
3,977
MahjongScoring3
Apache License 2.0
app/src/main/java/com/celzero/bravedns/service/BraveTileService.kt
celzero
270,683,546
false
null
/* Copyright 2020 RethinkDNS and its authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.celzero.bravedns.service import android.content.Intent import android.net.VpnService import android.os.Build import android.service.quicksettings.Tile import android.service.quicksettings.TileService import androidx.annotation.RequiresApi import com.celzero.bravedns.ui.HomeScreenActivity import com.celzero.bravedns.ui.PrepareVpnActivity import com.celzero.bravedns.util.Utilities @RequiresApi(api = Build.VERSION_CODES.N) class BraveTileService : TileService() { override fun onCreate() { VpnController.persistentState.vpnEnabledLiveData.observeForever(this::updateTile) } private fun updateTile(enabled: Boolean) { qsTile?.apply { state = if (enabled) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE updateTile() } } override fun onClick() { super.onClick() val vpnState: VpnState = VpnController.state() if (vpnState.on) { VpnController.stop(this) } else if (VpnService.prepare(this) == null) { // Start VPN service when VPN permission has been granted. VpnController.start(this) } else { // Open Main activity when VPN permission has not been granted. val intent = if (Utilities.isHeadlessFlavour()) { Intent(this, PrepareVpnActivity::class.java) } else { Intent(this, HomeScreenActivity::class.java) } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivityAndCollapse(intent) } } }
188
Kotlin
93
1,641
09f8ddbc9a995f0d5e099ff5205dd24aaf7e59b7
2,170
rethink-app
Apache License 2.0
common/src/test/kotlin/dev/jaims/moducore/common/test/message/StringsTest.kt
Jaimss
321,796,760
false
null
/* * This file is a part of ModuCore, licensed under the MIT License. * * Copyright (c) 2020 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.jaims.moducore.common.test.message import dev.jaims.moducore.common.message.LEGACY_SECTION import dev.jaims.moducore.common.message.longHexPattern import dev.jaims.moducore.common.message.miniStyle import dev.jaims.moducore.common.message.shortHexPattern import org.junit.Test import kotlin.test.assertEquals class StringsTest { @Test fun `test that converting from long to short hex works`() { assertEquals("&#ff009d", "&#ff009d".shortHexPattern()) assertEquals("&#FF009d", "&#FF009d".shortHexPattern()) assertEquals("some before&#FF009d", "some before<#FF009d>".shortHexPattern()) assertEquals("&#FF009dwith other words", "<#FF009d>with other words".shortHexPattern()) assertEquals("some before&#FF009dwith other words", "some before<#FF009d>with other words".shortHexPattern()) } @Test fun `test that converting from short to long hex works`() { assertEquals("<#ff009d>", "&#ff009d".longHexPattern()) assertEquals("<#FF009d>", "&#FF009d".longHexPattern()) assertEquals("some before<#FF009d>", "some before&#FF009d".longHexPattern()) assertEquals("<#FF009d>with other words", "&#FF009dwith other words".longHexPattern()) assertEquals("some before<#FF009d>with other words", "some before&#FF009dwith other words".longHexPattern()) } @Test fun `test string to mini message style`() { assertEquals("<dark_blue>This is a <em>mini message", "&1This is a <em>mini message".miniStyle()) assertEquals("<black><italic><bold>Testing", "&0&o&lTesting".miniStyle()) } }
15
Kotlin
1
3
75d723bafa9f53c09e1100c7828e4085ebfa3060
2,791
moducore
MIT License
app/src/main/java/dev/keego/tictactoe/state/VimelStateHolder.kt
thuanpham582002
640,401,257
false
null
package dev.keego.tictactoe.state import androidx.compose.runtime.Stable import androidx.lifecycle.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.updateAndGet /** * Base for all the ViewModels */ @Stable open class VimelStateHolder<STATE : State>(initial: STATE) : ViewModel() { /** * Mutable dev.keego.tictactoe.State of this ViewModel */ private val _state = MutableStateFlow(initial) /** * dev.keego.tictactoe.State to be exposed to the UI layer */ val state: StateFlow<STATE> = _state.asStateFlow() /** * Retrieves the current UI state */ val currentState: STATE get() = state.value /** * Updates the state of this ViewModel and returns the new state * * @param update Lambda callback with old state to calculate a new state * @return The updated state */ protected fun update(update: (old: STATE) -> STATE): STATE = _state.updateAndGet(update) }
0
Kotlin
0
0
f20a74eedf25ca6e68086554e40acca5350ee3bc
1,072
Tic-Tac-Toe-Jetpack-Compose
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SingleNumber3.kt
ashtanko
203,993,092
false
{"Kotlin": 7464757, "Shell": 1168, "Makefile": 1144}
/* * Copyright 2024 <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 dev.shtanko.algorithms.leetcode /** * 260. Single Number III * @see <a href="https://leetcode.com/problems/single-number-iii/">Source</a> */ fun interface SingleNumber3 { operator fun invoke(nums: IntArray): IntArray } class SingleNumber3Bitwise : SingleNumber3 { override fun invoke(nums: IntArray): IntArray { var bitmask = 0 for (num in nums) { bitmask = bitmask xor num } val diff = bitmask and -bitmask var x = 0 for (num in nums) { if (num and diff != 0) { x = x xor num } } return intArrayOf(x, bitmask xor x) } }
6
Kotlin
0
19
5bfd35e51c9076522e46286c3f6e0a81aef5abaa
1,254
kotlab
Apache License 2.0
app/src/main/java/com/pandulapeter/beagle/appDemo/data/model/BeagleListItemContractImplementation.kt
pandulapeter
209,092,048
false
{"Kotlin": 849080, "Ruby": 497}
package com.pandulapeter.beagle.appDemo.data.model import com.pandulapeter.beagle.common.configuration.toText import com.pandulapeter.beagle.common.contracts.BeagleListItemContract data class BeagleListItemContractImplementation( private val name: CharSequence ) : BeagleListItemContract { override val title = name.toText() }
15
Kotlin
27
491
edc654e4bd75bf9519c476c67a9b77d600e3ce9e
337
beagle
Apache License 2.0
src/test/kotlin/no/nav/pensjon/integrationtest/controller/FinnControllerTests.kt
navikt
498,360,259
false
null
package no.nav.pensjon.integrationtest.controller import no.nav.pensjon.TestHelper.mockLoggInnslag import no.nav.pensjon.domain.LoggMelding import no.nav.pensjon.util.fromJson2Any import no.nav.pensjon.util.typeRefs import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.springframework.http.MediaType import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers internal class FinnControllerTest: BaseTest() { @Test fun `sjekk finnController for søk etter person`() { loggTjeneste.lagreLoggInnslag(mockLoggInnslag("13055212250")) loggTjeneste.lagreLoggInnslag(mockLoggInnslag("13055220123")) loggTjeneste.lagreLoggInnslag(mockLoggInnslag("17024101234")) val token: String = mockServiceToken() val response = mockMvc.perform( MockMvcRequestBuilders.get("/sporingslogg/api/test/finn/130552") .header("Authorization", "Bearer $token") .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() val result = response.response.getContentAsString(charset("UTF-8")) assertEquals("""["13055212250","13055220123"]""", result) } @Test fun `sjekk finnController for søk etter person med ingen resultat`() { val token: String = mockServiceToken() val response = mockMvc.perform( MockMvcRequestBuilders.get("/sporingslogg/api/test/finn/010203404") .header("Authorization", "Bearer $token") .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() val result = response.response.getContentAsString(charset("UTF-8")) assertEquals("[]", result) } @Test fun `sjekk finnController for hent av data`() { loggTjeneste.lagreLoggInnslag(mockLoggInnslag("03055212288")) val token: String = mockServiceToken() val response = mockMvc.perform( MockMvcRequestBuilders.get("/sporingslogg/api/test/hent/03055212288") .header("Authorization", "Bearer $token") .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() val result = response.response.getContentAsString(charset("UTF-8")) val list: List<LoggMelding> = fromJson2Any(result, typeRefs()) val expected = """ LoggMelding [person=030552xxxxx, mottaker=938908909, tema=PEN, behandlingsGrunnlag=Lovhjemmel samordningsloven § 27 (samordningsloven paragraf 27), uthentingsTidspunkt=2021-10-09T10:10, leverteData=TGV2ZXJ0ZURhdGEgZXIga3VuIGZvciBkdW1teVRlc3RpbmcgYXYgc3BvcmluZ3Nsb2dnIFRlc3Q=, samtykkeToken=DummyToken, dataForespoersel=Foresporsel, leverandoer=lever] """.trimIndent() assertEquals(expected, list[0].toString()) } @Test fun `sjekk finnController for hentAntall`() { loggTjeneste.lagreLoggInnslag(mockLoggInnslag("01053212288")) loggTjeneste.lagreLoggInnslag(mockLoggInnslag("01053212288")) val token: String = mockServiceToken() val response = mockMvc.perform( MockMvcRequestBuilders.get("/sporingslogg/api/test/antall/01053212288") .header("Authorization", "Bearer $token") .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() assertEquals("2", response.response.getContentAsString(charset("UTF-8"))) } }
10
null
3
2
c738f91e869c8b104a3dd4e47a2e64de9fe34c86
3,703
sporingslogg
MIT License
src/main/kotlin/de/cvguy/kotlin/koreander/exception/ParseError.kt
lukasjapan
112,826,577
false
null
package de.cvguy.kotlin.koreander.exception import de.cvguy.kotlin.koreander.parser.Token open class ParseError( val file: String, val line: Int, val character: Int, message: String ) : KoreanderException(message) { override val message: String = message get() = "Parse error in $file at $line:$character - $field" } class UnexpextedToken(token: Token): ParseError("tba", token.line, token.character, "Unexpexted ${token.type}") class UnexpectedDocType(token: Token): ParseError("tba", token.line, token.character, "Unexpexted DocType ${token.content}") class ExpectedOther(token: Token, expectedType: Set<Token.Type>): ParseError("tba", token.line, token.character, "Expected ${expectedType.joinToString(",")} but found ${token.type}") class UnexpectedEndOfInput(): ParseError("tba", 0, 0, "Unexpected end of input") class InvalidPluginInputExeption(invalidWhitespace: Token) : ParseError("tba", invalidWhitespace.line, invalidWhitespace.character + invalidWhitespace.content.length, "Invalid plugin input. Keep whitespace sane.") class ExpectedBlock(token: Token) : ParseError("tba", token.line + 1, 0, "Expected a deeper indented block.")
3
Kotlin
3
28
4bb233d5d4b36055fcdba53e8d9e92fa500cf6e6
1,193
koreander
MIT License
server/src/main/kotlin/net/eiradir/server/entity/event/EntityMergedEvent.kt
Eiradir
635,460,745
false
null
package net.eiradir.server.entity.event import com.badlogic.ashley.core.Entity import net.eiradir.server.map.ChunkDimensions import net.eiradir.server.map.EiradirMap data class EntityMergedEvent(val map: EiradirMap, val chunkPos: ChunkDimensions, val entity: Entity)
12
Kotlin
0
0
fd732d283c6c72bbd0d0127bb86e8daf7e5bf3cd
268
eiradir-server
MIT License
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/loops/handlers/DefaultProgressionHandler.kt
zhangaz1
282,800,996
true
{"Kotlin": 52922979, "Java": 7648192, "JavaScript": 185101, "HTML": 78949, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "Swift": 10768, "CSS": 9270, "Shell": 7220, "Batchfile": 5727, "Ruby": 2655, "Objective-C": 626, "Scala": 80}
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.common.lower.loops.handlers import org.jetbrains.kotlin.backend.common.CommonBackendContext import org.jetbrains.kotlin.backend.common.lower.createIrBuilder import org.jetbrains.kotlin.backend.common.lower.loops.* import org.jetbrains.kotlin.ir.builders.irCall import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.types.getClass import org.jetbrains.kotlin.ir.util.deepCopyWithSymbols import org.jetbrains.kotlin.ir.util.getPropertyGetter /** Builds a [HeaderInfo] for progressions not handled by more specialized handlers. */ internal class DefaultProgressionHandler(private val context: CommonBackendContext) : ExpressionHandler { private val symbols = context.ir.symbols override fun matchIterable(expression: IrExpression) = ProgressionType.fromIrType( expression.type, symbols ) != null override fun build(expression: IrExpression, scopeOwner: IrSymbol): HeaderInfo? = with(context.createIrBuilder(scopeOwner, expression.startOffset, expression.endOffset)) { // Directly use the `first/last/step` properties of the progression. val (progressionVar, progressionExpression) = createTemporaryVariableIfNecessary(expression, nameHint = "progression") val progressionClass = progressionExpression.type.getClass()!! val first = irCall(progressionClass.symbol.getPropertyGetter("first")!!).apply { dispatchReceiver = progressionExpression } val last = irCall(progressionClass.symbol.getPropertyGetter("last")!!).apply { dispatchReceiver = progressionExpression.deepCopyWithSymbols() } val step = irCall(progressionClass.symbol.getPropertyGetter("step")!!).apply { dispatchReceiver = progressionExpression.deepCopyWithSymbols() } ProgressionHeaderInfo( ProgressionType.fromIrType(progressionExpression.type, symbols)!!, first, last, step, additionalStatements = listOfNotNull(progressionVar), direction = ProgressionDirection.UNKNOWN ) } }
0
null
0
0
635869f15a80b56f7c4d865b73bb7a9b47ee615b
2,499
kotlin
Apache License 2.0
app/src/main/java/it/polito/timebanking/WelcomeActivity.kt
tndevelop
586,483,147
false
null
package it.polito.timebanking import android.accounts.AccountManager import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import android.view.View import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.fragment.app.activityViewModels import com.fasterxml.jackson.databind.ObjectMapper import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.SignInButton import com.google.android.gms.common.api.ApiException import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.GoogleAuthProvider import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import it.polito.timebanking.database.User import it.polito.timebanking.viewmodels.UserViewModel import java.util.* import kotlin.concurrent.schedule class WelcomeActivity : AppCompatActivity() { private lateinit var auth: FirebaseAuth private lateinit var googleSignInClient: GoogleSignInClient val userViewModel by viewModels<UserViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_welcome) val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.web_token)) .requestEmail() .build() googleSignInClient = GoogleSignIn.getClient(this, gso) auth = Firebase.auth findViewById<SignInButton>(R.id.google_button).setOnClickListener { val signInIntent = googleSignInClient.signInIntent startActivityForResult(signInIntent, RC_SIGN_IN) } } override fun onStart() { super.onStart() signIn() } fun signOut(){ Firebase.auth.signOut() } private fun loadToken(account: GoogleSignInAccount) { val am: AccountManager = AccountManager.get(this) val options = Bundle() am.getAuthToken( account.account, // Account retrieved using getAccountsByType() "oauth2: https://www.googleapis.com/auth/firebase.messaging", // Auth scope options, // Authenticator-specific options this, // Your activity { MessagingService.oauthToken = it.result.getString(AccountManager.KEY_AUTHTOKEN)!! }, // Callback called when a token is successfully acquired Handler (Looper.getMainLooper()){ Log.d("GoogleSignInError", "ERROR") Snackbar.make(findViewById(android.R.id.content), getString(R.string.oauth_token_error), Snackbar.LENGTH_LONG).show() true } // Callback called if an error occurs ) } private fun firebaseAuthWithGoogle(idToken: String) { val credential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success") goToMainActivity() } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.exception) Snackbar.make(findViewById(android.R.id.content), getString(R.string.credentials_error), Snackbar.LENGTH_LONG).show() } } } private fun signIn() { if(auth.currentUser!=null) { GoogleSignIn.getLastSignedInAccount(this).also { loadToken(it!!) } goToMainActivity() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN){ if(resultCode == Activity.RESULT_OK) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { // Google Sign In was successful, authenticate with Firebase val account = task.getResult(ApiException::class.java)!! loadToken(account) firebaseAuthWithGoogle(account.idToken!!) val loggedInUser = auth.currentUser Timer().schedule(300) { loggedInUser?.let { val user = User() user.email = it.email!! user.id = it.uid user.nickname = it.email!! user.description = "Hi there! I'm using TimeBanking" userViewModel.save(it.uid, ObjectMapper().convertValue( user, HashMap::class.java ) as HashMap<String, Any>, { Log.d("t", "success") }, { e: Exception -> Log.d("t", e.message.toString()) } ) } } } catch (e: ApiException) { // Google Sign In failed, update UI appropriately Log.w("GoogleSignInError", "Google sign in failed", e) Snackbar.make(findViewById(android.R.id.content), getString(R.string.firebase_login_error), Snackbar.LENGTH_LONG).show() } }else { if (data != null && data.extras!=null) { val e = data.extras!!; Log.d("firestore", e.keySet().size.toString()) e.keySet().iterator().forEach{ Log.d("firestore", "$it -> ${e.get(it).toString()}")} } Snackbar.make(findViewById(android.R.id.content), getString(R.string.firebase_login_error), Snackbar.LENGTH_LONG).show() }} } companion object { private const val TAG = "MAD-group-29" private const val RC_SIGN_IN = 9001 } private fun goToMainActivity(){ findViewById<ConstraintLayout>(R.id.loading).visibility = View.VISIBLE startActivity(Intent(this, MainActivity::class.java)) finishAffinity() } }
0
Kotlin
1
1
edb734d5bf2aa391e7012d45447a8ba4bf5489e4
7,134
Android-Timebanking
MIT License
app/src/main/java/com/luigivampa92/nfcshare/hce/ShareNdefActor.kt
msgpo
267,217,098
true
{"Kotlin": 59923}
package com.luigivampa92.nfcshare.hce import android.nfc.NdefMessage import com.luigivampa92.nfcshare.DataUtil import com.luigivampa92.nfcshare.NdefUtil import com.luigivampa92.nfcshare.toPositiveInt import java.math.BigInteger import java.util.* class ShareNdefActor (message: String) : ApduExecutor { companion object { private val NDEF_AID = byteArrayOf(0xD2.toByte(), 0x76.toByte(), 0x00.toByte(), 0x00.toByte(), 0x85.toByte(), 0x01.toByte(), 0x01.toByte()) private val NDEF_FID_CC = byteArrayOf(0xE1.toByte(), 0x03.toByte()) private val NDEF_FID_DATA = byteArrayOf(0xE1.toByte(), 0x04.toByte()) private val NDEF_SIZE_MAX = byteArrayOf(0x00.toByte(), 0x90.toByte()) // 0x0090 == 144 bytes == sizeof(NTAG213) // 0x0378 == 888 bytes == sizeof(NTAG216) private val NDEF_MODE_READ = byteArrayOf(0x00.toByte()) private val NDEF_MODE_WRITE = byteArrayOf(0xFF.toByte()) } private val ndefMessage: NdefMessage private val ndefMessageBinary: ByteArray private val ndefMessageBinarySize: ByteArray private var adfSelected = false private var efCcSelected = false private var efDataSelected = false init { ndefMessage = NdefUtil.createNdefMessage(message) ndefMessageBinary = ndefMessage.toByteArray() ndefMessageBinarySize = fillByteArrayToFixedDimension(BigInteger.valueOf(ndefMessageBinary.size.toLong()).toByteArray(), 2) } override fun reset() { adfSelected = false efCcSelected = false efDataSelected = false } override fun transmitApdu(apdu: ByteArray): ByteArray { try { val apduCommand = DataUtil.parseCommandApdu(apdu) val cla = apduCommand.cla val ins = apduCommand.ins val p1 = apduCommand.p1 val p2 = apduCommand.p2 val lc = apduCommand.lc val le = apduCommand.le val data = apduCommand.data if (cla == 0x00.toByte() && ins == 0xA4.toByte() && p1 == 0x04.toByte() && p2 == 0x00.toByte() && lc != null && lc.size == 1 && lc[0] == 0x07.toByte() && data != null && data.size == lc[0].toPositiveInt() ) { return if (Arrays.equals(NDEF_AID, data)) { adfSelected = true ApduConstants.SW_OK } else { ApduConstants.SW_ERROR_NO_SUCH_ADF } } if (cla == 0x00.toByte() && ins == 0xA4.toByte() && p1 == 0x00.toByte() && p2 == 0x0C.toByte() && lc != null && lc.size == 1 && lc[0] == 0x02.toByte() && le == null && data != null && data.size == lc[0].toPositiveInt() && adfSelected && !efCcSelected && !efDataSelected ) { return if (Arrays.equals(NDEF_FID_CC, data)) { efCcSelected = true ApduConstants.SW_OK } else { ApduConstants.SW_ERROR_NO_SUCH_ADF } } if (cla == 0x00.toByte() && ins == 0xB0.toByte() && p1 == 0x00.toByte() && p2 == 0x00.toByte() && lc == null && data == null && le != null && le.size == 1 && le[0] == 0x0F.toByte() && adfSelected && efCcSelected && !efDataSelected ) { val ccPrefix = byteArrayOf(0x00.toByte(), 0x11.toByte(), 0x20.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0x04.toByte(), 0x06.toByte()) return DataUtil.concatByteArrays(ccPrefix, NDEF_FID_DATA, NDEF_SIZE_MAX, NDEF_MODE_READ, NDEF_MODE_WRITE, ApduConstants.SW_OK) } if (cla == 0x00.toByte() && ins == 0xA4.toByte() && p1 == 0x00.toByte() && p2 == 0x0C.toByte() && lc != null && lc.size == 1 && lc[0] == 0x02.toByte() && le == null && data != null && data.size == lc[0].toPositiveInt() && adfSelected // && efCcSelected && !efDataSelected // iphones send select data fid multiple times !!! ) { return if (Arrays.equals(NDEF_FID_DATA, data)) { efCcSelected = false efDataSelected = true ApduConstants.SW_OK } else { ApduConstants.SW_ERROR_NO_SUCH_ADF } } if (cla == 0x00.toByte() && ins == 0xB0.toByte() && p1 == 0x00.toByte() && p2 == 0x00.toByte() && lc == null && data == null && le != null && le.size == 1 && le[0] == 0x02.toByte() && adfSelected && !efCcSelected && efDataSelected ) { return DataUtil.concatByteArrays(ndefMessageBinarySize, ApduConstants.SW_OK) } if (cla == 0x00.toByte() && ins == 0xB0.toByte() && adfSelected && !efCcSelected && efDataSelected ) { val offset = apdu.sliceToInt(2..3) val length = apdu.sliceToInt(4..4) val fullResponse = DataUtil.concatByteArrays(ndefMessageBinarySize, ndefMessageBinary) val slicedResponse = fullResponse.sliceArray(offset until fullResponse.size) val realLength = if (slicedResponse.size <= length) slicedResponse.size else length val response = ByteArray(realLength + ApduConstants.SW_OK.size) System.arraycopy(slicedResponse, 0, response, 0, realLength) System.arraycopy(ApduConstants.SW_OK, 0, response, realLength, ApduConstants.SW_OK.size) return response } return ApduConstants.SW_ERROR_GENERAL } catch (e: Throwable) { return ApduConstants.SW_ERROR_GENERAL } } private val HEX_CHARS = "0123456789ABCDEF".toCharArray() private fun ByteArray.toHex() : String{ val result = StringBuffer() forEach { val octet = it.toInt() val firstIndex = (octet and 0xF0).ushr(4) val secondIndex = octet and 0x0F result.append(HEX_CHARS[firstIndex]) result.append(HEX_CHARS[secondIndex]) } return result.toString() } private fun ByteArray.sliceToInt(range: IntRange): Int { return this.sliceArray(range).toHex().toInt(16) } private fun fillByteArrayToFixedDimension(array: ByteArray, fixedSize: Int): ByteArray { if (array.size == fixedSize) { return array } val start = byteArrayOf(0x00.toByte()) val filledArray = ByteArray(start.size + array.size) System.arraycopy(start, 0, filledArray, 0, start.size) System.arraycopy(array, 0, filledArray, start.size, array.size) return fillByteArrayToFixedDimension(filledArray, fixedSize) } }
0
null
0
0
6cf32d32cd4ee53ef7ac5c4f64de87a3ba4f02ac
7,221
ProxyShare
Apache License 2.0
app/src/main/java/by/itman/boxingtimer/ui/main/MainActivity.kt
jaaliska
307,840,684
false
null
package by.itman.boxingtimer.ui.main import android.content.Intent import android.os.Bundle import android.widget.* import by.itman.boxingtimer.R import by.itman.boxingtimer.data.ApplicationDefaultTimers import by.itman.boxingtimer.models.TimerPresentation import by.itman.boxingtimer.ui.BaseActivity import by.itman.boxingtimer.utils.timerFormat import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MainActivity: BaseActivity(), MainView { private lateinit var mImgButSettings: ImageButton private lateinit var mTimeRoundDuration: TextView private lateinit var mTxtRoundDuration: TextView private lateinit var mTimeRestDuration: TextView private lateinit var mTxtRestDuration: TextView private lateinit var mTxtRoundQuantity: TextView private lateinit var mTimeRoundQuantity: TextView private lateinit var mTrainingDuration: TextView private lateinit var mButtonStart: Button private lateinit var mTxtChangeTimer: TextView private lateinit var spinner: Spinner @Inject lateinit var mainPresenter: MainPresenter @Inject lateinit var applicationDefaultTimers: ApplicationDefaultTimers override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mainPresenter.setView(this) applicationDefaultTimers.initializeDefaultTimers() initFields() setOnClickListeners() mainPresenter.setSpinner(this, spinner) } private fun initFields() { mImgButSettings = findViewById(R.id.imgBut_main_settings) mTxtRoundDuration = findViewById(R.id.txt_main_roundDuration) mTimeRoundDuration = findViewById(R.id.time_main_roundDuration) mTxtRestDuration = findViewById(R.id.txt_main_restDuration) mTimeRestDuration = findViewById(R.id.time_main_restDuration) mTxtRoundQuantity = findViewById(R.id.txt_main_roundQuantity) mTimeRoundQuantity = findViewById(R.id.time_main_roundQuantity) mTrainingDuration = findViewById(R.id.txt_main_training_duration) mButtonStart = findViewById(R.id.button_main_start) mTxtChangeTimer = findViewById(R.id.txt_main_change_timer) spinner = findViewById(R.id.spinner_main_timer) } private fun setOnClickListeners() { mImgButSettings.setOnClickListener { mainPresenter.onClickSettings(this) } mTimeRoundDuration.setOnClickListener { mainPresenter.onClickRoundDuration(this) } mTimeRestDuration.setOnClickListener { mainPresenter.onClickRestDuration(this) } mTimeRoundQuantity.setOnClickListener { mainPresenter.onClickRoundQuantity(this) } mButtonStart.setOnClickListener { mainPresenter.onClickStart(this) } } override fun onResume() { super.onResume() mainPresenter.onResumedActivity() mainPresenter.setSpinner(this, spinner) } override fun onPause() { super.onPause() mainPresenter.onPausedActivity() } override fun updateView(timer: TimerPresentation) { mTimeRestDuration.text = timer.getRestDuration().timerFormat() mTimeRoundDuration.text = timer.getRoundDuration().timerFormat() mTimeRoundQuantity.text = "${timer.getRoundQuantity()}" mTrainingDuration.text = getString(R.string.main_txt_training_duration, timer.getTrainingDuration()) } override fun startActivityWith(intent: Intent) { startActivity(intent) } }
1
Kotlin
0
0
d91ea745afb63f44d6c484b9db712c27ddf8002c
3,629
boxing-timer
Apache License 2.0
app/src/main/java/com/greylabs/weathercities/models/CityModelDAO.kt
GreyLabsDev
142,150,856
false
null
package com.greylabs.weathercities.models import android.arch.persistence.room.* @Dao interface CityModelDAO { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(vararg cities: CityModel) @Delete fun delete(city: CityModel) @Query("SELECT * FROM CityModel") fun getAllCities() : List<CityModel> @Query("SELECT * FROM CityModel WHERE cityName LIKE :query") fun getCityByName(query: String) : List<CityModel> @Query("SELECT * FROM CityModel WHERE cityType LIKE :query") fun getCityByType(query: String) : List<CityModel> @Query("DELETE FROM CityModel") fun nukeTable() }
0
Kotlin
0
0
06eaa43c794a49770be127f466c595bc1267d044
606
WeatherCities
MIT License
invirt-utils/src/main/kotlin/invirt/utils/files/TempDir.kt
resoluteworks
762,239,437
false
{"Kotlin": 315493, "Makefile": 673, "CSS": 8}
package invirt.utils.files import invirt.utils.uuid7 import io.github.oshai.kotlinlogging.KotlinLogging import java.io.Closeable import java.io.File import java.io.IOException private val log = KotlinLogging.logger {} class TempDir(parentDirectory: File = tempDirectory()) : Closeable { val directory = createRootDir(parentDirectory) init { log.atInfo { message = "Creating temporary directory" payload = mapOf("directory" to directory.absolutePath) } } fun newFile(extension: String? = null): File { val ext = extension?.let { "." + extension.removePrefix(".") } ?: "" return File(directory, uuid7() + ext) } fun newDirectory(): File { val dir = File(directory, uuid7()) if (!dir.mkdirs()) { throw IllegalStateException("Could not create directory $dir") } return dir } override fun close() { val deleted = try { directory.deleteRecursively() true } catch (e: IOException) { log.atError { message = "Could not delete temporary directory" payload = mapOf("directory" to directory.absolutePath) cause = e } false } if (!deleted) { log.atError { message = "Could not delete temporary directory" payload = mapOf("directory" to directory.absolutePath) } } else { log.atInfo { message = "Deleted temporary directory" payload = mapOf("directory" to directory.absolutePath) } } } private fun createRootDir(workingDirectory: File): File { val tempFile = File(workingDirectory, uuid7()) if (!tempFile.mkdirs()) { throw IllegalStateException("Could not create temp dir $tempFile") } return tempFile } } fun <T> withTempDir( currentDirectory: File = tempDirectory(), block: (TempDir) -> T ): T { return TempDir(currentDirectory).use(block) }
0
Kotlin
0
2
2b80ab6a7df004ec2407d18e38734fbe31322d89
2,110
invirt
Apache License 2.0
src/main/kotlin/com/iwayee/exam/api/comp/User.kt
andycai
339,348,293
false
null
package com.iwayee.exam.api.comp import com.iwayee.exam.define.SexType import io.vertx.core.json.JsonArray data class User( var id: Int = 0, var sex: Int = SexType.MALE.ordinal, var scores: Int = 0, var username: String = "", var password: String = "", var nick: String = "", var wx_nick: String = "", var token: String = "", var wx_token: String = "", var ip: String = "", var phone: String = "", var email: String = "", var create_at: String = "", ) { }
0
Kotlin
0
1
8e5195935a618d60ebadbf6a37812cdad0d7d3c6
562
riki-kotlin
MIT License