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
thread/src/commonMain/kotlin/pw/binom/thread/FreezedStack.kt
dragossusi
277,504,821
true
{"C": 13518997, "Kotlin": 569853, "C++": 546364, "Shell": 86}
package pw.binom.thread import pw.binom.AppendableQueue import pw.binom.PopResult import pw.binom.atomic.AtomicInt import pw.binom.atomic.AtomicReference import pw.binom.doFreeze class FreezedStack<T> { val size: Int get() = _size.value fun clear() { lock.use { _size.value = 0 top.value = null bottom.value = null } } private val lock = Lock() private val _size = AtomicInt(0) private inner class Item(val value: T, next: Item?, back: Item?) { val next = AtomicReference(next) val back = AtomicReference(back) } private val top = AtomicReference<Item?>(null) private val bottom = AtomicReference<Item?>(null) fun pushFirst(value: T) { lock.use { val i = Item(value, next = bottom.value, back = null).doFreeze() if (bottom.value == null) bottom.value = i top.value?.back?.value = i top.value = i _size.increment() } } fun pushLast(value: T) { lock.use { val i = Item(value, next = null, back = bottom.value).doFreeze() if (top.value == null) top.value = i bottom.value = i _size.increment() } } private fun privatePopFirst(): T { val item = top.value ?: throw IllegalStateException("Stack is empty") top.value = item.next.value if (bottom.value == item) bottom.value = null _size.decrement() return item.value } fun popFirst(): T = lock.use { privatePopFirst() } private fun privatePopLast(): T { val item = bottom.value ?: throw IllegalStateException("Stack is empty") bottom.value = item.back.value if (top.value == item) top.value = null _size.decrement() return item.value } fun popLast(): T = lock.use { privatePopLast() } fun peekFirst(): T { val item = top.value ?: throw NoSuchElementException() return item.value } fun peekLast(): T { val item = bottom.value ?: throw NoSuchElementException() return item.value } val isEmpty: Boolean get() = top.value == null fun asFiFoQueue() = object : AppendableQueue<T> { override val size: Int get() = [email protected] override fun pop(dist: PopResult<T>) { lock.use { if (isEmpty) dist.clear() else dist.set(privatePopLast()) } } override val isEmpty: Boolean get() = [email protected] override fun push(value: T) { pushFirst(value) } override fun pop(): T = popLast() override fun peek(): T = peekLast() init { doFreeze() } } fun asLiFoQueue() = object : AppendableQueue<T> { override val size: Int get() = [email protected] override fun pop(dist: PopResult<T>) { lock.use { if (isEmpty) dist.clear() else dist.set(privatePopFirst()) } } override val isEmpty: Boolean get() = [email protected] override fun push(value: T) { pushFirst(value) } override fun pop(): T = popFirst() override fun peek(): T = peekFirst() init { doFreeze() } } init { doFreeze() } }
0
null
0
0
d16040b0f0d340104194014fc174858244684813
3,664
pw.binom.io
Apache License 2.0
service-image/src/main/kotlin/io/net/image/config/SentinelRule.kt
spcookie
671,080,496
false
null
package io.net.image.config import com.alibaba.csp.sentinel.slots.block.RuleConstant import com.alibaba.csp.sentinel.slots.block.flow.FlowRule import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager import org.springframework.context.ApplicationStartupAware import org.springframework.core.metrics.ApplicationStartup import org.springframework.stereotype.Component /** *@author Augenstern *@since 2023/7/28 */ @Component class SentinelRule : ApplicationStartupAware { companion object { const val IMG = "img" const val ST = "st" } init { flowRule() } private fun flowRule() { val flowRules = buildList { add( FlowRule().apply { resource = IMG count = 0.5 grade = RuleConstant.FLOW_GRADE_QPS controlBehavior = RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER maxQueueingTimeMs = 1000 * 1 } ) add( FlowRule().apply { resource = ST count = 0.5 grade = RuleConstant.FLOW_GRADE_QPS controlBehavior = RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER maxQueueingTimeMs = 1000 * 2 } ) } FlowRuleManager.loadRules(flowRules) } override fun setApplicationStartup(applicationStartup: ApplicationStartup) {} }
0
Kotlin
0
0
9940ffc5f0f87f627681c9bb9868ff38c2237a0a
1,491
qq-robot
Apache License 2.0
app/src/main/java/com/precopia/rxtracker/view/edittimeview/buildlogic/EditTimeLogicFactory.kt
DavidPrecopia
243,413,607
false
null
package com.precopia.rxtracker.view.edittimeview.buildlogic import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.precopia.domain.repository.ITimeStampRepoContract import com.precopia.rxtracker.util.IUtilParseDateTime import com.precopia.rxtracker.util.IUtilSchedulerProviderContract import com.precopia.rxtracker.view.edittimeview.EditTimeLogic import io.reactivex.rxjava3.disposables.CompositeDisposable class EditTimeLogicFactory( private val repo: ITimeStampRepoContract, private val utilSchedulerProvider: IUtilSchedulerProviderContract, private val disposable: CompositeDisposable, private val utilParseDateTime: IUtilParseDateTime ): ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T: ViewModel?> create(modelClass: Class<T>): T { return EditTimeLogic(repo, utilSchedulerProvider, disposable, utilParseDateTime) as T } }
0
Kotlin
0
0
4209c7c951820f91b84e184415e4cba2ac986018
953
RxTracker
Apache License 2.0
core/src/main/java/com/android/appengine/router/RouterExtend.kt
devin1014
384,307,844
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "INI": 2, "Proguard": 3, "Kotlin": 57, "XML": 24, "Java": 1}
package com.android.appengine.router import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Parcelable import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import com.alibaba.android.arouter.facade.Postcard import com.alibaba.android.arouter.launcher.ARouter import java.io.Serializable import kotlin.reflect.KClass // --------------------------------------------------------------------- // ---- Service // --------------------------------------------------------------------- fun <T : Any> getAppService(service: KClass<out T>): T = getAppService(service.java) fun <T> getAppService(service: Class<out T>): T = ARouter.getInstance().navigation(service) // --------------------------------------------------------------------- // ---- Extras // --------------------------------------------------------------------- fun Postcard.transferPendingData(intent: Intent): Postcard { if (intent.data != null) { withParcelable(Router.EXTRA_KEY_PENDING_DATA, intent.data) } return this } fun Postcard.transferExtraParams(bundle: Bundle?): Postcard { if (bundle != null && bundle.size() > 0) { for (key in bundle.keySet()) { // ignore chrome browser data. if (key.startsWith("org.chromium")) continue if (key.startsWith("com.android.browser")) continue if (key.startsWith(Intent.EXTRA_REFERRER)) continue bundle.get(key)?.run { setPostcardData(this@transferExtraParams, key, this) } } } return this } fun Postcard.transferExtraParams(routerInfo: RouterInfo?): Postcard { if (routerInfo != null) { setPostcardData(this@transferExtraParams, Router.EXTRA_KEY_ROUTER_INFO, routerInfo) if (routerInfo.params.isNotEmpty()) { for ((key, value) in routerInfo.params) { // ignore chrome browser data. if (key.startsWith("org.chromium")) continue if (key.startsWith("com.android.browser")) continue if (key.startsWith(Intent.EXTRA_REFERRER)) continue setPostcardData(this@transferExtraParams, key, value) } } } return this } private fun setPostcardData(postcard: Postcard, key: String, value: Any?) { if (value == null) return when (value) { is Byte -> postcard.withByte(key, value) is Int -> postcard.withInt(key, value) is Float -> postcard.withFloat(key, value) is Double -> postcard.withDouble(key, value) is Long -> postcard.withLong(key, value) is Char -> postcard.withChar(key, value) is String -> postcard.withString(key, value) is Bundle -> postcard.withBundle(key, value) is Serializable -> postcard.withSerializable(key, value) is Parcelable -> postcard.withParcelable(key, value) else -> postcard.withObject(key, value) } } // --------------------------------------------------------------------- // ---- Navigate // --------------------------------------------------------------------- fun Activity.buildActivity(path: String, pendingData: Boolean = false) { val postcard = ARouter.getInstance().build(path) if (pendingData) postcard.transferPendingData(intent) postcard .transferExtraParams(intent.extras) .withString(Router.EXTRA_KEY_PATH, path) .navigation() } fun Activity.buildActivity(lambda: RouterInfo.() -> Unit) { buildActivity(RouterInfo().apply(lambda)) } fun Activity.buildActivity(info: RouterInfo) { ARouter.getInstance() .build(info.activity) .transferExtraParams(intent.extras) .transferExtraParams(info) .withString(Router.EXTRA_KEY_PATH, info.activity) .navigation() } fun <T : Fragment> FragmentActivity.buildFragment(path: String): T? { return ARouter.getInstance() .build(path) .transferExtraParams(intent.extras) .withString(Router.EXTRA_KEY_PATH, path) .navigation() as? T }
0
Kotlin
0
0
759f46a6d8faab6bb5fd045616f0ba4cdc69b26c
4,076
AppEngine
Apache License 2.0
app/src/main/java/com/example/movplayv3/utils/ImageUrlParser.kt
Aldikitta
514,876,509
false
{"Kotlin": 850016}
package com.example.movplayv3.utils import android.util.Size import com.example.movplayv3.data.model.ImagesConfig import kotlin.math.abs class ImageUrlParser(private val imagesConfig: ImagesConfig) { private val secureBaseUrl = imagesConfig.secureBaseUrl private val backdropDimensions = convertCodes(imagesConfig.backdropSizes).distinct() private val logoDimensions = convertCodes(imagesConfig.logoSizes).distinct() private val posterDimensions = convertCodes(imagesConfig.posterSizes).distinct() private val profileDimensions = convertCodes(imagesConfig.profileSizes).distinct() private val stillDimensions = convertCodes(imagesConfig.stillSizes).distinct() fun getImageUrl( path: String?, type: ImageType, preferredSize: Size? = null, strategy: MatchingStrategy = MatchingStrategy.FirstBiggerWidth ): String? { val source = when (type) { ImageType.Backdrop -> backdropDimensions ImageType.Logo -> logoDimensions ImageType.Poster -> posterDimensions ImageType.Profile -> profileDimensions ImageType.Still -> stillDimensions } return urlFromSource(source, path, preferredSize, strategy) } private fun urlFromSource( source: List<Dimension>, path: String?, preferredSize: Size?, strategy: MatchingStrategy = MatchingStrategy.FirstBiggerWidth ): String? { if (path == null) { return null } if (preferredSize == null) { return createSecureUrl(secureBaseUrl, Dimension.Original, path) } val preferredDimension = when (strategy) { MatchingStrategy.FirstBiggerWidth -> { source.filterIsInstance<Dimension.Width>() .firstOrNull { dimension -> dimension.value >= preferredSize.width } } MatchingStrategy.FirstBiggerHeight -> { source.filterIsInstance<Dimension.Height>() .firstOrNull { dimension -> dimension.value >= preferredSize.height } } MatchingStrategy.LowestWidthDiff -> { source.filterIsInstance<Dimension.Width>().map { dimension -> dimension to abs(preferredSize.width - dimension.value) }.minByOrNull { (_, delta) -> delta }?.first } MatchingStrategy.LowestHeightDiff -> { source.filterIsInstance<Dimension.Height>().map { dimension -> dimension to abs(preferredSize.height - dimension.value) }.minByOrNull { (_, delta) -> delta }?.first } } ?: Dimension.Original return createSecureUrl(secureBaseUrl, preferredDimension, path) } private sealed class Dimension(val code: String) { object Original : Dimension(code = "original") data class Width(val value: Int) : Dimension(code = code) { companion object { const val code = "w" } } data class Height(val value: Int) : Dimension(code = code) { companion object { const val code = "h" } } fun asCode() = when (this) { is Width -> "${Width.code}${this.value}" is Height -> "${Height.code}${this.value}" is Original -> "original" } } private fun convertCodes(codes: List<String>): List<Dimension> { return codes.mapNotNull { code -> when { code.contains(Dimension.Original.code) -> Dimension.Original code.contains(Dimension.Width.code) -> getValueFromCode(code)?.let { value -> Dimension.Width(value) } code.contains(Dimension.Height.code) -> getValueFromCode(code)?.let { value -> Dimension.Height(value) } else -> null } } } private fun getValueFromCode(code: String): Int? { return code.filter { char -> char.isDigit() }.toIntOrNull() } private fun createSecureUrl(secureBaseUrl: String, dimension: Dimension, path: String): String { return "${secureBaseUrl}${dimension.asCode()}${path}" } enum class MatchingStrategy { FirstBiggerWidth, FirstBiggerHeight, LowestWidthDiff, LowestHeightDiff } enum class ImageType { Backdrop, Logo, Poster, Profile, Still } }
1
Kotlin
12
77
8344e2a5cf62289c2b56494bf4ecd5227e26de31
4,509
MovplayV3
Apache License 2.0
idea/idea-completion/testData/basic/common/parameterNameAndType/URLConnection.kt
JakeWharton
99,388,807
true
null
import java.net.URLConnection fun foo(url<caret>){} // EXIST_JAVA_ONLY: { itemText: "urlConnection: URLConnection", tailText: " (java.net)" } // ABSENT: { itemText: "urlconnection: URLConnection" }
1
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
200
kotlin
Apache License 2.0
authentication/src/main/kotlin/com/mdelbel/android/firebase/authentication/repository/Authenticator.kt
matiasdelbel
207,588,056
false
null
package com.mdelbel.android.firebase.authentication.repository import androidx.lifecycle.LiveData import com.google.firebase.auth.AuthCredential import com.mdelbel.android.firebase.authentication.AuthenticationState interface Authenticator { fun authenticate(credential: AuthCredential): LiveData<AuthenticationState> fun executeIf(isAuthenticatedUser: () -> Unit, isGuessUSer: () -> Unit) fun signOut() }
1
Kotlin
0
0
201e8866663fe9d55f815213354e08c2217623bc
422
android-poc-firebase-authentication
Apache License 2.0
app/src/main/java/dev/amits/cleanarchitecturenewsapp/data/api/NewsService.kt
amitsahoo1998
591,703,105
false
null
package dev.amits.cleanarchitecturenewsapp.data.api import dev.amits.cleanarchitecturenewsapp.data.model.NewsResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface NewsService { @GET("/v2/top-headlines") suspend fun getHeading( @Query("country") country: String , @Query("page") page: Int, @Query("apiKey") apiKey : String = dev.amits.cleanarchitecturenewsapp.BuildConfig.API_KEY ) : Response<NewsResponse> @GET("/v2/top-headlines") suspend fun getSearchedTopHeadlines( @Query("country") country:String, @Query("q") searchQuery:String, @Query("page") page:Int, @Query("apiKey") apiKey:String = dev.amits.cleanarchitecturenewsapp.BuildConfig.API_KEY ) : Response<NewsResponse> }
0
Kotlin
0
0
7100ec6b7ec15f287febffe76a28b1433eee8833
866
News-Apps-MVVM-Clean-Architecture
MIT License
app/src/main/java/com/mayberry/recipedemo/fragment/recipe/adapter/BindingAdapter.kt
Mayberryqvq
654,453,008
false
null
package com.mayberry.recipedemo.fragment.recipe.adapter import android.widget.ImageView import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide import com.google.android.material.chip.Chip import com.mayberry.recipedemo.R object BindingAdapter { @JvmStatic @BindingAdapter("loadImageWithUrl") fun loadImageWithUrl(imageView: ImageView, url: String) { //将url对应的图片下载下来,显示到imageView上 //Glide Glide.with(imageView).load(url).into(imageView) } @JvmStatic @BindingAdapter("loadIngredientImageWithName") fun loadIngredientImageWithName(imageView: ImageView, name: String) { //将url对应的图片下载下来,显示到imageView上 //Glide val imageBaseUrl = "https://spoonacular.com/cdn/ingredients_250x250/" Glide.with(imageView).load(imageBaseUrl + name).placeholder(R.drawable.ic_launcher_background).into(imageView) } @JvmStatic @BindingAdapter("changeStatus") fun changeStatus(chip: Chip, status: Boolean) { chip.isSelected = status } }
0
Kotlin
0
1
2cfa734599efe2607b1b7444380d8fd19a935210
1,043
recipeDemo
Apache License 2.0
nodejs_socketIO_flutter/flutter_socketio/android/app/src/main/kotlin/com/example/flutter_socketio/MainActivity.kt
HeroLive
414,979,558
false
{"C++": 256280, "CMake": 119463, "Dart": 93058, "HTML": 58105, "C": 11010, "Swift": 6060, "JavaScript": 2309, "Kotlin": 2045, "Objective-C": 570}
package com.example.flutter_socketio import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
C++
5
1
230b89a65bb0e1a63d592f34ac0fb829cc4eab3d
133
Flutter_Radiation
MIT License
ndarray/ndarray-webgpu/src/commonMain/kotlin/io/kinference/ndarray/arrays/WebGPUDataType.kt
isomethane
591,976,225
false
null
package io.kinference.ndarray.arrays enum class WebGPUDataType(val wgslType: String, val sizeBytes: Int) { BOOLEAN("i32", 4), INT32("i32", 4), UINT32("u32", 4), FLOAT32("f32", 4); fun wgslMinValue(): String = when (this) { BOOLEAN -> "false" INT32 -> "i32(-0x80000000)" UINT32 -> "0u" FLOAT32 -> "-0x1.fffffep+127f" } fun wgslMaxValue(): String = when (this) { BOOLEAN -> "true" INT32 -> "0x7fffffffi" UINT32 -> "0xffffffffu" FLOAT32 -> "0x1.fffffep+127f" } }
0
Kotlin
0
0
3056bc4ebcd03a86d0ee9ef093cdac81491325b2
559
kinference
Apache License 2.0
src/main/kotlin/vendingmachine/states/VmSelectionState.kt
Arya-Abhishek
808,936,485
false
{"Kotlin": 13191}
package org.example.vendingmachine.states import org.example.vendingmachine.VendingMachine import org.example.vendingmachine.entities.UserInput import org.example.vendingmachine.inventory.Inventory class VmSelectionState( private val vendingMachine: VendingMachine ) : IVmStates { override fun insertCoinBtn() { println("Not supported in this state") } override fun insertCoin() { println("Not supported in this state") } override fun selectProductBtn() { println("In selection state, select the product") } override fun selectProduct() { // user given productCode in `userInput.productCode` as string // NOTE: Before, selectProduct is called, user had given the product code vendingMachine.userInput?.productCode ?. let { productCode -> val currentProduct = vendingMachine.inventory.getProduct(productCode) val currentProductQuantity = vendingMachine.inventory.getProductQuantity(productCode) when { currentProduct == null -> { println("Product code not valid") vendingMachine.changeState(VmIdleState(vendingMachine)) } currentProductQuantity == 0 -> { println("Product out of stock") refund() vendingMachine.changeState(VmIdleState(vendingMachine)) } vendingMachine.userInput!!.totalAmount >= currentProduct.price -> { vendingMachine.inventory.updateProductQuantity(productCode, currentProductQuantity - 1) vendingMachine.changeState(VmDispenseState(vendingMachine)) } else -> { println("Insufficient amount, please insert more coins") vendingMachine.changeState(VmAwaitingPaymentState(vendingMachine)) } } } ?: run { println("Product code not valid") vendingMachine.changeState(VmIdleState(vendingMachine)) } } override fun pressCancelBtn() { vendingMachine.userInput ?. let { refund() } vendingMachine.changeState(VmIdleState(vendingMachine)) } override fun refund() { // will give refund here: dispense all user inserted coins println("Refund Total amount: ${vendingMachine.userInput?.totalAmount}") vendingMachine.userInput?.coins?.map { (coin, qty) -> println("Refund Coin: $coin, Quantity: $qty") } } override fun dispenseProduct() { println("Not supported in this state") } }
0
Kotlin
0
0
08a32df46eb8ec74d1957df1329b9e6832579d83
2,686
vending-machine
MIT License
shared/src/androidMain/kotlin/com/aglushkov/wordteacher/shared/general/Logger.kt
soniccat
302,971,014
false
{"Kotlin": 1159793, "Go": 188960, "Swift": 38695, "TypeScript": 29600, "Dockerfile": 5502, "JavaScript": 3131, "Makefile": 3016, "Shell": 2690, "Ruby": 1740, "HTML": 897, "Java": 872, "SCSS": 544, "C": 59}
package com.aglushkov.wordteacher.shared.general import co.touchlab.kermit.LoggerConfig import com.aglushkov.wordteacher.shared.analytics.Analytics actual class Logger { actual companion object { actual var analytics: Analytics? = null } actual fun setupDebug(config: LoggerConfig) { co.touchlab.kermit.Logger.setMinSeverity(config.minSeverity) co.touchlab.kermit.Logger.setLogWriters(config.logWriterList) } }
0
Kotlin
1
11
3c1cb6b58c87a20ee29449f87ccc6cad4b0aeb23
453
WordTeacher
MIT License
meistercharts-commons/src/commonMain/kotlin/it/neckar/open/i18n/TextResolver.kt
Neckar-IT
599,079,962
false
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
package it.neckar.open.i18n /** * A service that resolves texts - for a given locale. * * Attention: Does *not* replace parameters! Just resolves texts */ fun interface TextResolver { /** * Resolves the text for the given key and locale */ fun resolve( key: TextKey, i18nConfiguration: I18nConfiguration ): String? }
3
Kotlin
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
342
meistercharts
Apache License 2.0
src/test/java/net/sourceforge/jenesis4java/j4jik/AccessModifierTest.kt
erikfk
133,113,449
false
{"Maven POM": 1, "Text": 1, "YAML": 1, "Markdown": 1, "Java": 1, "Kotlin": 31}
package net.sourceforge.jenesis4java.j4jik import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test internal class AccessModifierTest { @Test fun test() { assertEquals("", AccessModifier.PACKAGE.keyword()) assertEquals("private", AccessModifier.PRIVATE.keyword()) assertEquals("protected", AccessModifier.PROTECTED.keyword()) assertEquals("public", AccessModifier.PUBLIC.keyword()) } }
1
null
1
1
6791061ab9f7a08d3ee30f41c6057d158d625b13
450
jenesis4javaInKotlin
Apache License 2.0
kotok/src/io/github/devcrocod/kotok/LazyEncodingRegistry.kt
devcrocod
802,025,652
false
{"Kotlin": 70681}
package io.github.devcrocod.kotok import io.github.devcrocod.kotok.api.Encoding import io.github.devcrocod.kotok.api.EncodingType import io.github.devcrocod.kotok.api.ModelType internal class LazyEncodingRegistry : AbstractEncodingRegistry() { override fun encoding(encodingName: String): Encoding? { EncodingType.of(encodingName)?.let { type: EncodingType -> this.addEncoding(type) } return super.encoding(encodingName) } override fun encoding(encodingType: EncodingType): Encoding { addEncoding(encodingType) return super.encoding(encodingType) } override fun encodingForModel(modelType: ModelType): Encoding { addEncoding(modelType.encodingType) return super.encodingForModel(modelType) } }
3
Kotlin
0
0
d691c9f9e390017ad9b74b01dcedf46780ecc570
791
Kotok
Apache License 2.0
examples/CustomEntitlementComputationSample/app/src/main/java/com/revenuecat/sample/main/CustomerInfoDetailScreen.kt
RevenueCat
127,346,826
false
null
package com.revenuecat.sample.main import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.revenuecat.sample.data.CustomerInfoEvent private const val JSON_INDENT_SPACES = 4 @OptIn(ExperimentalMaterial3Api::class) @Composable fun CustomerInfoDetailScreen(event: CustomerInfoEvent) { Scaffold( topBar = { TopAppBar( title = { Text(text = "Customer Info Detail") }, ) }, ) { Box(modifier = Modifier.padding(it)) { Column( modifier = Modifier .fillMaxSize() .background(color = Color.White), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { Text( text = event.customerInfo.rawData.toString(JSON_INDENT_SPACES), modifier = Modifier.padding(16.dp), ) } } } }
30
null
52
253
dad31133777389a224e9a570daec17f5c4c795ca
1,653
purchases-android
MIT License
spring-graalvm-native-samples/kotlin-webmvc/src/test/kotlin/com/example/demo/KotlinCoroutinesApplicationTests.kt
dsyer
208,247,467
false
null
package com.example.demo import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class ActuatorDemoApplicationTests { @Test fun contextLoads() { } }
3
null
1
4
c49471318582b4e4a20cbb3bc1b3f28f6b7b6aaf
210
spring-native
Apache License 2.0
app/app/src/main/java/xyz/mirage/app/presentation/ui/main/home/list/HomeScreen.kt
sentrionic
378,704,735
false
null
package xyz.mirage.app.presentation.ui.main.home.list import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Scaffold import androidx.compose.material.ScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.navigation.NavController import coil.ImageLoader import coil.annotation.ExperimentalCoilApi import kotlinx.coroutines.launch import xyz.mirage.app.presentation.core.theme.AppTheme import xyz.mirage.app.presentation.navigation.Screen import xyz.mirage.app.presentation.ui.main.home.list.PostListEvent.* import xyz.mirage.app.presentation.ui.main.home.list.components.PostList import xyz.mirage.app.presentation.ui.main.home.list.components.TopBar import xyz.mirage.app.presentation.ui.main.refresh.RefreshViewManager import xyz.mirage.app.presentation.ui.shared.CreatePostFab import xyz.mirage.app.presentation.ui.shared.NavBar @ExperimentalCoilApi @Composable fun HomeScreen( isDarkTheme: Boolean, isNetworkAvailable: Boolean, navController: NavController, state: PostListState, onTriggerEvent: (PostListEvent) -> Unit, scaffoldState: ScaffoldState, refreshViewManager: RefreshViewManager, authId: String, imageLoader: ImageLoader, ) { val coroutineScope = rememberCoroutineScope() val listState = rememberLazyListState() refreshViewManager.state.value.let { value -> value.postToRefresh?.let { post -> onTriggerEvent(UpdateListEvent(post)) } value.postToRemove?.let { id -> onTriggerEvent(RemoveItemEvent(id)) } value.postToAdd?.let { post -> onTriggerEvent(AddPostToListEvent(post)) } } AppTheme( displayProgressBar = state.isLoading, scaffoldState = scaffoldState, darkTheme = isDarkTheme, isNetworkAvailable = isNetworkAvailable, dialogQueue = state.queue, onRemoveHeadMessageFromQueue = { onTriggerEvent(OnRemoveHeadFromQueue) } ) { Scaffold( topBar = { TopBar( onScrollToTop = { coroutineScope.launch { listState.animateScrollToItem(0) } }, isDarkTheme = isDarkTheme, ) }, floatingActionButton = { CreatePostFab( handleClick = { navController.navigate(Screen.CreatePost.route) } ) }, bottomBar = { NavBar( navController = navController, ) } ) { PostList( state = state, navController = navController, listState = listState, isDarkTheme = isDarkTheme, onTriggerEvent = onTriggerEvent, authId = authId, imageLoader = imageLoader ) } } }
0
Kotlin
0
1
38f8a669cdb6f8a804fae9320bf645dd33ee0a7b
3,085
Mirage
MIT License
app/src/main/java/ca/on/hojat/gamenews/core/data/api/igdbcalypse/serialization/ApicalypseSerializer.kt
hojat72elect
574,228,468
false
null
package ca.hojat.gamehub.core.data.api.igdbcalypse.serialization interface ApicalypseSerializer { fun serialize(clazz: Class<*>): String }
0
Kotlin
8
4
b1c07551e90790ee3d273bc4c0ad3a5f97f71202
144
GameHub
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/SquareT.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.SquareT: ImageVector get() { if (_squareT != null) { return _squareT!! } _squareT = Builder(name = "SquareT", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(5.0f, 5.0f) horizontalLineToRelative(14.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(-6.0f) verticalLineToRelative(12.0f) horizontalLineToRelative(-2.0f) lineTo(11.0f, 7.0f) horizontalLineToRelative(-6.0f) verticalLineToRelative(-2.0f) close() moveTo(24.0f, 3.0f) verticalLineToRelative(21.0f) lineTo(0.0f, 24.0f) lineTo(0.0f, 3.0f) curveTo(0.0f, 1.346f, 1.346f, 0.0f, 3.0f, 0.0f) horizontalLineToRelative(18.0f) curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f) close() moveTo(22.0f, 3.0f) curveToRelative(0.0f, -0.552f, -0.449f, -1.0f, -1.0f, -1.0f) lineTo(3.0f, 2.0f) curveToRelative(-0.551f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f) verticalLineToRelative(19.0f) horizontalLineToRelative(20.0f) lineTo(22.0f, 3.0f) close() } } .build() return _squareT!! } private var _squareT: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,375
icons
MIT License
core-network/src/main/java/com/zavaitar/core/network/model/UrlXXXXX.kt
hybrid-developer
240,302,035
false
null
package com.zavaitar.core.network.model import com.google.gson.annotations.SerializedName import androidx.annotation.Keep @Keep data class UrlX( @SerializedName("display_url") val displayUrl: String, @SerializedName("expanded_url") val expandedUrl: String, @SerializedName("indices") val indices: List<Int>, @SerializedName("url") val url: String )
0
Kotlin
0
0
98d454977cc2db035f7e1567448de8977d054b50
367
TwitterFeed
Apache License 2.0
db-async-common/src/main/kotlin/com/github/mauricio/async/db/pool/ConnectionPool.kt
KotlinPorts
77,183,383
false
null
/* * Copyright 2013 <NAME> * * <NAME> licenses this file to you 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.mauricio.async.db.pool import com.github.mauricio.async.db.util.ExecutorServiceUtils import com.github.mauricio.async.db.QueryResult import com.github.mauricio.async.db.Connection import com.github.elizarov.async.suspendable import kotlin.coroutines.ContinuationDispatcher import kotlin.coroutines.suspendCoroutine /** * * Pool specialized in database connections that also simplifies connection handling by * implementing the [[com.github.mauricio.async.db.Connection]] trait and saving clients from having to implement * the "give back" part of pool management. This lets you do your job without having to worry * about managing and giving back connection objects to the pool. * * The downside of this is that you should not start transactions or any kind of long running process * in this object as the object will be sent back to the pool right after executing a query. If you * need to start transactions you will have to take an object from the pool, do it and then give it * back manually. * * @param factory * @param configuration */ class ConnectionPool<T : Connection>( factory: ObjectFactory<T>, configuration: PoolConfiguration, val executionContext: ContinuationDispatcher? = ExecutorServiceUtils.CachedExecutionContext ) : SingleThreadedAsyncObjectPool<T>(factory, configuration), Connection { /** * * Closes the pool, you should discard the object. * * @return */ override suspend fun disconnect() = suspendable<Connection> { if (isConnected) { close() } this@ConnectionPool } /** * * Always returns an empty map. * * @return */ override suspend fun connect() = suspendCoroutine<Connection> { it.resume(this) } override val isConnected: Boolean get() = !this.isClosed() /** * * Picks one connection and runs this query against it. The query should be stateless, it should not * start transactions and should not leave anything to be cleaned up in the future. The behavior of this * object is undefined if you start a transaction from this method. * * @param query * @return */ override suspend fun sendQuery(query: String): QueryResult = this.use(executionContext, { it.sendQuery(query) }) /** * * Picks one connection and runs this query against it. The query should be stateless, it should not * start transactions and should not leave anything to be cleaned up in the future. The behavior of this * object is undefined if you start a transaction from this method. * * @param query * @param values * @return */ override suspend fun sendPreparedStatement(query: String, values: List<Any?>): QueryResult = this.use(executionContext, { it.sendPreparedStatement(query, values) }) /** * * Picks one connection and executes an (asynchronous) function on it within a transaction block. * If the function completes successfully, the transaction is committed, otherwise it is aborted. * Either way, the connection is returned to the pool on completion. * * @param f operation to execute on a connection * @return result of f, conditional on transaction operations succeeding */ override suspend fun <A> inTransaction(dispatcher: ContinuationDispatcher?, f: suspend (conn: Connection) -> A): A = this.use(executionContext, { it.inTransaction(dispatcher ?: executionContext, f) }) }
5
Kotlin
2
23
942ebfeee4601f9580916ed551fcfd2f8084d701
4,174
pooled-client
Apache License 2.0
src/main/kotlin/com/github/ivan_osipov/clabo/dsl/LongPollingInteraction.kt
ivan-osipov
92,181,671
false
null
package com.github.ivan_osipov.clabo.dsl import com.github.ivan_osipov.clabo.api.internal.TelegramApiInteraction import com.github.ivan_osipov.clabo.dsl.internal.contextProcessing.ContextProcessor import org.slf4j.Logger import org.slf4j.LoggerFactory class LongPollingInteraction(private val telegramApiUrl: String) : Interaction { private val logger: Logger = LoggerFactory.getLogger(LongPollingInteraction::class.java) override fun run(context: CommonBotContext) : BotResults { val api = TelegramApiInteraction(telegramApiUrl) context.sender = api context.receiver = api val contextProcessor = ContextProcessor(context, api) logger.info("Context processing is starting") return contextProcessor.run() } }
31
Kotlin
3
6
943583bce73aad8479c1be8d7e6f6fe74807058e
773
Clabo
Apache License 2.0
project-system-gradle/src/com/android/tools/idea/gradle/project/sync/issues/processor/SuppressUnsupportedSdkVersionPropertyProcessor.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.android.tools.idea.gradle.project.sync.issues.processor import com.android.SdkConstants.FN_GRADLE_PROPERTIES import com.android.tools.idea.gradle.dsl.api.ProjectBuildModel import com.android.tools.idea.gradle.project.sync.GradleSyncInvoker import com.android.tools.idea.gradle.project.sync.requestProjectSync import com.google.wireless.android.sdk.stats.GradleSyncStats.Trigger.TRIGGER_PROJECT_MODIFIED import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewDescriptor import org.jetbrains.annotations.VisibleForTesting class SuppressUnsupportedSdkVersionPropertyProcessor( val project: Project, private val sdkVersionsToSuppress: String, ) : BaseRefactoringProcessor(project) { public override fun createUsageViewDescriptor(usages: Array<UsageInfo>): UsageViewDescriptor { return object : UsageViewDescriptor { override fun getCodeReferencesText(usagesCount: Int, filesCount: Int): String { return "References to be updated or added: ${UsageViewBundle.getReferencesString(usagesCount, filesCount)}" } override fun getElements(): Array<PsiElement> { return PsiElement.EMPTY_ARRAY } override fun getProcessedElementsHeader(): String { return "Updating or adding android.suppressUnsupportedCompileSdk gradle property" } } } public override fun findUsages(): Array<UsageInfo> { val baseDir = myProject.baseDir ?: return emptyArray() val gradlePropertiesVirtualFile = baseDir.findChild("gradle.properties") if (gradlePropertiesVirtualFile != null && gradlePropertiesVirtualFile.exists()) { val gradlePropertiesPsiFile = PsiManager.getInstance(myProject).findFile(gradlePropertiesVirtualFile) if (gradlePropertiesPsiFile is PropertiesFile) { val psiElement = when(val property = gradlePropertiesPsiFile.findPropertyByKey("android.suppressUnsupportedCompileSdk")) { null -> gradlePropertiesPsiFile else -> property.psiElement } return arrayOf(UsageInfo(psiElement)) } } else if (baseDir.exists()) { val baseDirPsiDirectory = PsiManager.getInstance(myProject).findDirectory(baseDir) if (baseDirPsiDirectory is PsiElement) { return arrayOf(UsageInfo(baseDirPsiDirectory)) } } return emptyArray() } public override fun performRefactoring(usages: Array<UsageInfo>) { updateProjectBuildModel(usages) GradleSyncInvoker.getInstance().requestProjectSync(myProject, TRIGGER_PROJECT_MODIFIED) } @VisibleForTesting fun updateProjectBuildModel(usages: Array<UsageInfo>) { usages.forEach { usage -> val propertiesFile = when (val element = usage.element) { is PsiFile -> element as? PropertiesFile is PsiDirectory -> (element.findFile(FN_GRADLE_PROPERTIES) ?: element.createFile(FN_GRADLE_PROPERTIES)).let { (it as? PropertiesFile ?: return@forEach) } is PsiElement -> element.containingFile as? PropertiesFile else -> return@forEach } val existing = propertiesFile?.findPropertyByKey("android.suppressUnsupportedCompileSdk") if (existing != null) { existing.setValue(sdkVersionsToSuppress) } else { propertiesFile?.addProperty("android.suppressUnsupportedCompileSdk", sdkVersionsToSuppress) } } val projectBuildModel = ProjectBuildModel.get(myProject) projectBuildModel.applyChanges() } public override fun getCommandName(): String { return "Updating or adding android.suppressUnsupportedCompileSdk gradle property" } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
4,554
android
Apache License 2.0
HandyHealthLog/app/src/main/java/sss/handyhealthlog/views/EditEventActivity.kt
ctmobiledev
249,363,264
false
null
package sss.handyhealthlog.views import android.content.DialogInterface import android.graphics.Color import android.os.Bundle import android.view.View import android.widget.* import android.widget.AdapterView.OnItemSelectedListener import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders import kotlinx.android.synthetic.main.activity_edit_event.* import sss.handyhealthlog.R import sss.handyhealthlog.models.HealthLogModel import sss.handyhealthlog.viewmodels.HealthLogViewModel import java.lang.Float.parseFloat import java.text.SimpleDateFormat import java.util.* class EditEventActivity : AppCompatActivity() { // Globals private lateinit var healthLogViewModel: HealthLogViewModel private var currDataType: String = String() private var proceedToSave: Boolean = false // Determined if record is complete override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit_event) // Users won't need to alter this, but this will confirm the new record is "fresh" DisableEditText(edtTimestamp) // Spinner setup // Create an ArrayAdapter using the string array and a default spinner layout // Had to do a Stop Application, then Invalidate/Restart to get the custom layout recognized. val spnDataType: Spinner = findViewById(R.id.spnDataType) ArrayAdapter.createFromResource( this, R.array.data_types_array, R.layout.datatype_spinner_item ).also { adapter -> // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // Apply the adapter to the spinner spnDataType.adapter = adapter } spnDataType.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>, view: View, pos: Int, id: Long ) { currDataType = parent.getItemAtPosition(pos).toString() // Clear previous values. edtMetric1.isEnabled = true edtMetric2.isEnabled = true edtMetric3.isEnabled = true edtMetric1.setText("") edtMetric2.setText("") edtMetric3.setText("") val labelBlack = "#000000" val labelDimmed = "#BBBBBB" lblMetric1.setTextColor(Color.parseColor(labelBlack)) lblMetric2.setTextColor(Color.parseColor(labelBlack)) lblMetric3.setTextColor(Color.parseColor(labelBlack)) // Each type triggers a different set of units. if (currDataType == "BP") { edtUnit1.setText("Systolic mmHg") edtUnit2.setText("Diastolic mmHg") edtUnit3.setText("Pulse BPM") } if (currDataType == "EXERC") { edtUnit1.setText("Minutes") edtUnit2.setText("Miles") edtUnit3.setText("Laps") } if (currDataType == "GLU") { edtUnit1.setText("mg/dL") edtUnit2.setText("") edtUnit3.setText("") edtMetric2.isEnabled = false edtMetric3.isEnabled = false lblMetric2.setTextColor(Color.parseColor(labelDimmed)) lblMetric3.setTextColor(Color.parseColor(labelDimmed)) } if (currDataType == "OTHER") { edtUnit1.setText("Value 1") edtUnit2.setText("Value 2") edtUnit3.setText("Value 3") } if (currDataType == "RX") { edtUnit1.setText("pills") edtUnit2.setText("tsp") edtUnit3.setText("dosage") } if (currDataType == "TEMP") { edtUnit1.setText("deg F") edtUnit2.setText("") edtUnit3.setText("") edtMetric2.isEnabled = false edtMetric3.isEnabled = false lblMetric2.setTextColor(Color.parseColor(labelDimmed)) lblMetric3.setTextColor(Color.parseColor(labelDimmed)) } if (currDataType == "WGT") { edtUnit1.setText("pounds") edtUnit2.setText("ounces") edtMetric3.isEnabled = false lblMetric3.setTextColor(Color.parseColor(labelDimmed)) } } override fun onNothingSelected(parent: AdapterView<*>?) { // nothing } } // Get the viewModel and, in turn, the connection to the database healthLogViewModel = ViewModelProviders.of(this).get(HealthLogViewModel::class.java) // Populate timestamp var tstest = generateTimestamp() println(">>> tstest = " + tstest) edtTimestamp.setText(generateTimestamp()) // odd...EditText controls can't be set with .text = ... btnSave.setOnClickListener { // If one or more values are left blank, make sure that's what the user really wants. var availableFields = 0 var completedFields = 0 if (lblMetric1.isEnabled) { availableFields++ if (edtMetric1.text.toString().trim() != "") { completedFields++ } } if (lblMetric2.isEnabled) { availableFields++ if (edtMetric2.text.toString().trim() != "") { completedFields++ } } if (lblMetric3.isEnabled) { availableFields++ if (edtMetric3.text.toString().trim() != "") { completedFields++ } } println(">>> availableFields = " + availableFields) println(">>> completedFields = " + completedFields) if (completedFields == 0) { val builder = AlertDialog.Builder(this) builder.setTitle("Blank Fields") builder.setMessage("You didn't fill in any data value fields. All values will show 0. " + "Are you sure you wish to save this record this way?") builder.setPositiveButton("Yes, Continue", DialogInterface.OnClickListener { dialog, id -> insertEventWithMessage() return@OnClickListener }) builder.setNegativeButton("No, Cancel", DialogInterface.OnClickListener { dialog, id -> println(">>> Save ignored") }) builder.show() } else { println(">>> All metric entry fields completed; proceedToSave is $proceedToSave") insertEventWithMessage() } } btnCancel.setOnClickListener { finish() } } private fun insertEventWithMessage() { // Parse entered values, validate var strMetric1 = edtMetric1.text.toString() var fpMetric1 = 0f fpMetric1 = try { parseFloat(strMetric1) } catch (ex: Exception) { 0f } var strMetric2 = edtMetric2.text.toString() var fpMetric2 = 0f fpMetric2 = try { parseFloat(strMetric2) } catch (ex: Exception) { 0f } var strMetric3 = edtMetric3.text.toString() var fpMetric3 = 0f fpMetric3 = try { parseFloat(strMetric3) } catch (ex: Exception) { 0f } // Get input values from UI controls // Input type mask precludes need to parse-test input values var newLogEvent: HealthLogModel = HealthLogModel( null, edtTimestamp.text.toString(), currDataType, fpMetric1, edtUnit1.text.toString(), fpMetric2, edtUnit2.text.toString(), fpMetric3, edtUnit3.text.toString(), edtLocation.text.toString().trim(), edtDescription1.text.toString().trim(), edtDescription2.text.toString().trim() ) // Call save method in viewModel healthLogViewModel.insert(newLogEvent) // Indicate completion Toast.makeText(this, "Event saved successfully", Toast.LENGTH_SHORT).show() finish() } private fun generateTimestamp(): String { val currDate = Date() val pattern = "yyyyMMdd_HHmmss" val simpleDateFormat = SimpleDateFormat(pattern) println(">>> generateTimestamp - output date is: " + simpleDateFormat.format(currDate)) return simpleDateFormat.format(currDate) } private fun DisableEditText( editText: EditText ) { val isEnabled: Boolean = false editText.isFocusable = isEnabled editText.isFocusableInTouchMode = isEnabled editText.isClickable = isEnabled editText.isLongClickable = isEnabled editText.isCursorVisible = isEnabled } }
0
Kotlin
0
0
e9fe85d6edced788c031b8f5cce14a160f052180
9,683
HandyHealthLog
Apache License 2.0
app/src/main/java/durdinstudios/wowarena/profile/CharacterListActivity.kt
FrangSierra
114,635,873
false
null
package durdinstudios.wowarena.profile import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import durdinstudios.wowarena.R import durdinstudios.wowarena.core.dagger.BaseActivity import durdinstudios.wowarena.domain.user.DeleteUserAction import durdinstudios.wowarena.domain.user.UserStore import durdinstudios.wowarena.error.ErrorHandler import durdinstudios.wowarena.misc.GridSpacingItemDecoration import durdinstudios.wowarena.misc.filterOne import durdinstudios.wowarena.misc.setGridLayoutManager import durdinstudios.wowarena.misc.toast import durdinstudios.wowarena.navigation.HomeActivity import io.reactivex.android.schedulers.AndroidSchedulers import kotlinx.android.synthetic.main.character_list_activity.* import kotlinx.android.synthetic.main.toolbar.* import mini.Dispatcher import mini.select import javax.inject.Inject class CharacterListActivity : BaseActivity() { @Inject lateinit var dispatcher: Dispatcher @Inject lateinit var userStore: UserStore @Inject lateinit var errorHandler: ErrorHandler private val adapter = CharacterAdapter(::onCharacterClick) companion object { fun newIntent(context: Context): Intent = Intent(context, CharacterListActivity::class.java) } override fun onResume() { super.onResume() toolbar.title = getString(R.string.navigation_characters) } override fun onContextItemSelected(item: MenuItem): Boolean { return when (item.order) { CharacterAdapter.DELETE_MENU_ID -> { onDeleteCharacterClick(adapter.getCharacter(item.groupId)) true } else -> super.onContextItemSelected(item) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.character_list_activity) initializeInterface() listenStoreChanges() } private fun listenStoreChanges() { userStore.flowable() .select { it.currentCharacters } .subscribe { adapter.updateCharacters(it) } .track() } private fun initializeInterface() { add_char.setOnClickListener { addNewCharacter() } players_recycler.setGridLayoutManager(this, 2, reverseLayout = false, stackFromEnd = false) players_recycler.addItemDecoration(GridSpacingItemDecoration(2, 32, true)) players_recycler.adapter = adapter registerForContextMenu(players_recycler) } private fun addNewCharacter() { startActivity(AddCharacterActivity.newIntent(this)) } private fun onDeleteCharacterClick(character: Character) { dispatcher.dispatchOnUi(DeleteUserAction(character)) userStore.flowable() .observeOn(AndroidSchedulers.mainThread()) .select { it.deleteTask } .filterOne { it.isTerminal() } .subscribe { if (it.isFailure()) { toast(errorHandler.getMessageForError(it.error!!)) } }.track() } private fun onCharacterClick(info: Character) { startActivity(HomeActivity.newIntent(this, name = info.username, realm = info.realm, region = info.region)) } }
0
null
0
6
a290ee99b7d8d78609396fe684e564a3586712b3
3,352
WoWArena
Apache License 2.0
app/src/main/java/com/example/busschedule/schedule/ScheduleDao.kt
hayasaudd
436,204,349
false
null
package com.example.busschedule.schedule import androidx.room.Dao import androidx.room.Query import com.example.busschedule.Schedule import kotlinx.coroutines.flow.Flow @Dao interface ScheduleDao { @Query("SELECT * FROM schedule ORDER BY arrival_time ASC") fun getAll(): Flow<List<Schedule>> @Query("SELECT * FROM schedule WHERE stop_name = :stopName ORDER BY arrival_time ASC") fun getByStopName(stopName:String): Flow<List<Schedule>> }
0
Kotlin
0
0
6bb011027b9fa78ff46d59567c4abcdd99f73df3
460
busscheduler
Apache License 2.0
navigation/src/main/java/com/gk/android/navigation/ArtistArgs.kt
gauravk95
337,455,111
false
null
package com.gk.android.navigation import android.os.Parcelable import androidx.annotation.Keep import kotlinx.parcelize.Parcelize @Keep @Parcelize class ArtistArgs constructor( val id: String, val name: String? = null, val disambiguation: String? = null, var isBookmarked: Boolean = false ) : Parcelable
0
Kotlin
1
0
3aa56970035eb0d7bc10d4e41d47912a98066c3b
321
android-kotlin-mvvm-clean
Apache License 2.0
app/src/main/java/com/alpriest/energystats/ui/helpers/ErrorView.kt
alpriest
606,081,400
false
{"Kotlin": 724972}
package com.alpriest.energystats.ui.helpers import android.net.http.NetworkException import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ErrorOutline import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.alpriest.energystats.R import com.alpriest.energystats.services.MissingDataException import com.alpriest.energystats.ui.settings.ColorThemeMode import com.alpriest.energystats.ui.theme.EnergyStatsTheme import kotlinx.coroutines.launch @Composable fun ErrorView(ex: Exception?, reason: String, onRetry: suspend () -> Unit, onLogout: () -> Unit) { val scrollState = rememberScrollState() val coroutineScope = rememberCoroutineScope() val uriHandler = LocalUriHandler.current Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() .padding(8.dp) .verticalScroll(scrollState) ) { Icon( Icons.Rounded.ErrorOutline, tint = Color.Red, contentDescription = "", modifier = Modifier .size(128.dp) ) Text( text = stringResource(R.string.something_went_wrong_fetching_data_from_foxess_cloud), textAlign = TextAlign.Center, modifier = Modifier.padding(bottom = 16.dp), fontSize = 16.sp ) Text( reason, textAlign = TextAlign.Center ) EqualWidthButtonList( listOf( ButtonDefinition(stringResource(R.string.retry), { coroutineScope.launch { onRetry() } }), ButtonDefinition(stringResource(R.string.foxess_cloud_status), { uriHandler.openUri("https://monitor.foxesscommunity.com/status/foxess") }), ButtonDefinition(stringResource(R.string.logout), { onLogout() }) ) ) } } @Preview @Composable fun ErrorPreview() { EnergyStatsTheme(colorThemeMode = ColorThemeMode.Dark) { ErrorView( ex = MissingDataException(), reason = "BEGIN_OBJECT was expected but got something else instead. Will try again because something else went wrong too.", onRetry = {}, onLogout = {} ) } }
8
Kotlin
3
3
89405674897a5e89b6451bfd361e8691238a8de0
3,186
EnergyStats-Android
MIT License
app/src/main/java/com/github/mbarrben/moviedb/movies/ui/composables/MoviesLoadingScreen.kt
mbarrben
30,839,916
false
null
package com.github.mbarrben.moviedb.movies.ui.composables import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.github.mbarrben.moviedb.ui.theme.MovieDbTheme @Composable fun MoviesLoadingScreen() { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { CircularProgressIndicator() } } @Preview( showBackground = true, showSystemUi = true, ) @Composable private fun DefaultPreview() { MovieDbTheme { MoviesLoadingScreen() } }
6
Kotlin
2
15
bcebd39b3d77724b066f126dff0b4b029825b302
796
moviedb
Apache License 2.0
app/src/main/java/dev/chet/graphics/shapes/shapesdemo/Utilities.kt
chethaase
626,626,283
false
{"Kotlin": 50555}
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.chet.graphics.shapes.shapesdemo import android.graphics.PointF import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.graphics.Path import androidx.core.graphics.plus import androidx.core.graphics.times import androidx.graphics.shapes.Cubic import androidx.graphics.shapes.Morph import androidx.graphics.shapes.MutableCubic import androidx.graphics.shapes.RoundedPolygon import androidx.graphics.shapes.TransformResult import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin internal fun Float.toRadians() = this * PI.toFloat() / 180f internal fun Offset.rotate90() = Offset(-y, x) internal fun directionVector(angleRadians: Float) = Offset(cos(angleRadians), sin(angleRadians)) internal fun Offset.rotate(angleRadians: Float): Offset { val vec = directionVector(angleRadians) return vec * x + vec.rotate90() * y } internal val PointZero = PointF(0f, 0f) internal fun radialToCartesian( radius: Float, angleRadians: Float, center: PointF = PointZero ) = directionVectorPointF(angleRadians) * radius + center internal fun directionVectorPointF(angleRadians: Float) = PointF(cos(angleRadians), sin(angleRadians)) /** * Utility functions providing more idiomatic ways of transforming RoundedPolygons and * transforming shapes into a compose Path, for drawing them. * * This should in the future move into the compose library, maybe with additional API that makes * it easier to create, draw, and animate from Compose apps. * * This code is just here for now prior to integration into compose */ /** * Scales a shape (given as a Sequence) in place. * As this works in Sequences, it doesn't create the whole list at any point, only one * MutableCubic is (re)used. */ fun Sequence<MutableCubic>.scaled(scale: Float) = map { it.transform { x, y -> TransformResult(x * scale, y * scale) } it } /** * Scales a shape (given as a List), creating a new List. */ fun List<Cubic>.scaled(scale: Float) = map { it.transformed { x, y -> TransformResult(x * scale, y * scale) } } /** * Transforms a [RoundedPolygon] with the given [Matrix] */ fun RoundedPolygon.transformed(matrix: Matrix): RoundedPolygon = transformed { x, y -> val transformedPoint = matrix.map(Offset(x, y)) TransformResult(transformedPoint.x, transformedPoint.y) } /** * Calculates and returns the bounds of this [RoundedPolygon] as a [Rect] */ fun RoundedPolygon.getBounds() = calculateBounds().let { Rect(it[0], it[1], it[2], it[3]) } /** * Function used to create a Path from a list of Cubics. */ fun List<Cubic>.toPath(path: Path = Path()): Path { path.rewind() firstOrNull()?.let { first -> path.moveTo(first.anchor0X, first.anchor0Y) } for (bezier in this) { path.cubicTo( bezier.control0X, bezier.control0Y, bezier.control1X, bezier.control1Y, bezier.anchor1X, bezier.anchor1Y ) } path.close() return path } /** * Transforms the morph at a given progress into a [Path]. * It can optionally be scaled, using the origin (0,0) as pivot point. */ fun Morph.toComposePath(progress: Float, scale: Float = 1f, path: Path = Path()): Path { var first = true path.rewind() forEachCubic(progress) { bezier -> if (first) { path.moveTo(bezier.anchor0X * scale, bezier.anchor0Y * scale) first = false } path.cubicTo( bezier.control0X * scale, bezier.control0Y * scale, bezier.control1X * scale, bezier.control1Y * scale, bezier.anchor1X * scale, bezier.anchor1Y * scale ) } path.close() return path } /** * Transforms the morph at a given progress into a [Path]. * It can optionally be scaled, using the origin (0,0) as pivot point. */ fun Morph.toAndroidPath(progress: Float, scale: Float = 1f, path: android.graphics.Path = android.graphics.Path()): android.graphics.Path { var first = true path.rewind() forEachCubic(progress) { bezier -> if (first) { path.moveTo(bezier.anchor0X * scale, bezier.anchor0Y * scale) first = false } path.cubicTo( bezier.control0X * scale, bezier.control0Y * scale, bezier.control1X * scale, bezier.control1Y * scale, bezier.anchor1X * scale, bezier.anchor1Y * scale ) } path.close() return path } internal const val DEBUG = false internal inline fun debugLog(message: String) { if (DEBUG) { println(message) } }
2
Kotlin
14
136
2648f6a8287d94c2856e9cf0249ad952c8a6c137
5,305
ShapesDemo
Apache License 2.0
app/src/main/java/com/workfort/pstuian/app/ui/signup/StudentSignUpActivity.kt
arhanashik
411,942,559
false
{"Kotlin": 1051684}
package com.workfort.pstuian.app.ui.signup import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import androidx.lifecycle.lifecycleScope import com.workfort.pstuian.R import com.workfort.pstuian.app.ui.base.activity.BaseActivity import com.workfort.pstuian.app.ui.common.dialog.CommonDialog import com.workfort.pstuian.app.ui.common.intent.AuthIntent import com.workfort.pstuian.app.ui.common.viewmodel.AuthViewModel import com.workfort.pstuian.app.ui.signin.SignInActivity import com.workfort.pstuian.app.ui.webview.WebViewActivity import com.workfort.pstuian.appconstant.Const import com.workfort.pstuian.appconstant.NetworkConst import com.workfort.pstuian.databinding.ActivityStudentSignUpBinding import com.workfort.pstuian.model.BatchEntity import com.workfort.pstuian.model.FacultyEntity import com.workfort.pstuian.model.RequestState import com.workfort.pstuian.model.StudentEntity import com.workfort.pstuian.util.extension.launchActivity import kotlinx.coroutines.launch import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber class StudentSignUpActivity : BaseActivity<ActivityStudentSignUpBinding>() { override val bindingInflater: (LayoutInflater) -> ActivityStudentSignUpBinding = ActivityStudentSignUpBinding::inflate private val mViewModel: AuthViewModel by viewModel() private lateinit var mFaculty: FacultyEntity private lateinit var mBatch: BatchEntity override fun getToolbarId(): Int = R.id.toolbar override fun afterOnCreate(savedInstanceState: Bundle?) { setHomeEnabled() val faculty = intent.getParcelableExtra<FacultyEntity>(Const.Key.FACULTY) if(faculty == null) finish() else mFaculty = faculty val batch = intent.getParcelableExtra<BatchEntity>(Const.Key.BATCH) if(batch == null) finish() else mBatch = batch with(binding) { tvBatch.text = mBatch.name setClickListener(btnSignUp, btnSignIn, btnTermsAndConditions, btnPrivacyPolicy) } observeSignUp() } override fun onClick(v: View?) { super.onClick(v) when(v) { binding.btnSignUp -> signUp() binding.btnSignIn -> gotToSignIn() binding.btnTermsAndConditions -> launchActivity<WebViewActivity>(Pair( Const.Key.URL, NetworkConst.Remote.TERMS_AND_CONDITIONS)) binding.btnPrivacyPolicy -> launchActivity<WebViewActivity>(Pair( Const.Key.URL, NetworkConst.Remote.PRIVACY_POLICY)) else -> Timber.e("Who clicked me!") } } private fun signUp() { with(binding) { val name = etName.text.toString() if(TextUtils.isEmpty(name)) { tilName.error = "*Required" return } tilName.error = null val id = etId.text.toString() if(TextUtils.isEmpty(id)) { tilId.error = "*Required" return } tilId.error = null val reg = etReg.text.toString() if(TextUtils.isEmpty(reg)) { tilReg.error = "*Required" return } tilReg.error = null val session = etSession.text.toString() if(TextUtils.isEmpty(session)) { tilSession.error = "*Required" return } tilSession.error = null val email = etEmail.text.toString() if(TextUtils.isEmpty(email)) { tilEmail.error = "*Required" return } tilEmail.error = null lifecycleScope.launch { mViewModel.intent.send(AuthIntent.SignUpStudent( name, id, reg, mFaculty.id, mBatch.id, session, email )) } } } private fun observeSignUp() { lifecycleScope.launch { mViewModel.studentSignUpState.collect { when (it) { is RequestState.Idle -> Unit is RequestState.Loading -> setActionUiState(true) is RequestState.Success<*> -> { setActionUiState(false) doSuccessAction() } is RequestState.Error -> { setActionUiState(false) val title = "Sign up failed!" val msg = it.error?: getString(R.string.default_error_dialog_message) CommonDialog.error(this@StudentSignUpActivity, title, msg) } } } } } private fun setActionUiState(isLoading: Boolean) { val visibility = if(isLoading) View.VISIBLE else View.GONE with(binding) { loader.visibility = visibility btnSignIn.isEnabled = !isLoading btnSignUp.isEnabled = !isLoading btnTermsAndConditions.isEnabled = !isLoading btnPrivacyPolicy.isEnabled = !isLoading } } private fun doSuccessAction() { val msg = getString(R.string.success_msg_sign_up) val btnTxt = getString(R.string.txt_sign_in) val warning = getString(R.string.warning_msg_sign_up) CommonDialog.success(this@StudentSignUpActivity, message = msg, btnText = btnTxt, warning = warning, cancelable = false) { gotToSignIn() } } private fun gotToSignIn() { launchActivity<SignInActivity>() finish() } }
0
Kotlin
0
2
9c51ec4d4d477ae739b922c49127ac69844f4d6e
5,712
PSTUian-android
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnAnalysisKPIVisualStandardLayoutPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.quicksight import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.quicksight.CfnAnalysis /** * The standard layout of the KPI visual. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.quicksight.*; * KPIVisualStandardLayoutProperty kPIVisualStandardLayoutProperty = * KPIVisualStandardLayoutProperty.builder() * .type("type") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-kpivisualstandardlayout.html) */ @CdkDslMarker public class CfnAnalysisKPIVisualStandardLayoutPropertyDsl { private val cdkBuilder: CfnAnalysis.KPIVisualStandardLayoutProperty.Builder = CfnAnalysis.KPIVisualStandardLayoutProperty.builder() /** @param type The standard layout type. */ public fun type(type: String) { cdkBuilder.type(type) } public fun build(): CfnAnalysis.KPIVisualStandardLayoutProperty = cdkBuilder.build() }
0
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
1,397
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/com/braisgabin/showmedamoney/presentation/confirmation/ConfirmationPresenter.kt
BraisGabin
161,705,625
false
null
package com.braisgabin.showmedamoney.presentation.confirmation import com.braisgabin.showmedamoney.commons.RxViewModel import com.braisgabin.showmedamoney.entities.Contact import io.reactivex.Flowable import java.math.BigDecimal import java.math.RoundingMode import javax.inject.Inject class ConfirmationPresenter @Inject constructor( private val amount: BigDecimal, private val contacts: List<Contact> ) : RxViewModel() { val states: Flowable<ConfirmationState> by lazy { // This is not the perfect split. But it's not that bad. val contactsCount = contacts.size val split = amount.divide(BigDecimal(contactsCount), 2, RoundingMode.FLOOR) val lastSplit = amount.minus(split.times(BigDecimal(contactsCount - 1))) val splits = contacts.mapIndexed { i, it -> if (i <= contactsCount - 2) { Split(split, it) } else { Split(lastSplit, it) } } Flowable.just(ConfirmationState(amount, splits)) } }
0
Kotlin
0
0
9610f84170e89c69fe729acfbba300f971d9020a
969
showmedamoney
Apache License 2.0
app/src/main/java/xyz/lazysoft/a3amp/midi/UsbMidiManager.kt
skyfion
166,003,849
false
{"Kotlin": 93860}
package xyz.lazysoft.a3amp.midi import android.content.Context import android.hardware.usb.UsbDevice import jp.kshoji.driver.midi.device.MidiInputDevice import jp.kshoji.driver.midi.device.MidiOutputDevice import jp.kshoji.driver.midi.util.UsbMidiDriver abstract class UsbMidiManager(context: Context) : UsbMidiDriver(context), SysExMidiManager { override fun onMidiActiveSensing(p0: MidiInputDevice, p1: Int) { } override fun onMidiNoteOff(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int, p4: Int) { } override fun onMidiChannelAftertouch(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int) { } override fun onMidiProgramChange(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int) { } override fun onMidiSongPositionPointer(p0: MidiInputDevice, p1: Int, p2: Int) { } override fun onMidiPitchWheel(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int) { } override fun onMidiTimeCodeQuarterFrame(p0: MidiInputDevice, p1: Int, p2: Int) { } override fun onMidiMiscellaneousFunctionCodes(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int, p4: Int) { } override fun onMidiStart(p0: MidiInputDevice, p1: Int) { } override fun onMidiTimingClock(p0: MidiInputDevice, p1: Int) { } override fun onMidiOutputDeviceAttached(p0: MidiOutputDevice) { } override fun onMidiOutputDeviceDetached(p0: MidiOutputDevice) { } override fun onMidiSongSelect(p0: MidiInputDevice, p1: Int, p2: Int) { } override fun onMidiReset(p0: MidiInputDevice, p1: Int) { } override fun onMidiSystemCommonMessage(p0: MidiInputDevice, p1: Int, p2: ByteArray?) { } override fun onMidiSingleByte(p0: MidiInputDevice, p1: Int, p2: Int) { } override fun onMidiPolyphonicAftertouch(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int, p4: Int) { } override fun onMidiCableEvents(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int, p4: Int) { } override fun onMidiContinue(p0: MidiInputDevice, p1: Int) { } override fun onMidiNoteOn(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int, p4: Int) { } override fun onMidiTuneRequest(p0: MidiInputDevice, p1: Int) { } override fun onMidiControlChange(p0: MidiInputDevice, p1: Int, p2: Int, p3: Int, p4: Int) { } override fun onMidiStop(p0: MidiInputDevice, p1: Int) { } @Deprecated("Deprecated in Java") override fun onDeviceDetached(p0: UsbDevice) { } @Deprecated("Deprecated in Java") override fun onDeviceAttached(p0: UsbDevice) { } }
0
Kotlin
0
0
d07022563e9d51b7080ea40dc306f78c1afda99d
2,554
3amp
MIT License
app/src/main/java/me/reezy/demo/router/PostActivity.kt
czy1121
348,677,507
false
null
package me.reezy.demo.router import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.layout_demo.* import me.reezy.jetpack.argument.ArgumentInt import me.reezy.router.annotation.Route @Route("post", routes = ["post/:id"]) class PostActivity : AppCompatActivity(R.layout.layout_demo) { private val id by ArgumentInt() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) text.text = "PostActivity\n id = $id" } }
0
Kotlin
0
3
da94bec47c641aff3099da3ad0e943f18120f6ba
536
router
Apache License 1.1
checkout/src/test/kotlin/com/lastminute/cdc/checkout/flight/FlightCheckoutControllerPactTest.kt
gdipaolantonio
192,891,873
false
null
package com.lastminute.cdc.checkout.flight import au.com.dius.pact.provider.junit.Provider import au.com.dius.pact.provider.junit.State import au.com.dius.pact.provider.junit.loader.PactBroker import au.com.dius.pact.provider.junit.target.Target import au.com.dius.pact.provider.junit.target.TestTarget import au.com.dius.pact.provider.spring.SpringRestPactRunner import au.com.dius.pact.provider.spring.target.MockMvcTarget import org.junit.runner.RunWith import java.util.* @RunWith(SpringRestPactRunner::class) @Provider("checkout") @PactBroker(host = "192.168.99.100", port = "9292") class FlightCheckoutControllerPactTest { private val checkout: InMemoryCheckout = InMemoryCheckout() @TestTarget @JvmField val target: Target = MockMvcTarget( controllers = listOf( FlightCheckoutController(checkout) ) ) @State("found flight with id 47e2f0e6-a848-48c8-b1ab-e3dd80a80829") fun `with flight with id 47e2f0e6-a848-48c8-b1ab-e3dd80a80829`() { checkout.accept( UUID.fromString("47e2f0e6-a848-48c8-b1ab-e3dd80a80829"), "alice" ) } }
4
Kotlin
0
1
8ca9d7a980d8501b24707ae11e9493e1f8ea0e77
1,084
cdc-with-pact
Apache License 2.0
src/serverMain/kotlin/mce/serialization/NbtInputDecoder.kt
mcenv
435,848,712
false
null
package mce.serialization import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.descriptors.StructureKind import kotlinx.serialization.encoding.AbstractDecoder import kotlinx.serialization.encoding.CompositeDecoder import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.modules.EmptySerializersModule import kotlinx.serialization.modules.SerializersModule import java.io.DataInput @ExperimentalSerializationApi class NbtInputDecoder(private val input: DataInput, private val elementsCount: Int = 0) : AbstractDecoder() { private var elementIndex: Int = 0 override val serializersModule: SerializersModule = EmptySerializersModule override fun decodeNotNullMark(): Boolean = TODO() override fun decodeNull(): Nothing? = TODO() override fun decodeBoolean(): Boolean = input.readBoolean() override fun decodeByte(): Byte = input.readByte() override fun decodeShort(): Short = input.readShort() override fun decodeChar(): Char = input.readChar() override fun decodeInt(): Int = input.readInt() override fun decodeLong(): Long = input.readLong() override fun decodeFloat(): Float = input.readFloat() override fun decodeDouble(): Double = input.readDouble() override fun decodeString(): String = input.readUTF() override fun decodeEnum(enumDescriptor: SerialDescriptor): Int = input.readInt() override fun decodeInline(inlineDescriptor: SerialDescriptor): Decoder = this private fun decodeByteArray(): ByteArray { val size = decodeInt() return ByteArray(size).also { input.readFully(it) } } private fun decodeIntArray(): IntArray { val size = decodeInt() return IntArray(size) { decodeInt() } } private fun decodeLongArray(): LongArray { val size = decodeInt() return LongArray(size) { decodeLong() } } @Suppress("UNCHECKED_CAST") override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T = when (deserializer.descriptor) { byteArrayDescriptor -> decodeByteArray() as T intArrayDescriptor -> decodeIntArray() as T longArrayDescriptor -> decodeLongArray() as T else -> super.decodeSerializableValue(deserializer) } override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder { val elementsCount = when (descriptor.kind) { StructureKind.LIST -> { decodeByte() decodeInt() } StructureKind.OBJECT -> { decodeByte() descriptor.elementsCount } else -> descriptor.elementsCount } return NbtInputDecoder(input, elementsCount) } override fun endStructure(descriptor: SerialDescriptor) { when (descriptor.kind) { StructureKind.CLASS -> require(NbtType.END.ordinal == input.readByte().toInt()) else -> Unit } } override fun decodeElementIndex(descriptor: SerialDescriptor): Int { return if (elementsCount == elementIndex) { CompositeDecoder.DECODE_DONE } else { when (descriptor.kind) { StructureKind.CLASS -> { require(descriptor.getElementDescriptor(elementIndex).kind.toNbtType().ordinal == input.readByte().toInt()) require(descriptor.getElementName(elementIndex) == input.readUTF()) } else -> Unit } elementIndex++ } } }
79
Kotlin
0
15
f63905729320733d3cae95c3b51b492e94339fca
3,716
mce
MIT License
app/main/kotlin/tilgang/integrasjoner/saf/SafGraphqlClient.kt
navikt
819,933,604
false
{"Kotlin": 123742, "Dockerfile": 248}
package no.nav.aap.postmottak.saf.graphql import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.http.* import io.micrometer.prometheusmetrics.PrometheusMeterRegistry import kotlinx.coroutines.runBlocking import org.slf4j.LoggerFactory import tilgang.LOGGER import tilgang.SafConfig import tilgang.auth.AzureAdTokenProvider import tilgang.auth.AzureConfig import tilgang.http.HttpClientFactory import tilgang.integrasjoner.saf.SafException import tilgang.metrics.cacheHit import tilgang.metrics.cacheMiss import tilgang.redis.Key import tilgang.redis.Redis import tilgang.redis.Redis.Companion.deserialize import tilgang.redis.Redis.Companion.serialize class SafGraphqlClient( azureConfig: AzureConfig, private val safConfig: SafConfig, private val redis: Redis, private val prometheus: PrometheusMeterRegistry ) { private val log = LoggerFactory.getLogger(SafGraphqlClient::class.java) private val httpClient = HttpClientFactory.create() private val azureTokenProvider = AzureAdTokenProvider( azureConfig, safConfig.scope ).also { LOGGER.info("azure scope: ${safConfig.scope}") } companion object { private const val JOURNALPOST_PREFIX = "journalpost" } suspend fun hentJournalpostInfo(journalpostId: Long, callId: String): SafJournalpost { if (redis.exists(Key(JOURNALPOST_PREFIX, journalpostId.toString()))) { prometheus.cacheHit(JOURNALPOST_PREFIX).increment() return redis[Key(JOURNALPOST_PREFIX, journalpostId.toString())]!!.deserialize() } prometheus.cacheMiss(JOURNALPOST_PREFIX).increment() val azureToken = azureTokenProvider.getClientCredentialToken() val request = SafRequest.hentJournalpost(journalpostId) val response = runBlocking { query(azureToken, request, callId) } val journalpost: SafJournalpost = response.getOrThrow().data?.journalpost ?: error("Fant ikke journalpost for $journalpostId") redis.set(Key(JOURNALPOST_PREFIX, journalpostId.toString()), journalpost.serialize()) if (journalpost.bruker?.type != BrukerIdType.FNR) { log.warn("Journalpost ${journalpostId} har ikke personident") } return journalpost } private suspend fun query(accessToken: String, query: SafRequest, callId: String): Result<SafRespons> { val request = httpClient.post(safConfig.baseUrl) { accept(ContentType.Application.Json) header("Nav-Call-Id", callId) bearerAuth(accessToken) contentType(ContentType.Application.Json) setBody(query) } return runCatching { val respons = request.body<SafRespons>() if (respons.errors != null) { log.error("Feil ved henting av journalpost: ${respons.errors}") throw SafException("Feil mot SAF: ${respons.errors}") } respons } } }
0
Kotlin
0
0
ad73f13132698cf5642c092a331e3e0c885ca3dd
2,976
aap-tilgang
MIT License
remote/src/test/java/com/github/abhrp/cryptograph/remote/mapper/ChartItemMapperTest.kt
abhrp
154,935,698
false
{"Gradle": 10, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Kotlin": 106, "XML": 25, "INI": 1, "Java": 2, "JSON": 1}
package com.github.abhrp.cryptograph.remote.mapper import com.github.abhrp.cryptograph.remote.factory.ChartResponseFactory import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import kotlin.test.assertEquals @RunWith(JUnit4::class) class ChartItemMapperTest { private val chartItemMapper = ChartItemMapper() @Test fun testChartItemMapperMapsToEntityCorrectly() { val chartItem = ChartResponseFactory.getRandomChartItem() val chartItemEntity = chartItemMapper.mapToEntity(chartItem) assertEquals(chartItem.datetime, chartItemEntity.datetime) assertEquals(chartItem.value, chartItemEntity.value) } }
1
null
1
1
1582562019efd270cb14b298caf3f1620d99548b
681
cryptograph
MIT License
app/src/main/java/com/aditPrayogo/githubusers/data/local/repository/UserRepository.kt
aanfarhan
357,811,667
true
{"Kotlin": 83057}
package com.aditPrayogo.githubusers.data.local.repository import com.aditPrayogo.githubusers.data.local.db.entity.UserFavorite import com.aditPrayogo.githubusers.data.local.responses.SearchUserResponse import com.aditPrayogo.githubusers.data.local.responses.UserDetailResponse import com.aditPrayogo.githubusers.data.local.responses.UserFollowersResponse import com.aditPrayogo.githubusers.data.local.responses.UserFollowingResponse import retrofit2.Response interface UserRepository { /** * Remote */ suspend fun getUserFromApi(username: String) : Response<SearchUserResponse> suspend fun getDetailUserFromApi(username: String) : Response<UserDetailResponse> suspend fun getUserFollowers(username: String) : Response<UserFollowersResponse> suspend fun getUserFollowing(username: String) : Response<UserFollowingResponse> /** * Local */ suspend fun fetchAllUserFavorite() : List<UserFavorite> suspend fun getFavoriteUserByUsername(username: String) : List<UserFavorite> suspend fun addUserToFavDB(userFavorite: UserFavorite) suspend fun deleteUserFromFavDB(userFavorite: UserFavorite) }
0
null
0
0
3787cb69946623654c59af823b06edc21da5eed5
1,159
GithubUsers
Apache License 2.0
src/fr/lelscanvf/src/eu/kanade/tachiyomi/extension/fr/lelscanvf/LelscanVF.kt
keiyoushi
740,710,728
false
{"Kotlin": 5885779, "JavaScript": 2160}
package eu.kanade.tachiyomi.extension.fr.lelscanvf import eu.kanade.tachiyomi.multisrc.mmrcms.MMRCMS class LelscanVF : MMRCMS( "Lelscan-VF", "https://lelscanvf.cc", "fr", supportsAdvancedSearch = false, )
268
Kotlin
293
1,264
3feb355beb807142cc56be8e63d04cf1873c8c8c
223
extensions-source
Apache License 2.0
app/src/main/java/com/google/samples/apps/sunflower/data/source/local/AppDatabase.kt
azisnaufal
190,738,715
true
{"Kotlin": 60269}
package com.google.samples.apps.sunflower.data.source.local import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.google.samples.apps.sunflower.data.model.GardenPlanting import com.google.samples.apps.sunflower.data.model.Plant import com.google.samples.apps.sunflower.data.utils.Converters import com.google.samples.apps.sunflower.utilities.DATABASE_NAME /** * The Room database for this app */ @Database(entities = [GardenPlanting::class, Plant::class], version = 1, exportSchema = false) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun gardenPlantingDao(): GardenPlantingDao abstract fun plantDao(): PlantDao companion object { // For Singleton instantiation @Volatile private var instance: AppDatabase? = null fun getInstance(context: Context): AppDatabase { return instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } } // Create and pre-populate the database. See this article for more details: // https://medium.com/google-developers/7-pro-tips-for-room-fbadea4bfbd1#4785 private fun buildDatabase(context: Context): AppDatabase { return Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME) .build() } } }
0
Kotlin
2
1
905abe0f990db73e83e59004a1a042bb5f323a65
1,514
android-mvvm-template
Apache License 2.0
gradle/build-logic/dev/src/main/kotlin/DokkaExtensions.kt
robstoll
79,735,987
false
{"Kotlin": 276135, "Java": 85}
import org.jetbrains.dokka.base.DokkaBase import org.jetbrains.dokka.base.DokkaBaseConfiguration import org.jetbrains.dokka.gradle.AbstractDokkaTask fun AbstractDokkaTask.configurePlugins() { pluginConfiguration<DokkaBase, DokkaBaseConfiguration> { footerMessage = "KBox &copy; Copyright <NAME> &lt;<EMAIL>&gt;" } }
1
Kotlin
3
8
9546196cfb0ee0c6b672b9d0e61ceaa034b4121b
333
kbox
Apache License 2.0
src/main/kotlin/dsm/service/announcement/core/domain/repository/AnnouncementRepository.kt
DMS-SMS
295,392,679
false
null
package dsm.service.announcement.core.domain.repository import dsm.service.announcement.core.domain.entity.Announcement import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.stereotype.Repository @Repository interface AnnouncementRepository { fun persist(announcement: Announcement): Announcement fun delete(announcement: Announcement) fun findById(id: String): Announcement? fun findByWriterUuidAndTypeOrderByDateDesc(writerUuid: String, type: String, pageable: Pageable): MutableIterable<Announcement> fun countByWriterUuidAndType(writerUuid: String, type: String): Long fun findByNumberAndType(number: Long, type: String): Announcement? fun findTopByOrderByNumberDesc(): Announcement? fun findTopByOrderByNumberAsc(): Announcement? fun countByType(type: String): Long fun findByTypeOrderByDateDesc(type: String): MutableIterable<Announcement> fun findByTypeOrderByDateDesc(type: String, pageable: Pageable): MutableIterable<Announcement> fun findByTitleContainsAndTypeOrderByDateDesc(title: String, type: String, pageable: Pageable): MutableIterable<Announcement> fun countByTitleContainsAndType(title: String, type: String): Long fun findByTitleContainsAndTypeAndTargetGradeContainsAndTargetGroupContainsOrderByDateDesc( title: String, type: String, targetGrade: String, targetGroup: String, pageable: Pageable): MutableIterable<Announcement> fun findByTypeAndTargetGradeContainsAndTargetGroupContainsOrderByDateDesc( type: String, targetGrade: String, targetGroup: String): MutableIterable<Announcement> fun findByTypeAndTargetGradeContainsAndTargetGroupContainsOrderByDateDesc( type: String, targetGrade: String, targetGroup: String, pageable: Pageable): MutableIterable<Announcement> fun countByTypeAndTargetGradeContainsAndTargetGroupContains(type: String, targetGrade: String, targetGroup: String): Long }
0
Kotlin
0
1
3a05939e1a13ca3bc12f6379917cbf9482350e43
2,001
v1-service-announcement
MIT License
Freelancer/app/src/main/java/com/example/freelancer/ui/screens/MainScreen.kt
madiistvan
445,539,478
false
{"Kotlin": 93209, "Java": 2411}
package com.example.freelancer.ui.screens import androidx.compose.animation.core.* import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Refresh import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.Alignment.Companion.End import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.freelancer.R import com.example.freelancer.ui.theme.PrimaryColor import com.example.freelancer.ui.theme.PrimaryVariant import com.example.freelancer.ui.theme.Secondary import kotlinx.coroutines.Job import java.util.concurrent.ThreadLocalRandom object Colors { var colors = ArrayList<Color>() fun initColors() { for (i in 0..3) { colors.add(rndColor()) } } } @Composable fun MainScreen(navController: NavController, openDrawer: () -> Job) { TopBar(onButtonClicked = { openDrawer() }) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Row() { GridItem( navController = navController, navTo = "Items", title = "Get a job!", PrimaryColor, Secondary ) GridItem( navController = navController, navTo = "JobList", title = "View your jobs!", Secondary, PrimaryColor ) } Row() { GridItem( navController = navController, navTo = "CreateJob", title = "Post a job!", Secondary, PrimaryColor ) GridItem( navController = navController, navTo = "UserList", title = "View other users", PrimaryColor, Secondary ) } } } @Composable fun GridItem(navController: NavController, navTo: String, title: String, color1: Color,color2:Color) { val infiniteTransition = rememberInfiniteTransition() val size by infiniteTransition.animateFloat( initialValue = 180f, targetValue = 200f, animationSpec = infiniteRepeatable( animation = tween( 800, delayMillis = ThreadLocalRandom.current().nextInt(150, 350), easing = FastOutLinearInEasing ), repeatMode = RepeatMode.Reverse ) ) Card(modifier = Modifier .padding(8.dp) .clickable { navController.navigate(navTo) } .width(Dp(size)) .height(Dp(size)) , border = BorderStroke(2.dp, color2), shape = RoundedCornerShape(50.dp), elevation = Dp.Hairline, backgroundColor = color1 ) { Text( text = title, textAlign = TextAlign.Center, fontSize = 31.sp, modifier = Modifier .padding(15.dp), color = Color.White ) } } fun rndColor(): Color { return Color( 10 * ThreadLocalRandom.current().nextInt(20, 26), ThreadLocalRandom.current().nextInt(25, 60), ThreadLocalRandom.current().nextInt(25, 60), ThreadLocalRandom.current().nextInt(100, 255) ) } @Composable fun TopBar(title: String = "Freelancer", onButtonClicked: () -> Unit) { var showMenu by remember { mutableStateOf(false) } TopAppBar( backgroundColor = PrimaryVariant, title = { Text(title) }, navigationIcon = { IconButton(onClick = { onButtonClicked() }) { val icon = Icons.Default.Menu Icon(icon, "Menu") } }, actions = { Image(painterResource(R.mipmap.appicon_foreground),"",Modifier.alpha(100F)) } ) } sealed class DrawerScreens(val title: String, val route: String, val id: Int) { object SignOut : DrawerScreens("SignOut", "SignOut", R.mipmap.logout_foreground) object Jobs : DrawerScreens("Jobs", "JobList", R.mipmap.workerhat_foreground) object Users : DrawerScreens("Users", "UserList", R.drawable.ic_baseline_sentiment_satisfied_alt_24) object CreateJobs : DrawerScreens("Create Jobs", "CreateJob", R.mipmap.box_foreground) object Items : DrawerScreens("Available jobs", "Items", R.drawable.ic_baseline_work_24) } private val screens = listOf( DrawerScreens.SignOut, DrawerScreens.Users, DrawerScreens.Jobs, DrawerScreens.CreateJobs, DrawerScreens.Items ) @Composable fun Drawer( modifier: Modifier = Modifier.background(PrimaryVariant), onDestinationClicked: (route: String) -> Unit ) { Scaffold() { Column( modifier .fillMaxSize() .padding(start = 24.dp, top = 48.dp) ) { Image( painter = painterResource(R.mipmap.appicon_foreground), contentDescription = "App icon", modifier = Modifier .fillMaxWidth() .height(200.dp) ) screens.forEach { screen -> Card( border = BorderStroke(2.dp, PrimaryColor), backgroundColor = Secondary ) { Row( modifier = Modifier .padding(10.dp) .fillMaxWidth() ) { Text( text = screen.title, style = MaterialTheme.typography.h4, modifier = Modifier.clickable { onDestinationClicked(screen.route) }, ) Spacer(Modifier.width(30.dp)) Image( painter = painterResource(screen.id), contentDescription = "icon", modifier = Modifier .height(40.dp) .wrapContentSize(align = Alignment.BottomEnd) ) } } } } } }
0
Kotlin
0
1
dd62c8e5bfd75daab8912f6510775cd64fdefe81
7,106
Freelancer
MIT License
server/src/main/java/de/zalando/zally/util/ast/JsonPointers.kt
hpdang
148,153,657
true
null
package de.zalando.zally.util.ast import com.fasterxml.jackson.core.JsonPointer import java.lang.reflect.Method /** * Utility to convert OpenAPI 3 JSON pointers to Swagger 2 pointers. */ object JsonPointers { val EMPTY: JsonPointer = JsonPointer.compile("") private val regexToReplacement = listOf( "^/servers/.*$" to "/basePath", "^/components/schemas/(.*)$" to "/definitions/$1", "^/components/responses/(.*)$" to "/responses/$1", "^/components/parameters/(.*)$" to "/parameters/$1", "^/components/securitySchemes/(.*?)/flows/(implicit|password|clientCredentials|authorizationCode)/(.*)$" to "/securityDefinitions/$1/$3", "^/components/securitySchemes/(.*)$" to "/securityDefinitions/$1", "^/paths/(.+/responses/.+)/content/.+/(schema.*)$" to "/paths/$1/$2", // VERB/responses/STATUS_CODE/content/MEDIA_TYPE --> VERB/responses/STATUS_CODE // Could also be VERB/produces but this information is lost from Swagger 2 to OpenAPI 3 conversion. "^/paths/(.+/responses/.+)/content/[^/]*$" to "/paths/$1", // VERB/requestBody/content/MEDIA_TYPE --> VERB/consumes "^/paths/(.*)/requestBody/content/[^/]*$" to "/paths/$1/consumes" ) .map { it.first.toRegex() to it.second } /** * Convert an OpenAPI 3 JSON pointer to a Swagger 2 pointer. * * @param pointer OpenAPI 3 JSON pointer. * @return Equivalent Swagger 2 JSON pointer or null. */ fun convertPointer(pointer: JsonPointer?): JsonPointer? = pointer ?.toString() ?.let { ptr -> regexToReplacement .find { (regex, _) -> regex.matches(ptr) } ?.let { (regex, replacement) -> JsonPointer.compile(regex.replace(ptr, replacement)) } } internal fun escape(method: Method, vararg arguments: Any): JsonPointer = escape(method.name .let { if (it.startsWith("get")) it.drop(3) else it } .decapitalize() .let { if (arguments.isNotEmpty()) it + arguments[0] else it }) // https://tools.ietf.org/html/rfc6901 internal fun escape(unescaped: String): JsonPointer = unescaped .replace("~", "~0") .replace("/", "~1") .let { JsonPointer.compile("/$it") } }
0
Kotlin
1
415
91bc7341a5b8d9a65bc67e8ca680b6c423d6c684
2,423
zally
MIT License
mvvm/src/main/java/cn/carveknife/mvvm/http/respository/RxHttpObserver.kt
Carveknife
312,512,449
false
null
package cn.carveknife.mvvm.http.respository import android.content.Context import android.text.TextUtils import cn.carveknife.mvvm.http.exception.NetworkErrorException import com.blankj.utilcode.util.NetworkUtils import io.reactivex.Observer import io.reactivex.disposables.Disposable /** * description : * created time: 2020/11/13 16:34 * created by: cuibenguang */ class RxHttpObserver<T>(context: Context) : Observer<T> { private val mContext: Context?; init { mContext = context; } override fun onSubscribe(d: Disposable) { if (NetworkUtils.isConnected()) { onError(NetworkErrorException("网络连接失败!请重试!")) } } override fun onNext(t: T) { val dataResponse = t as? DataResponse<*> if (!TextUtils.equals(dataResponse?.errorCode, "0")) { //onError() } } override fun onError(e: Throwable) { } override fun onComplete() { } }
0
Kotlin
0
2
019f4512bc1b38f68286901c00c4b56e590ffe3b
949
AndroidMVVM
Apache License 2.0
src/main/kotlin/no/nav/fia/arbeidsgiver/sporreundersokelse/kafka/SpørreundersøkelseSvarProdusent.kt
navikt
644,356,194
false
{"Kotlin": 184710, "Dockerfile": 214}
package no.nav.fia.arbeidsgiver.sporreundersokelse.kafka import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import no.nav.fia.arbeidsgiver.konfigurasjon.KafkaConfig import no.nav.fia.arbeidsgiver.konfigurasjon.KafkaTopics import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.clients.producer.ProducerRecord class SpørreundersøkelseSvarProdusent(kafkaConfig: KafkaConfig) { private val producer: KafkaProducer<String, String> = KafkaProducer(kafkaConfig.producerProperties()) init { Runtime.getRuntime().addShutdownHook(Thread { producer.close() }) } fun sendSvar(svar: SpørreundersøkelseSvarDTO) { val topic = KafkaTopics.SPØRREUNDERSØKELSE_SVAR producer.send(ProducerRecord(topic.navnMedNamespace, svar.tilNøkkel(), svar.tilMelding())) } @Serializable data class SpørreundersøkelseSvarDTO( val spørreundersøkelseId: String, val sesjonId: String, val spørsmålId: String, val svarIder: List<String>, ) { fun tilNøkkel() = "${sesjonId}_$spørsmålId" fun tilMelding(): String { return Json.encodeToString(this) } } }
0
Kotlin
0
0
7cbc469c0fe892d304938a0011e5fd46e0aa9ff9
1,268
fia-arbeidsgiver
MIT License
buildSrc/src/main/kotlin/Deps.kt
nanogiants
223,148,332
false
null
object Versions { const val constraintLayout = "1.1.3" const val coroutines = "1.3.2" const val coreKtx = "1.2.0" const val dagger = "2.26" const val ktor = "1.3.1" const val material = "1.2.0-alpha05" const val navigation = "2.2.1" const val timber = "4.7.1" const val appcompat = "1.1.0" const val glide = "4.11.0" const val lifecycle = "2.2.0" const val multiplatformSettings = "0.5" const val sqldelight = "1.2.1" } object Deps { const val timber = "com.jakewharton.timber:timber:${Versions.timber}" const val material = "com.google.android.material:material:${Versions.material}" object Dagger { const val dagger = "com.google.dagger:dagger:${Versions.dagger}" const val compiler = "com.google.dagger:dagger-compiler:${Versions.dagger}" const val android = "com.google.dagger:dagger-android:${Versions.dagger}" const val androidProcessor = "com.google.dagger:dagger-android-processor:${Versions.dagger}" const val androidSupport = "com.google.dagger:dagger-android-support:${Versions.dagger}" } object Glide { const val glide = "com.github.bumptech.glide:glide:${Versions.glide}" const val compiler = "com.github.bumptech.glide:compiler:${Versions.glide}" } object Coroutines { const val android = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.coroutines}" const val core = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.coroutines}" const val coreCommon = "org.jetbrains.kotlinx:kotlinx-coroutines-core-common:${Versions.coroutines}" const val coreNative = "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:${Versions.coroutines}" } object AndroidX { const val appcompat = "androidx.appcompat:appcompat:${Versions.appcompat}" const val constraintLayout = "androidx.constraintlayout:constraintlayout:${Versions.constraintLayout}" const val coreKtx = "androidx.core:core-ktx:${Versions.coreKtx}" const val lifecycleRuntimeKtx = "androidx.lifecycle:lifecycle-runtime-ktx:${Versions.lifecycle}" const val navigationFragment_ktx = "androidx.navigation:navigation-fragment-ktx:${Versions.navigation}" const val navigationUiKtx = "androidx.navigation:navigation-ui-ktx:${Versions.navigation}" } object Kotlin { const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib" const val stdlibCommon = "org.jetbrains.kotlin:kotlin-stdlib-common" const val stdlibJdk7 = "org.jetbrains.kotlin:kotlin-stdlib-jdk7" } object MultiplatformSettings { const val multiplatformSettings = "com.russhwolf:multiplatform-settings:${Versions.multiplatformSettings}" const val iosarm64 = "com.russhwolf:multiplatform-settings-iosarm64:${Versions.multiplatformSettings}" const val iosx64 = "com.russhwolf:multiplatform-settings-iosx64:${Versions.multiplatformSettings}" } object Ktor { const val android = "io.ktor:ktor-client-android:${Versions.ktor}" const val core = "io.ktor:ktor-client-core:${Versions.ktor}" const val coreJvm = "io.ktor:ktor-client-core-jvm:${Versions.ktor}" const val coreNative = "io.ktor:ktor-client-core-native:${Versions.ktor}" const val ios = "io.ktor:ktor-client-ios:${Versions.ktor}" const val json = "io.ktor:ktor-client-json:${Versions.ktor}" const val jsonJvm = "io.ktor:ktor-client-json-jvm:${Versions.ktor}" const val jsonNative = "io.ktor:ktor-client-json-native:${Versions.ktor}" const val serialization = "io.ktor:ktor-client-serialization:${Versions.ktor}" const val serializationJvm = "io.ktor:ktor-client-serialization-jvm:${Versions.ktor}" const val serializationNative = "io.ktor:ktor-client-serialization-native:${Versions.ktor}" const val serializationIosarm64 = "io.ktor:ktor-client-serialization-iosarm64:${Versions.ktor}" const val serializationIosx64 = "io.ktor:ktor-client-serialization-iosx64:${Versions.ktor}" } object SqlDelight { const val androidDriver = "com.squareup.sqldelight:android-driver:${Versions.sqldelight}" const val iosDriver = "com.squareup.sqldelight:ios-driver:${Versions.sqldelight}" } }
0
Kotlin
0
1
5218bd7673c7f22c5ca890b050703bad188e34a4
4,164
ba-playground-app-kmp
Apache License 2.0
src/main/kotlin/al132/alchemistry/Reference.kt
kellixon
172,050,722
true
{"Kotlin": 206768}
package al132.alchemistry import al132.alchemistry.blocks.ModBlocks import al132.alib.utils.extensions.toStack import net.minecraft.creativetab.CreativeTabs import net.minecraft.item.ItemStack import java.io.File import java.text.DecimalFormat import java.text.NumberFormat object Reference { const val MODID = "alchemistry" const val MODNAME = "Alchemistry" const val VERSION = "0.8.1" const val DEPENDENCIES = "required-after:forgelin;required-after:alib;" val DECIMAL_FORMAT: NumberFormat = DecimalFormat("#0.00") val pathPrefix = "alchemistry:" lateinit var configPath: String lateinit var configDir: File val creativeTab: CreativeTabs = object : CreativeTabs("alchemistry") { override fun getTabIconItem(): ItemStack = ModBlocks.chemical_combiner.toStack() } }
0
Kotlin
0
0
ca6cd0b9b258291beced8a2b13bbba206bf44479
818
alchemistry
MIT License
goProControllerAndroid/src/main/java/com/bortxapps/goprocontrollerandroid/infrastructure/ble/manager/BleManagerDeviceSearchOperations.kt
neoBortx
692,337,190
false
{"Kotlin": 407044, "Java": 572}
package com.bortxapps.goprocontrollerandroid.infrastructure.ble.manager import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.content.Context import android.util.Log import com.bortxapps.goprocontrollerandroid.domain.data.GoProError import com.bortxapps.goprocontrollerandroid.domain.data.GoProException import com.bortxapps.goprocontrollerandroid.infrastructure.ble.scanner.BleDeviceScannerManager import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onEach import java.util.UUID internal class BleManagerDeviceSearchOperations( private val bleScanner: BleDeviceScannerManager, ) { private var searchingDevices = false private val detectedDevices = mutableListOf<BluetoothDevice>() internal fun getDevicesByService(serviceUUID: UUID): Flow<BluetoothDevice> { if (!searchingDevices) { searchingDevices = true detectedDevices.clear() return bleScanner.scanBleDevicesNearby(serviceUUID).onEach { detectedDevices += it }.onCompletion { searchingDevices = false } } else { Log.e("BleManager", "getDevicesByService already searching devices") throw GoProException(GoProError.ALREADY_SEARCHING_CAMERAS) } } @SuppressLint("MissingPermission") internal fun getPairedDevicesByPrefix(context: Context, deviceNamePrefix: String): List<BluetoothDevice> = context.getSystemService(BluetoothManager::class.java) ?.adapter ?.bondedDevices ?.filter { it.name.startsWith(deviceNamePrefix) } .orEmpty() internal fun getDetectedDevices() = detectedDevices.toList() internal fun stopSearchDevices() = bleScanner.stopSearch() }
0
Kotlin
0
1
af74220e86c7b5574b0f70abe8b2feffcd87240f
1,886
goProController
Apache License 2.0
src/main/kotlin/codespitz2/AmountDiscount.kt
skaengus2012
195,506,540
false
null
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package codespitz2 abstract class AmountDiscount(private val amount: Money) : DiscountPolicy.AMOUNT, DiscountCondition { override fun calculateFee(fee: Money): Money { return fee.minus(amount) } }
1
Kotlin
1
1
645130abf71e0374dfea6077a1b7babcd10921b2
842
OBJECT_STUDY
Apache License 2.0
hmpps-sqs-spring-boot-autoconfigure/src/test/kotlin/uk/gov/justice/hmpps/sqs/HmppsAuditServiceTest.kt
ministryofjustice
370,951,976
false
{"Kotlin": 304896, "Shell": 3898}
package uk.gov.justice.hmpps.sqs import com.fasterxml.jackson.databind.ObjectMapper import kotlinx.coroutines.test.runTest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.kotlin.any import org.mockito.kotlin.check import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.json.JsonTest import software.amazon.awssdk.services.sqs.SqsAsyncClient import software.amazon.awssdk.services.sqs.model.SendMessageRequest import software.amazon.awssdk.services.sqs.model.SendMessageResponse import uk.gov.justice.hmpps.sqs.audit.HmppsAuditEvent import uk.gov.justice.hmpps.sqs.audit.HmppsAuditService import java.util.concurrent.CompletableFuture @JsonTest class HmppsAuditServiceTest(@Autowired private val objectMapper: ObjectMapper) { private val hmppsQueueService: HmppsQueueService = mock() private val hmppsQueue: HmppsQueue = mock() private val sqsAsyncClient: SqsAsyncClient = mock() @BeforeEach fun setup() { whenever(hmppsQueueService.findByQueueId(any())).thenReturn(hmppsQueue) whenever(hmppsQueue.sqsClient).thenReturn(sqsAsyncClient) whenever(hmppsQueue.queueUrl).thenReturn("a queue url") whenever(sqsAsyncClient.sendMessage(any<SendMessageRequest>())) .thenReturn(CompletableFuture.completedFuture(SendMessageResponse.builder().build())) } @Nested inner class PublishEventUsingDomainObject { @Test fun `test publish event using domain object`() = runTest { HmppsAuditService( hmppsQueueService = hmppsQueueService, objectMapper = objectMapper, applicationName = null, ) .publishEvent(HmppsAuditEvent(what = "bob", who = "me", service = "my-service")) verify(sqsAsyncClient).sendMessage( check<SendMessageRequest> { assertThat(it.queueUrl()).isEqualTo("a queue url") assertThat(it.messageBody()) .contains(""""what":"bob"""") .contains(""""who":"me"""") .contains(""""service":"my-service"""") }, ) } } @Nested inner class PublishEventUsingParameters { @Test fun `test publish event providing service as parameter`() = runTest { HmppsAuditService( hmppsQueueService = hmppsQueueService, objectMapper = objectMapper, applicationName = "application-name", ) .publishEvent(what = "bob", who = "me", service = "my-service") verify(sqsAsyncClient).sendMessage( check<SendMessageRequest> { assertThat(it.queueUrl()).isEqualTo("a queue url") assertThat(it.messageBody()) .contains(""""what":"bob"""") .contains(""""who":"me"""") .contains(""""service":"my-service"""") }, ) } @Test fun `test publish event defaulting to application name`() = runTest { HmppsAuditService( hmppsQueueService = hmppsQueueService, objectMapper = objectMapper, applicationName = "application-name", ) .publishEvent(what = "bob", who = "me") verify(sqsAsyncClient).sendMessage( check<SendMessageRequest> { assertThat(it.queueUrl()).isEqualTo("a queue url") assertThat(it.messageBody()) .contains(""""what":"bob"""") .contains(""""who":"me"""") .contains(""""service":"application-name"""") }, ) } @Test fun `test publish event throws exception when service not defined`() = runTest { assertThrows<NullPointerException> { HmppsAuditService( hmppsQueueService = hmppsQueueService, objectMapper = objectMapper, applicationName = null, ) .publishEvent(what = "bob", who = "me") } verifyNoInteractions(sqsAsyncClient) } @Test fun `test publish event uses service parameter`() = runTest { HmppsAuditService( hmppsQueueService = hmppsQueueService, objectMapper = objectMapper, applicationName = null, ) .publishEvent(what = "bob", who = "me", service = "my-service") verify(sqsAsyncClient).sendMessage( check<SendMessageRequest> { assertThat(it.queueUrl()).isEqualTo("a queue url") assertThat(it.messageBody()) .contains(""""what":"bob"""") .contains(""""who":"me"""") .contains(""""service":"my-service"""") }, ) } } }
0
Kotlin
0
2
a51d6983a20415dca4c6dbac3e499fd09d8f4bb3
4,771
hmpps-spring-boot-sqs
MIT License
sqlite-embedder-graalvm/src/jvmMain/kotlin/ru/pixnews/wasm/sqlite/open/helper/graalvm/host/emscripten/EmscriptenEnvModuleBuilder.kt
illarionov
769,429,996
false
{"Kotlin": 749374, "C": 64230}
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten import org.graalvm.polyglot.Context import org.graalvm.wasm.WasmContext import org.graalvm.wasm.WasmInstance import org.graalvm.wasm.WasmModule import org.graalvm.wasm.constants.Sizes import ru.pixnews.wasm.sqlite.open.helper.graalvm.SqliteEmbedderHost import ru.pixnews.wasm.sqlite.open.helper.graalvm.ext.setupWasmModuleFunctions import ru.pixnews.wasm.sqlite.open.helper.graalvm.ext.withWasmContext import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.HostFunction import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.Abort import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.AssertFail import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.EmscriptenDateNow import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.EmscriptenGetNow import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.EmscriptenGetNowIsMonotonic import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.EmscriptenResizeHeap import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.SyscallFchown32 import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.SyscallFstat64 import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.SyscallFtruncate64 import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.SyscallGetcwd import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.SyscallOpenat import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.SyscallUnlinkat import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.syscallLstat64 import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func.syscallStat64 import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.fn import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.fnVoid import ru.pixnews.wasm.sqlite.open.helper.host.WasmValueType.WebAssemblyTypes.F64 import ru.pixnews.wasm.sqlite.open.helper.host.WasmValueType.WebAssemblyTypes.I32 import ru.pixnews.wasm.sqlite.open.helper.host.WasmValueType.WebAssemblyTypes.I64 internal class EmscriptenEnvModuleBuilder( private val graalContext: Context, private val host: SqliteEmbedderHost, private val moduleName: String = ENV_MODULE_NAME, ) { private val envFunctions: List<HostFunction> = buildList { fnVoid( name = "abort", paramTypes = listOf(), nodeFactory = { language, module, _, functionName -> Abort(language, module, functionName) }, ) fnVoid( name = "__assert_fail", paramTypes = List(4) { I32 }, nodeFactory = { language, module, _, functionName -> AssertFail(language, module, functionName) }, ) fn( name = "emscripten_date_now", paramTypes = listOf(), retType = F64, nodeFactory = ::EmscriptenDateNow, ) fn( name = "emscripten_get_now", paramTypes = listOf(), retType = F64, nodeFactory = ::EmscriptenGetNow, ) fn( name = "_emscripten_get_now_is_monotonic", paramTypes = listOf(), retType = I32, nodeFactory = ::EmscriptenGetNowIsMonotonic, ) fn( name = "emscripten_resize_heap", paramTypes = listOf(I32), retType = I32, nodeFactory = ::EmscriptenResizeHeap, ) fnVoid("_localtime_js", listOf(I64, I32)) fn("_mmap_js", listOf(I32, I32, I32, I32, I64, I32, I32)) fn("_munmap_js", listOf(I32, I32, I32, I32, I32, I64)) // fnVoid("_localtime_js", listOf(I32, I32)) // fn("_mmap_js", listOf(I32, I32, I32, I32, I32, I32, I32)) // fn("_munmap_js", listOf(I32, I32, I32, I32, I32, I32)) fn("__syscall_chmod", listOf(I32, I32)) fn("__syscall_faccessat", List(4) { I32 }) fn("__syscall_fchmod", listOf(I32, I32)) fn( name = "__syscall_fchown32", paramTypes = List(3) { I32 }, retType = I32, nodeFactory = ::SyscallFchown32, ) fn("__syscall_fcntl64", List(3) { I32 }) fn("__syscall_fstat64", listOf(I32, I32), I32, ::SyscallFstat64) fn("__syscall_ftruncate64", listOf(I32, I64), I32, ::SyscallFtruncate64) fn( name = "__syscall_getcwd", paramTypes = listOf(I32, I32), retType = I32, nodeFactory = ::SyscallGetcwd, ) fn("__syscall_ioctl", List(3) { I32 }) fn("__syscall_mkdirat", List(3) { I32 }) fn("__syscall_newfstatat", List(4) { I32 }) fn( name = "__syscall_openat", paramTypes = List(4) { I32 }, retType = I32, nodeFactory = ::SyscallOpenat, ) fn("__syscall_readlinkat", List(4) { I32 }) fn("__syscall_rmdir", listOf(I32)) fn( name = "__syscall_stat64", paramTypes = listOf(I32, I32), retType = I32, nodeFactory = ::syscallStat64, ) fn( name = "__syscall_lstat64", paramTypes = listOf(I32, I32), retType = I32, nodeFactory = ::syscallLstat64, ) fn( name = "__syscall_unlinkat", paramTypes = List(3) { I32 }, retType = I32, nodeFactory = ::SyscallUnlinkat, ) fn("__syscall_utimensat", List(4) { I32 }) fnVoid("_tzset_js", List(4) { I32 }) } fun setupModule(): WasmInstance = graalContext.withWasmContext { wasmContext -> val envModule = WasmModule.create(moduleName, null) setupMemory(wasmContext, envModule) return setupWasmModuleFunctions(wasmContext, host, envModule, envFunctions) } @Suppress("MagicNumber", "LOCAL_VARIABLE_EARLY_DECLARATION") private fun setupMemory( context: WasmContext, envModule: WasmModule, ) { val minSize = 256L val maxSize: Long val is64Bit: Boolean if (context.contextOptions.supportMemory64()) { maxSize = Sizes.MAX_MEMORY_64_DECLARATION_SIZE is64Bit = true } else { maxSize = 32768 is64Bit = false } envModule.symbolTable().apply { val memoryIndex = memoryCount() allocateMemory(memoryIndex, minSize, maxSize, is64Bit, false, false, false) exportMemory(memoryIndex, "memory") } } companion object { private const val ENV_MODULE_NAME = "env" } }
0
Kotlin
0
0
8710b053eb5291ae3530e797741dfc09b138b305
6,956
wasm-sqlite-open-helper
Apache License 2.0
core/src/main/kotlin/knote/data/PageImpl.kt
DaemonicLabs
171,956,108
false
null
package knote.data import knote.api.Page import knote.script.PageScript import knote.util.MutableKObservableList import knote.util.MutableKObservableObject import java.io.File import java.nio.file.Path import kotlin.script.experimental.api.ScriptDiagnostic class PageImpl( override val id: String, file: File, fileContent: String = file.readText(), text: String = "", compiledScript: PageScript? = null, reports: List<ScriptDiagnostic>? = null ) : Page { override val textObject: MutableKObservableObject<Page, String> = MutableKObservableObject(text) override val fileObject: MutableKObservableObject<Page, File> = MutableKObservableObject(file) override val fileContentObject: MutableKObservableObject<Page, String> = MutableKObservableObject(fileContent) override val compiledScriptObject: MutableKObservableObject<Page, PageScript?> = MutableKObservableObject(compiledScript) override val reportsObject: MutableKObservableObject<Page, List<ScriptDiagnostic>?> = MutableKObservableObject(reports) override val resultObject: MutableKObservableObject<Page, Any?> = MutableKObservableObject(null) override val dependenciesObject: MutableKObservableObject<Page, Set<String>> = MutableKObservableObject(setOf()) override val fileInputs: MutableKObservableList<Path> = MutableKObservableList() override var text by textObject override var file by fileObject override var fileContent by fileContentObject override var compiledScript by compiledScriptObject override var reports by reportsObject override var result by resultObject override var dependencies by dependenciesObject var errored: Boolean = false }
2
Kotlin
0
3
a8e92a5cd738cb7b60b44c89ef0d6a5ac2514835
1,720
KNote
ISC License
app/src/main/java/io/horizontalsystems/bankwallet/modules/coin/overview/ui/MarketData.kt
horizontalsystems
142,825,178
false
null
package io.deus.wallet.modules.coin.overview.ui import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import io.deus.wallet.modules.coin.CoinDataItem import io.deus.wallet.ui.compose.ComposeAppTheme import io.deus.wallet.ui.compose.components.Badge import io.deus.wallet.ui.compose.components.CellSingleLineLawrenceSection import io.deus.wallet.ui.compose.components.subhead1_leah import io.deus.wallet.ui.compose.components.subhead2_grey @Preview @Composable fun MarketDataPreview() { val marketData = listOf( CoinDataItem(title = "Market Cap", value = "$123.34 B", rankLabel = "#555"), CoinDataItem(title = "Trading Volume", value = "112,112,112,112,112,112,112,112,112,112,112,112,112,112,112,112 ETH"), CoinDataItem(title = "Inception Date", value = "Jul 23, 2012"), ) ComposeAppTheme(darkTheme = false) { MarketData(marketData) } } @Composable fun MarketData(marketData: List<CoinDataItem>) { CellSingleLineLawrenceSection(marketData) { marketDataLine -> Row( modifier = Modifier .fillMaxSize() .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically ) { subhead2_grey(text = marketDataLine.title) marketDataLine.rankLabel?.let { Badge(modifier = Modifier.padding(start = 8.dp), it) } marketDataLine.value?.let { value -> subhead1_leah( modifier = Modifier .weight(1f) .padding(start = 8.dp), text = value, textAlign = TextAlign.End, maxLines = 1, overflow = TextOverflow.Ellipsis ) } } } }
168
null
364
895
218cd81423c570cdd92b1d5161a600d07c35c232
2,211
unstoppable-wallet-android
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/integration/AttendanceReasonIntegrationTest.kt
ministryofjustice
533,838,017
false
{"Kotlin": 3642217, "Shell": 9529, "Dockerfile": 1478}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.http.MediaType import org.springframework.test.web.reactive.server.WebTestClient import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.attendedReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.autoSuspendedReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.cancelledReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.clashReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.notRequiredReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.otherReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.refusedReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.restReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.sickReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration.testdata.suspendedReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model.AttendanceReason import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.resource.ROLE_PRISON class AttendanceReasonIntegrationTest : IntegrationTestBase() { @Test fun `get list of attendance reasons`() { assertThat(webTestClient.getAttendanceReasons()!!).containsExactlyInAnyOrder( sickReason, refusedReason, notRequiredReason, restReason, clashReason, otherReason, suspendedReason, autoSuspendedReason, cancelledReason, attendedReason, ) } private fun WebTestClient.getAttendanceReasons() = get() .uri("/attendance-reasons") .accept(MediaType.APPLICATION_JSON) .headers(setAuthorisation(roles = listOf(ROLE_PRISON))) .exchange() .expectStatus().isOk .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBodyList(AttendanceReason::class.java) .returnResult().responseBody }
4
Kotlin
0
1
d3db16ab9a7b8dba06b25e4f43207d4c6a9155ea
2,272
hmpps-activities-management-api
MIT License
app/src/main/java/org/covidwatch/android/data/exposureinformation/ExposureInformationRepository.kt
thymetech
278,956,982
true
{"Kotlin": 236262, "Java": 10738}
package org.covidwatch.android.data.exposureinformation import androidx.lifecycle.LiveData import kotlinx.coroutines.withContext import org.covidwatch.android.data.CovidExposureInformation import org.covidwatch.android.domain.AppCoroutineDispatchers class ExposureInformationRepository( private val local: ExposureInformationLocalSource, private val dispatchers: AppCoroutineDispatchers ) { suspend fun saveExposureInformation(exposureInformation: List<CovidExposureInformation>) = withContext(dispatchers.io) { local.saveExposureInformation(exposureInformation) } fun exposureInformation(): LiveData<List<CovidExposureInformation>> { return local.exposureInformation() } suspend fun exposures() = withContext(dispatchers.io) { local.exposures() } suspend fun reset() = withContext(dispatchers.io) { local.reset() } }
0
null
0
0
b66ecf8e313fb12a7a27565c5d26fcab181d9e74
911
covidwatch-android-en
Apache License 2.0
src/main/javatests/com/google/summit/translation/StatementTest.kt
google
458,007,554
false
{"Kotlin": 309165, "Starlark": 11839}
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.summit.translation import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import com.google.summit.ast.CompilationUnit import com.google.summit.ast.Node import com.google.summit.ast.declaration.ClassDeclaration import com.google.summit.ast.expression.LiteralExpression import com.google.summit.ast.expression.VariableExpression import com.google.summit.ast.statement.BreakStatement import com.google.summit.ast.statement.ContinueStatement import com.google.summit.ast.statement.DmlStatement import com.google.summit.ast.statement.DoWhileLoopStatement import com.google.summit.ast.statement.EnhancedForLoopStatement import com.google.summit.ast.statement.ExpressionStatement import com.google.summit.ast.statement.ForLoopStatement import com.google.summit.ast.statement.IfStatement import com.google.summit.ast.statement.ReturnStatement import com.google.summit.ast.statement.RunAsStatement import com.google.summit.ast.statement.SwitchStatement import com.google.summit.ast.statement.ThrowStatement import com.google.summit.ast.statement.TryStatement import com.google.summit.ast.statement.UntranslatedStatement import com.google.summit.ast.statement.VariableDeclarationStatement import com.google.summit.ast.statement.WhileLoopStatement import com.google.summit.ast.traversal.DfsWalker import com.google.summit.testing.TranslateHelpers import kotlin.test.assertNotNull import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class StatementTest { /** Counts the number of untranslated statement nodes in the AST. */ private fun countUntranslatedStatements(node: Node): Long { return DfsWalker(node, DfsWalker.Ordering.PRE_ORDER) .stream() .filter { it is UntranslatedStatement } .count() } /** Concatenates the string into a method body and returns the AST. */ private fun parseApexStatementInCode(statement: String): CompilationUnit { return TranslateHelpers.parseAndTranslate( """ class Test { void f() { $statement } } """ ) } @Test fun methodBody_is_compoundStatement() { val compilationUnit = parseApexStatementInCode("1; return 2;") val classDecl = compilationUnit.typeDeclaration as ClassDeclaration val methodDecl = classDecl.methodDeclarations.first() assertNotNull(methodDecl.body) assertThat(methodDecl.body?.statements).hasSize(2) TranslateHelpers.assertFullyTranslated(compilationUnit) } @Test fun ifStatement_condition_is_variableExpression() { val root = parseApexStatementInCode("if (x) { }") val node = TranslateHelpers.findFirstNodeOfType<IfStatement>(root) assertNotNull(node) assertThat(node.condition).isInstanceOf(VariableExpression::class.java) val conditionVariable = node.condition as VariableExpression assertThat(conditionVariable.id.asCodeString()).isEqualTo("x") assertWithMessage("Without `else`, the statement should be null") .that(node.elseStatement) .isNull() } @Test fun ifStatement_has_elseStatement() { val root = parseApexStatementInCode("if (x) { } else { }") val node = TranslateHelpers.findFirstNodeOfType<IfStatement>(root) assertNotNull(node) assertWithMessage("Since `else` is present (even if empty), the statement should not be null") .that(node.elseStatement) .isNotNull() } @Test fun switchStatement_condition_is_variableExpression() { val root = parseApexStatementInCode("switch on x { when else { } }") val node = TranslateHelpers.findFirstNodeOfType<SwitchStatement>(root) assertNotNull(node) assertThat(node.condition).isInstanceOf(VariableExpression::class.java) val conditionVariable = node.condition as VariableExpression assertThat(conditionVariable.id.asCodeString()).isEqualTo("x") val whenClause = node.whenClauses.first() assertThat(whenClause).isInstanceOf(SwitchStatement.WhenElse::class.java) } @Test fun switchStatement_whenClause_hasTwoValues() { val root = parseApexStatementInCode("switch on x { when value1, value2 { } }") val node = TranslateHelpers.findFirstNodeOfType<SwitchStatement.WhenValue>(root) assertNotNull(node) assertThat(node.values).hasSize(2) assertWithMessage( "Identifiers in `when` clauses are enum values, which should be a `VariableExpression`" ) .that(node.values.first()) .isInstanceOf(VariableExpression::class.java) } @Test fun switchStatement_whenClause_hasLiteralValues() { val root = parseApexStatementInCode( """ switch on x { when 0 { } when 1234L { } when 'string' { } when null { } }""" ) assertThat(TranslateHelpers.findFirstNodeOfType<LiteralExpression.IntegerVal>(root)).isNotNull() assertThat(TranslateHelpers.findFirstNodeOfType<LiteralExpression.LongVal>(root)).isNotNull() assertThat(TranslateHelpers.findFirstNodeOfType<LiteralExpression.StringVal>(root)).isNotNull() assertThat(TranslateHelpers.findFirstNodeOfType<LiteralExpression.NullVal>(root)).isNotNull() } @Test fun switchStatement_whenClause_declaresVariable() { val root = parseApexStatementInCode("switch on x { when Type variable { } }") val node = TranslateHelpers.findFirstNodeOfType<SwitchStatement.WhenType>(root) assertNotNull(node) assertThat(node.type.asCodeString()).isEqualTo("Type") assertThat(node.downcast.declarations).hasSize(1) val varDecl = node.downcast.declarations.first() assertThat(varDecl.type.asCodeString()).isEqualTo("Type") assertThat(varDecl.id.asCodeString()).isEqualTo("variable") assertWithMessage("Variables declared in `when` clauses should not have an initializer") .that(varDecl.initializer) .isNull() } @Test fun traditionalForStatement_declares_twoVariables() { val root = parseApexStatementInCode("for (int i=0, j=0; i+j<10; i++, j++) {}") val node = TranslateHelpers.findFirstNodeOfType<ForLoopStatement>(root) assertNotNull(node) assertNotNull(node.declarationGroup) assertThat(node.declarationGroup!!.declarations).hasSize(2) assertThat(node.initializations).isEmpty() assertThat(node.condition).isNotNull() assertThat(node.updates).hasSize(2) } @Test fun traditionalForStatement_initializes_twoExpressions() { val root = parseApexStatementInCode("for (i=0, j=0; ; ) {}") val node = TranslateHelpers.findFirstNodeOfType<ForLoopStatement>(root) assertNotNull(node) assertThat(node.declarationGroup).isNull() assertThat(node.initializations).hasSize(2) assertThat(node.condition).isNull() assertThat(node.updates).isEmpty() } @Test fun enhancedForStatement_has_variableDeclaration() { val root = parseApexStatementInCode("for (String s : collection) {}") val node = TranslateHelpers.findFirstNodeOfType<EnhancedForLoopStatement>(root) assertNotNull(node) assertThat(node.element.declarations).hasSize(1) val varDecl = node.element.declarations.first() assertThat(varDecl.type.asCodeString()).isEqualTo("String") assertThat(varDecl.id.asCodeString()).isEqualTo("s") assertThat(varDecl.initializer).isNull() } @Test fun whileStatement_condition_is_variableExpression() { val root = parseApexStatementInCode("while (x) {}") val node = TranslateHelpers.findFirstNodeOfType<WhileLoopStatement>(root) assertNotNull(node) assertThat(node.condition).isInstanceOf(VariableExpression::class.java) val conditionVariable = node.condition as VariableExpression assertThat(conditionVariable.id.asCodeString()).isEqualTo("x") } @Test fun doWhileStatement_condition_is_variableExpression() { val root = parseApexStatementInCode("do {} while(x);") val node = TranslateHelpers.findFirstNodeOfType<DoWhileLoopStatement>(root) assertNotNull(node) assertThat(node.condition).isInstanceOf(VariableExpression::class.java) val conditionVariable = node.condition as VariableExpression assertThat(conditionVariable.id.asCodeString()).isEqualTo("x") } @Test fun tryStatement_has_finallyBlock() { val root = parseApexStatementInCode("try {} finally {}") val node = TranslateHelpers.findFirstNodeOfType<TryStatement>(root) assertNotNull(node) assertThat(node.catchBlocks).hasSize(0) assertThat(node.finallyBlock).isNotNull() } @Test fun tryStatement_has_twoCatchBlocks() { val root = parseApexStatementInCode("try {} catch (X x) {} catch (Y y) {}") val node = TranslateHelpers.findFirstNodeOfType<TryStatement>(root) assertNotNull(node) assertThat(node.catchBlocks).hasSize(2) assertThat(node.finallyBlock).isNull() } @Test fun catchBlock_declares_variable() { val root = parseApexStatementInCode("try {} catch (Exception e) {}") val node = TranslateHelpers.findFirstNodeOfType<TryStatement>(root) assertNotNull(node) assertThat(node.catchBlocks).hasSize(1) val catchBlock = node.catchBlocks.first() assertThat(catchBlock.exception.declarations).hasSize(1) val exceptionDecl = catchBlock.exception.declarations.first() assertThat(exceptionDecl.type.asCodeString()).isEqualTo("Exception") assertThat(exceptionDecl.id.asCodeString()).isEqualTo("e") assertThat(node.finallyBlock).isNull() } @Test fun returnStatement_translation_hasOneChild() { val root = parseApexStatementInCode("return 7;") val node = TranslateHelpers.findFirstNodeOfType<ReturnStatement>(root) assertNotNull(node) assertWithMessage("Node should have one child").that(node.getChildren()).hasSize(1) } @Test fun throwStatement_translation_hasOneChild() { val root = parseApexStatementInCode("throw e;") val node = TranslateHelpers.findFirstNodeOfType<ThrowStatement>(root) assertNotNull(node) assertWithMessage("Node should have one child").that(node.getChildren()).hasSize(1) } @Test fun breakStatement_translation_isLeafNode() { val root = parseApexStatementInCode("break;") val node = TranslateHelpers.findFirstNodeOfType<BreakStatement>(root) assertNotNull(node) assertWithMessage("Node should have no children").that(node.getChildren()).isEmpty() } @Test fun continueStatement_translation_isLeafNode() { val root = parseApexStatementInCode("continue;") val node = TranslateHelpers.findFirstNodeOfType<ContinueStatement>(root) assertNotNull(node) assertWithMessage("Node should have no children").that(node.getChildren()).isEmpty() } @Test fun insertDmlStatement_translation_hasOneChild() { val root = parseApexStatementInCode("insert obj;") val node = TranslateHelpers.findFirstNodeOfType<DmlStatement.Insert>(root) assertNotNull(node) assertWithMessage("Node should have one child").that(node.getChildren()).hasSize(1) assertWithMessage("Node should have default/unspecified access") .that(node.access) .isNull() } @Test fun updateDmlStatement_translation_hasOneChild() { val root = parseApexStatementInCode("update obj;") val node = TranslateHelpers.findFirstNodeOfType<DmlStatement.Update>(root) assertNotNull(node) assertWithMessage("Node should have one child").that(node.getChildren()).hasSize(1) } @Test fun deleteDmlStatement_translation_hasOneChild() { val root = parseApexStatementInCode("delete obj;") val node = TranslateHelpers.findFirstNodeOfType<DmlStatement.Delete>(root) assertNotNull(node) assertWithMessage("Node should have one child").that(node.getChildren()).hasSize(1) } @Test fun undeleteDmlStatement_translation_hasOneChild() { val root = parseApexStatementInCode("undelete obj;") val node = TranslateHelpers.findFirstNodeOfType<DmlStatement.Undelete>(root) assertNotNull(node) assertWithMessage("Node should have one child").that(node.getChildren()).hasSize(1) } @Test fun upsertDmlStatement_translation_hasTwoChildren() { val root = parseApexStatementInCode("upsert obj field;") val node = TranslateHelpers.findFirstNodeOfType<DmlStatement.Upsert>(root) assertNotNull(node) assertWithMessage("Node should have two children").that(node.getChildren()).hasSize(2) } @Test fun mergeDmlStatement_translation_hasTwoChildren() { val root = parseApexStatementInCode("merge objto obj;") val node = TranslateHelpers.findFirstNodeOfType<DmlStatement.Merge>(root) assertNotNull(node) assertWithMessage("Node should have two children").that(node.getChildren()).hasSize(2) } @Test fun runAsStatement_translation_hasContextExpresssions() { val root = parseApexStatementInCode("system.runAs(user) { }") val node = TranslateHelpers.findFirstNodeOfType<RunAsStatement>(root) assertNotNull(node) assertWithMessage("Node should have one user context").that(node.contexts).hasSize(1) } @Test fun localVariableDeclarationStatement_translation_wrapsVariableDeclaration() { val root = parseApexStatementInCode("String s = null, t = 'hello';") val node = TranslateHelpers.findFirstNodeOfType<VariableDeclarationStatement>(root) assertNotNull(node) assertWithMessage("The statement should declare two variables") .that(node.group.declarations) .hasSize(2) val firstDecl = node.group.declarations.first() assertThat(firstDecl.id.asCodeString()).isEqualTo("s") assertThat(firstDecl.type.asCodeString()).isEqualTo("String") assertWithMessage("Variable 's' should be initialized to null") .that(firstDecl.initializer) .isInstanceOf(LiteralExpression.NullVal::class.java) } @Test fun expressionStatement_translation_hasOneChild() { val root = parseApexStatementInCode("x + y;") val node = TranslateHelpers.findFirstNodeOfType<ExpressionStatement>(root) assertNotNull(node) assertWithMessage("Node should have one child").that(node.getChildren()).hasSize(1) } @Test fun dmlStatement_translation_withSystemMode() { val root = parseApexStatementInCode("upsert as system obj field;") val node = TranslateHelpers.findFirstNodeOfType<DmlStatement>(root) assertNotNull(node) assertWithMessage("Node should have system access") .that(node.access) .isEqualTo(DmlStatement.AccessLevel.SYSTEM_MODE) } @Test fun dmlStatement_translation_withUserMode() { val root = parseApexStatementInCode("insert as user obj;") val node = TranslateHelpers.findFirstNodeOfType<DmlStatement>(root) assertNotNull(node) assertWithMessage("Node should have user access") .that(node.access) .isEqualTo(DmlStatement.AccessLevel.USER_MODE) } }
3
Kotlin
6
34
9b981b144878ed51ffb4bcc0594541edf5f167f9
15,364
summit-ast
Apache License 2.0
sdk/core/src/main/java/com/rocbillow/core/extension/Click.kt
wptdxii
278,525,387
false
null
package com.rocbillow.core.extension import android.view.View import androidx.core.view.postDelayed import com.jakewharton.rxbinding4.view.clicks import io.reactivex.rxjava3.disposables.Disposable import java.util.concurrent.TimeUnit const val THROTTLE_DURATION = 1500L inline fun View.setOnThrottleClickListenerByRx(crossinline onClick: (View) -> Unit): Disposable = clicks() .throttleFirst(THROTTLE_DURATION, TimeUnit.MILLISECONDS) .subscribe { onClick(this) } inline fun View.setOnThrottleClickListenerByClickable(crossinline onClick: (View) -> Unit) { setOnClickListener { onClick(it) with(it) { isClickable = false postDelayed(THROTTLE_DURATION) { isClickable = true } } } } inline fun View.setOnThrottleClickListener(crossinline onClick: (View) -> Unit) { var lastTimeMillis = 0L val currentTimeMillis = System.currentTimeMillis() if (currentTimeMillis - lastTimeMillis > THROTTLE_DURATION) { setOnClickListener { onClick(it) lastTimeMillis = System.currentTimeMillis() } } } inline fun View.setOnDoubleClickListener(crossinline onClick: (View) -> Unit) { var isClickedOnce = false setOnClickListener { if (!isClickedOnce) { isClickedOnce = true postDelayed(1000L) { isClickedOnce = false } return@setOnClickListener } onClick(this) } }
0
Kotlin
0
0
33fe10f5686664f99b1b0e37c9391562e81e56bf
1,378
kit-android
Apache License 2.0
app/src/main/java/net/cat_ears/kanmusuviewer/model/ShipImageCache.kt
veigr
155,668,775
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Markdown": 2, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 21, "XML": 23, "Java": 1}
package net.cat_ears.kanmusuviewer.model import java.io.File interface IShipImageCacheRepository { fun cacheFile(ship: Ship, isDamaged: Boolean): IShipImageCache } interface IShipImageCache { fun exists(): Boolean fun writeBytes(bytes: ByteArray) fun readBytes(): ByteArray } class ShipImageCacheRepository(private val cacheDir: File) : IShipImageCacheRepository { override fun cacheFile(ship: Ship, isDamaged: Boolean): IShipImageCache { val path = "${ship.id.toString().padStart(4, '0')}_${ship.imageVersion.toString().padStart(3, '0')}_${if (isDamaged) "damaged" else "undamaged"}.png" return ShipImageCache(File(cacheDir, path)) } } class ShipImageCache(private val cacheFile: File) : IShipImageCache { override fun exists(): Boolean = cacheFile.exists() override fun writeBytes(bytes: ByteArray) { if(!cacheFile.parentFile.exists()) cacheFile.parentFile.mkdir() cacheFile.writeBytes(bytes) } override fun readBytes(): ByteArray = cacheFile.readBytes() }
0
Kotlin
0
0
95a9e5f7690db88c88726f39c5f868c44fe6e41c
1,037
KanMusuViewer.Android
Apache License 2.0
sample-compose/app/routing/src/main/kotlin/ru/kode/way/sample/compose/app/routing/di/AppFlowComponent.kt
appKODE
607,636,487
false
{"Kotlin": 208436, "ANTLR": 3639}
package ru.kode.way.sample.compose.app.routing.di import dagger.Module import dagger.Provides import dagger.Subcomponent import ru.kode.way.FlowNode import ru.kode.way.NodeBuilder import ru.kode.way.sample.compose.app.routing.AppFlowNode import ru.kode.way.sample.compose.app.routing.AppNodeBuilder import ru.kode.way.sample.compose.login.routing.LoginFlow import ru.kode.way.sample.compose.login.routing.di.LoginFlowComponent import ru.kode.way.sample.compose.main.parallel.routing.MainParallelFlow import ru.kode.way.sample.compose.main.parallel.routing.di.MainParallelFlowComponent import ru.kode.way.sample.compose.main.routing.MainFlow import ru.kode.way.sample.compose.main.routing.di.MainFlowComponent import javax.inject.Provider import javax.inject.Scope @Scope annotation class AppFlowScope @Subcomponent(modules = [AppFlowModule::class]) @AppFlowScope interface AppFlowComponent { fun loginFlowComponent(): LoginFlowComponent fun mainFlowComponent(): MainFlowComponent fun mainParallelFlowComponent(): MainParallelFlowComponent fun nodeFactory(): AppNodeBuilder.Factory } @Module object AppFlowModule { @Provides @AppFlowScope fun provideNodeFactory(component: AppFlowComponent, appFlowNode: Provider<AppFlowNode>): AppNodeBuilder.Factory { return object : AppNodeBuilder.Factory { override fun createRootNode(): FlowNode<*> = appFlowNode.get() override fun createMainNodeBuilder(): NodeBuilder = MainFlow.nodeBuilder(component.mainFlowComponent()) override fun createLoginNodeBuilder(): NodeBuilder = LoginFlow.nodeBuilder(component.loginFlowComponent()) override fun createMainParallelNodeBuilder(): NodeBuilder = MainParallelFlow.nodeBuilder(component.mainParallelFlowComponent()) } } }
1
Kotlin
1
1
c73afebf44f9653091e967bbe7b8470d9b3b0192
1,763
way
MIT License
acrarium/src/main/kotlin/com/faendir/acra/model/view/Queries.kt
F43nd1r
91,593,043
false
null
/* * (C) Copyright 2018 <NAME> (https://github.com/F43nd1r) * * 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.faendir.acra.model.view import com.faendir.acra.model.App import com.faendir.acra.model.QApp import com.faendir.acra.model.QBug import com.faendir.acra.model.QDevice import com.faendir.acra.model.QReport import com.faendir.acra.model.QStacktrace import com.querydsl.core.types.Expression import com.querydsl.core.types.Projections import com.querydsl.core.types.dsl.Expressions import com.querydsl.core.types.dsl.StringTemplate import com.querydsl.jpa.impl.JPAQuery import javax.persistence.EntityManager /** * @author lukas * @since 30.05.18 */ object Queries { private val V_BUG = JPAQuery<Any>().from(QBug.bug) .leftJoin(QStacktrace.stacktrace1) .on(QStacktrace.stacktrace1.bug.eq(QBug.bug)) .leftJoin(QReport.report) .on(QReport.report.stacktrace.eq(QStacktrace.stacktrace1)) .leftJoin(QBug.bug.solvedVersion).fetchJoin() .select( QVBug( QBug.bug, QReport.report.date.max(), QReport.report.count(), QStacktrace.stacktrace1.version.code.max(), QReport.report.installationId.countDistinct() ) ) .groupBy(QBug.bug) private val V_APP = JPAQuery<Any>().from(QApp.app) .leftJoin(QBug.bug) .on(QBug.bug.app.eq(QApp.app)) .leftJoin(QStacktrace.stacktrace1) .on(QStacktrace.stacktrace1.bug.eq(QBug.bug)) .leftJoin(QReport.report) .on(QReport.report.stacktrace.eq(QStacktrace.stacktrace1)) .select(QVApp(QApp.app, QBug.bug.countDistinct(), QReport.report.count())) .groupBy(QApp.app) private val V_REPORT = JPAQuery<Any>().from(QReport.report) .leftJoin(QStacktrace.stacktrace1).on(QStacktrace.stacktrace1.eq(QReport.report.stacktrace)) .join(QStacktrace.stacktrace1.bug, QBug.bug).fetchJoin() .join(QBug.bug.app, QApp.app).fetchJoin() .leftJoin(QDevice.device1).on(QReport.report.phoneModel.eq(QDevice.device1.model).and(QReport.report.device.eq(QDevice.device1.device))) fun selectVBug(entityManager: EntityManager): JPAQuery<VBug> { return V_BUG.clone(entityManager) } fun selectVApp(entityManager: EntityManager): JPAQuery<VApp> { return V_APP.clone(entityManager) } @Suppress("UNCHECKED_CAST") fun selectVReport(entityManager: EntityManager, app: App): JPAQuery<VReport> { return V_REPORT.clone(entityManager).select( QVReport( QStacktrace.stacktrace1, QReport.report.id, QReport.report.date, QReport.report.androidVersion, QReport.report.phoneModel, QReport.report.installationId, QReport.report.isSilent, QDevice.device1.marketingName.coalesce(QReport.report.phoneModel), Projections.list(*app.configuration.customReportColumns.map { customReportColumnExpression(it) }.toTypedArray()) as Expression<out List<String>> ) ) } fun customReportColumnExpression(customColumn: String): StringTemplate = Expressions.stringTemplate( "COALESCE(JSON_UNQUOTE(JSON_EXTRACT(content, {0})), '')", "$.$customColumn" ) }
13
Kotlin
32
142
06d66b282910ffe15847d51e2fef62dc18f0b074
3,877
Acrarium
Apache License 2.0
src/test/kotlin/com/jordantipton/kinesisexample/writer/StockTradeGeneratorTest.kt
JordanTipton
134,092,629
false
{"Maven POM": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Shell": 1, "Kotlin": 11, "JAR Manifest": 2, "Java": 2, "JSON": 1, "XML": 5}
package com.jordantipton.kinesisexample.writer import org.junit.Assert import org.junit.Test class StockTradeGeneratorTest { @Test fun getRandomStockTradeTest() { val stockTradeGenerator = StockTradeGenerator() val randomStockTrade = stockTradeGenerator.getRandomTrade() Assert.assertNotNull(randomStockTrade.getId()) Assert.assertNotNull(randomStockTrade.getTickerSymbol()) Assert.assertNotNull(randomStockTrade.getPrice()) Assert.assertNotNull(randomStockTrade.getQuantity()) Assert.assertNotNull(randomStockTrade.getTradeType()) } }
1
null
1
1
cccf2adc42ff113bd504c8a37819e32fd7af752b
605
kinesisexample
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/presencetracing/checkins/qrcode/TraceLocationVerifier.kt
rgrenz
390,331,768
false
null
package de.rki.coronawarnapp.presencetracing.checkins.qrcode import androidx.annotation.StringRes import dagger.Reusable import de.rki.coronawarnapp.R import de.rki.coronawarnapp.server.protocols.internal.pt.TraceLocationOuterClass import javax.inject.Inject @Reusable class TraceLocationVerifier @Inject constructor() { @Suppress("ReturnCount") fun verifyTraceLocation(payload: TraceLocationOuterClass.QRCodePayload): VerificationResult { val traceLocation = payload.traceLocation() if (traceLocation.description.isEmpty()) { return VerificationResult.Invalid.Description } if (traceLocation.description.length > QR_CODE_DESCRIPTION_MAX_LENGTH) { return VerificationResult.Invalid.Description } if (traceLocation.description.lines().size > 1) { return VerificationResult.Invalid.Description } if (traceLocation.address.isEmpty()) { return VerificationResult.Invalid.Address } if (traceLocation.address.length > QR_CODE_ADDRESS_MAX_LENGTH) { return VerificationResult.Invalid.Address } if (traceLocation.address.lines().size > 1) { return VerificationResult.Invalid.Address } // If both are 0 do nothing else check start is smaller than end or return error if ( !(payload.locationData.startTimestamp == 0L && payload.locationData.endTimestamp == 0L) && payload.locationData.startTimestamp > payload.locationData.endTimestamp ) { return VerificationResult.Invalid.StartEndTime } if (traceLocation.cryptographicSeed.size != CROWD_NOTIFIER_CRYPTO_SEED_LENGTH) { return VerificationResult.Invalid.CryptographicSeed } return VerificationResult.Valid( VerifiedTraceLocation(payload) ) } sealed class VerificationResult { data class Valid(val verifiedTraceLocation: VerifiedTraceLocation) : VerificationResult() sealed class Invalid(@StringRes val errorTextRes: Int) : VerificationResult() { object Description : Invalid(R.string.trace_location_checkins_qr_code_invalid_description) object Address : Invalid(R.string.trace_location_checkins_qr_code_invalid_address) object StartEndTime : Invalid(R.string.trace_location_checkins_qr_code_invalid_times) object CryptographicSeed : Invalid(R.string.trace_location_checkins_qr_code_invalid_cryptographic_seed) } } companion object { private const val CROWD_NOTIFIER_CRYPTO_SEED_LENGTH = 16 private const val QR_CODE_DESCRIPTION_MAX_LENGTH = 100 private const val QR_CODE_ADDRESS_MAX_LENGTH = 100 } }
1
null
1
1
bd2b989daff48881949402dbbc8827a1d3806425
2,793
cwa-app-android
Apache License 2.0
retrofit-kx-android-sample/src/main/kotlin/io/github/retrofitx/android/products/details/ProductDetailsEvent.kt
agamula90
600,692,053
false
{"Kotlin": 193895}
package io.github.retrofitx.android.products.details import io.github.retrofitx.android.dto.IdError sealed class ProductDetailsEvent { class ShowApiErrorMessage(val error: IdError): ProductDetailsEvent() object ShowConnectionErrorMessage: ProductDetailsEvent() }
0
Kotlin
0
3
8c9fcfc6f6e08aaf524675c4ba588d7b25da4a10
273
retrofit-kx
Apache License 2.0
born2crawl-core/src/main/java/com/arthurivanets/born2crawl/TraversalAlgorithm.kt
arthur3486
609,665,683
false
{"Kotlin": 134860, "Shell": 541}
package com.arthurivanets.born2crawl /** * A set of supported crawling algorithms. */ enum class TraversalAlgorithm { /** * A breadth-first search data graph traversal (processing) algorithm. */ BFS, /** * A depth-first search data graph traversal (processing) algorithm. */ DFS, }
0
Kotlin
0
8
8d63628afdaacdfe8f7db17677f7d796e3e5e758
324
born2crawl
Apache License 2.0
app/src/main/java/no/mhl/swap/data/local/SwapDatabase.kt
maxhvesser
231,920,043
false
null
package no.mhl.swap.data.local import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import no.mhl.swap.data.local.converters.Converters import no.mhl.swap.data.local.dao.ExchangeDao import no.mhl.swap.data.local.dao.RateDao import no.mhl.swap.data.model.Exchange import no.mhl.swap.data.model.Rate @Database( entities = [ Rate::class, Exchange::class ], version = 2, exportSchema = false ) @TypeConverters( Converters::class ) abstract class SwapDatabase : RoomDatabase() { // region Rates abstract fun rateDao(): RateDao // endregion // region Exchange abstract fun exchangeDao(): ExchangeDao // endregion }
0
Kotlin
2
2
dc309954ed3ddf5ebe094e56fdb5339d18666ef8
721
swap-android
Apache License 2.0
web3walletcore/src/commonMain/kotlin/com/sonsofcrypto/web3walletcore/modules/improvementProposal/ImprovementProposalWireframe.kt
sonsofcrypto
454,978,132
false
{"Kotlin": 1330889, "Swift": 970782, "Objective-C": 77663, "Jupyter Notebook": 20914, "Go": 20697, "C": 15793, "Java": 12789, "Shell": 4282, "JavaScript": 1718}
package com.sonsofcrypto.web3walletcore.modules.improvementProposal import com.sonsofcrypto.web3walletcore.services.improvementProposals.ImprovementProposal data class ImprovementProposalWireframeContext( /** Proposal to display details of */ val proposal: ImprovementProposal, ) sealed class ImprovementProposalWireframeDestination { /** Vote on proposal */ data class Vote( val proposal: ImprovementProposal ): ImprovementProposalWireframeDestination() /** Dismissed wireframe */ object Dismiss: ImprovementProposalWireframeDestination() } interface ImprovementProposalWireframe { /** Present proposal */ fun present() /** Navigate to new destination screen */ fun navigate(destination: ImprovementProposalWireframeDestination) }
1
Kotlin
2
6
d86df4845a1f60624dffa179ce6507ede3222186
787
web3wallet
MIT License
buildSrc/src/main/kotlin/ru/surfstudio/android/build/exceptions/UnauthorizedException.kt
surfstudio
175,407,898
false
null
package ru.surfstudio.android.build.exceptions import org.gradle.api.GradleException /** * Unauthorized user */ class UnauthorizedException(message: String) : GradleException(message)
1
null
2
27
5f68262ac148bc090c600121295f81c7ce3486c0
187
EasyAdapter
Apache License 2.0
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/scene/entity/EntityFightPropUpdateNotify.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.scene.entity import org.anime_game_servers.core.base.Version.GI_CB1 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.ProtoCommand @AddedIn(GI_CB1) @ProtoCommand(NOTIFY) internal interface EntityFightPropNotify { var entityId: Int var fightPropMap: Map<Int, Float> }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
468
anime-game-multi-proto
MIT License
afterpay/src/main/kotlin/com/afterpay/android/internal/AfterpayCheckoutCompletion.kt
afterpay
279,474,371
false
null
package com.afterpay.android.internal import kotlinx.serialization.Serializable @Serializable internal data class AfterpayCheckoutCompletion( val status: Status, val orderToken: String ) { @Suppress("UNUSED_PARAMETER") @Serializable internal enum class Status(statusString: String) { SUCCESS("SUCCESS"), CANCELLED("CANCELLED") } }
0
Kotlin
5
8
fc2e10abc31eb35c36adda6ffd0e5affdafc8756
374
sdk-android
Apache License 2.0
app/src/main/java/com/sakethh/linkora/data/remote/localization/LocalizationRepo.kt
sakethpathike
648,784,316
false
{"Kotlin": 1590874}
package com.sakethh.linkora.data.remote.localization import com.sakethh.linkora.data.RequestResult import com.sakethh.linkora.data.local.localization.language.translations.Translation import com.sakethh.linkora.data.remote.localization.model.RemoteLocalizationInfoDTO interface LocalizationRepo { suspend fun getRemoteStrings(languageCode: String): RequestResult<List<Translation>> suspend fun getRemoteLanguages(): RequestResult<RemoteLocalizationInfoDTO> }
9
Kotlin
11
307
ebbd4669a8e762587267560f60d0ec3339e9e75f
469
Linkora
MIT License
src/main/java/org/stevenlowes/tools/lifxcontroller/values/Color.kt
stevenwaterman
126,380,593
true
{"Kotlin": 53966}
package org.stevenlowes.tools.lifxcontroller.values data class Color(var hue: Hue = Hue.RED, var saturation: Level = Level.MAX, var brightness: Level = Level.MAX, var temp: Temp = Temp.MEDIUM){ companion object { val RANDOM: Color get() = Color(hue = Hue.RANDOM) val WHITE: Color = Color(saturation = Level.MIN) val BLACK: Color = Color(brightness = Level.MIN, saturation = Level.MIN) } }
0
Kotlin
0
0
7b17808a6ca08e7efc7cefe937be1a5d0eb4f4b5
473
LifxCommander_v1.0
MIT License
src/main/kotlin/no/nav/hm/grunndata/db/hmdb/HmDbBatch.kt
navikt
555,213,385
false
null
package no.nav.hm.grunndata.db.hmdb import io.micronaut.data.annotation.GeneratedValue import io.micronaut.data.annotation.Id import io.micronaut.data.annotation.MappedEntity import no.nav.hm.grunndata.db.supplier.Supplier import no.nav.hm.grunndata.db.supplier.SupplierInfo import java.time.LocalDateTime import javax.persistence.Table @MappedEntity @Table(name="hmdbbatch_v1") data class HmDbBatch( @field:GeneratedValue @field:Id var id: Long = -1L, val name: String, val updated: LocalDateTime = LocalDateTime.now(), val syncfrom: LocalDateTime = LocalDateTime.now() ) const val SYNC_AGREEMENTS="agreements" const val SYNC_PRODUCTS="products" const val SYNC_SUPPLIERS="suppliers"
0
Kotlin
0
1
72d24067e6263f57ed34f8a85bcdf1ac6cab4c93
710
hm-grunndata-db
MIT License
feature/overview/src/main/java/com/uxstate/overview/presentation/settings_screen/components/SettingsItem.kt
Tonnie-Dev
518,721,038
false
{"Kotlin": 160830}
package com.uxstate.overview.presentation.settings_screen.components import android.content.res.Configuration import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.uxstate.ui.theme.CountriesPadTheme import com.uxstate.ui.theme.LocalSpacing import com.uxstate.ui.R @Composable fun SettingsItem( modifier: Modifier = Modifier, @StringRes title: Int, @StringRes subTitle: Int, @DrawableRes icon:Int, onClickSetting: () -> Unit ) { val spacing = LocalSpacing.current Row( modifier = modifier .clickable(onClick = onClickSetting) .padding(spacing.spaceSmall) .fillMaxWidth() ) { Icon( painter = painterResource(id = icon), contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(spacing.spaceMedium) ) Column(modifier = Modifier.padding(spacing.spaceMedium)) { Text( text = stringResource(id = title), style = MaterialTheme.typography.bodyLarge ) Text( text = stringResource(id = subTitle), style = MaterialTheme.typography.bodyMedium ) } } } @Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true) @Composable fun SettingItemPreviewLight() { CountriesPadTheme { Column { SettingsItem( title = R.string.theme, subTitle = R.string.light, icon = R.drawable.palette, onClickSetting = {} ) SettingsItem( title = R.string.share_application, subTitle = R.string.invite_friends, icon = R.drawable.share, onClickSetting = {} ) SettingsItem( title = R.string.report_issue, subTitle = R.string.help_us, icon = R.drawable.bug, onClickSetting = {} ) SettingsItem( title = R.string.rate_us, subTitle = R.string.give_feedback, icon = R.drawable.rate_us, onClickSetting = {} ) SettingsItem( title = R.string.version, subTitle = R.string.app_version, icon = R.drawable.version, onClickSetting = {} ) } } } @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true) @Composable fun SettingItemPreviewDark() { CountriesPadTheme(true) { Column { SettingsItem( title = R.string.theme, subTitle = R.string.light, icon = R.drawable.palette, onClickSetting = {} ) SettingsItem( title = R.string.share_application, subTitle = R.string.invite_friends, icon = R.drawable.share, onClickSetting = {} ) SettingsItem( title = R.string.report_issue, subTitle = R.string.help_us, icon = R.drawable.bug, onClickSetting = {} ) SettingsItem( title = R.string.rate_us, subTitle = R.string.give_feedback, icon = R.drawable.rate_us, onClickSetting = {} ) SettingsItem( title = R.string.version, subTitle = R.string.app_version, icon = R.drawable.version, onClickSetting = {} ) } } }
0
Kotlin
0
5
27774f362615bf23c9b6dfd133ec39d0d7e7b24b
4,592
CountriesPad
The Unlicense
src/main/java/com/tianyisoft/database/relations/HasOne.kt
tianyirenjian
512,697,155
false
null
package com.tianyisoft.database.relations open class HasOne( override val table: String, override val foreignKey: String, override val localKey: String = "id" ) : HasMany(table, foreignKey, localKey) { override var recursive = false override fun clone(): Any { val hasOne = HasOne(table, foreignKey, localKey) hasOne.recursive = recursive copyAttributes(hasOne) return hasOne } override fun copy(): HasOne { return clone() as HasOne } }
0
null
0
1
1d4685c8483ebbfa1ce1032944b04e113b465a3b
511
querybuilder
Apache License 2.0
idea/tests/org/jetbrains/kotlin/idea/highlighter/AbstractHighlightExitPointsTest.kt
staltz
93,485,627
true
{"Markdown": 33, "XML": 685, "Ant Build System": 37, "Proguard": 1, "Ignore List": 8, "Maven POM": 49, "Kotlin": 18030, "Java": 4375, "CSS": 3, "Shell": 9, "Batchfile": 8, "Java Properties": 10, "Gradle": 68, "HTML": 131, "INI": 7, "Groovy": 20, "JavaScript": 61, "Text": 3936, "ANTLR": 1, "Protocol Buffer": 4, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "JFlex": 2}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.highlighter import com.intellij.codeInsight.highlighting.HighlightUsagesHandler import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import org.jetbrains.kotlin.test.InTextDirectivesUtils import kotlin.test.assertEquals public abstract class AbstractHighlightExitPointsTest : LightCodeInsightFixtureTestCase() { public fun doTest(testDataPath: String) { myFixture.configureByFile(testDataPath) HighlightUsagesHandler.invoke(myFixture.getProject(), myFixture.getEditor(), myFixture.getFile()); val text = myFixture.getFile().getText() val expectedToBeHighlighted = InTextDirectivesUtils.findLinesWithPrefixesRemoved(text, "//HIGHLIGHTED:") val searchResultsTextAttributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES) val highlighters = myFixture.getEditor().getMarkupModel().getAllHighlighters() .filter { it.getTextAttributes() == searchResultsTextAttributes } val actual = highlighters.map { text.substring(it.getStartOffset(), it.getEndOffset()) } assertEquals(expectedToBeHighlighted, actual) } }
0
Java
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
1,927
kotlin
Apache License 2.0
Fragmentos/app/src/main/java/com/example/fragmentos/MainActivity.kt
AlessandroStamatto
336,594,532
false
null
package com.example.fragmentos import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.add import androidx.fragment.app.commit import com.example.fragmentos.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) } }
0
Kotlin
0
1
4a86aa0d15eea66634c19c54b4a69032cf22605a
558
KotlinDev
MIT License
app/src/main/java/com/zhao/wanandroid/bean/NavigationBean.kt
zhaojfGithub
395,265,301
false
null
package com.zhao.wanandroid.bean /** *创建时间: 2021/12/30 *编 写: zjf *页面功能: */ class NavigationBoxBean( val articles: List<NavigationItemBean>, val cid: Int, val name: String, var isSelect: Boolean = false ) data class NavigationItemBean( val apkLink: String, val audit: Int, val author: String, val canEdit: Boolean, val chapterId: Int, val chapterName: String, val collect: Boolean, val courseId: Int, val desc: String, val descMd: String, val envelopePic: String, val fresh: Boolean, val host: String, val id: Int, val link: String, val niceDate: String, val niceShareDate: String, val origin: String, val prefix: String, val projectLink: String, val publishTime: Long, val realSuperChapterId: Int, val selfVisible: Int, val shareDate: Any, val shareUser: String, val superChapterId: Int, val superChapterName: String, val tags: List<Any>, val title: String, val type: Int, val userId: Int, val visible: Int, val zan: Int )
0
Kotlin
0
0
d5aeeaa0f00c2cc5166707c0f506bb7afa92e06a
1,079
wanandroid
Apache License 2.0
app/src/main/java/com/example/rocketjournal/view/SignUpForm.kt
JennaRV
746,806,258
false
{"Kotlin": 272122}
package com.example.rocketjournal.view import android.content.Context import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.absolutePadding import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.PointerIcon.Companion.Text import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.semantics.SemanticsProperties.Text import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType.Companion.Text import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.example.rocketjournal.model.dataModel.UserState import com.example.rocketjournal.viewmodel.SignUpViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun SignUpForm(navController: NavController, signUpViewModel: SignUpViewModel, context: Context) { val firstName by signUpViewModel.firstName.collectAsState() val lastName by signUpViewModel.lastName.collectAsState() val username by signUpViewModel.username.collectAsState() var confirmPassword by remember { mutableStateOf("") } Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { // Define your Column here and include TextFields and Button Column( modifier = Modifier .fillMaxSize() .fillMaxWidth() .padding(horizontal = 40.dp) .absolutePadding(top = 200.dp) .padding(top = 100.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { var email = signUpViewModel.email.collectAsState(initial = "") val password = signUpViewModel.password.collectAsState() OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = firstName, onValueChange = { signUpViewModel.firstName.value = it }, label = { Text("<NAME>") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), colors = TextFieldDefaults.outlinedTextFieldColors( focusedTextColor = Color.White, unfocusedTextColor = Color.White, focusedLabelColor = Color.White, // Label color when focused unfocusedLabelColor = Color.White, // Label color when not focused focusedBorderColor = Color.White, // Border color when focused unfocusedBorderColor = Color.White, // Border color when not focused ), shape = RoundedCornerShape(60.dp) ) Spacer(modifier = Modifier.height(1.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = lastName, onValueChange = { signUpViewModel.lastName.value = it }, label = { Text("<NAME>") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), colors = TextFieldDefaults.outlinedTextFieldColors( focusedTextColor = Color.White, unfocusedTextColor = Color.White, focusedLabelColor = Color.White, // Label color when focused unfocusedLabelColor = Color.White, // Label color when not focused focusedBorderColor = Color.White, // Border color when focused unfocusedBorderColor = Color.White, // Border color when not focused ), shape = RoundedCornerShape(60.dp) ) Spacer(modifier = Modifier.height(1.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = username, onValueChange = { signUpViewModel.username.value = it }, label = { Text("Username") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), colors = TextFieldDefaults.outlinedTextFieldColors( focusedTextColor = Color.White, unfocusedTextColor = Color.White, focusedLabelColor = Color.White, // Label color when focused unfocusedLabelColor = Color.White, // Label color when not focused focusedBorderColor = Color.White, // Border color when focused unfocusedBorderColor = Color.White, // Border color when not focused ), shape = RoundedCornerShape(60.dp) ) Spacer(modifier = Modifier.height(1.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = email.value, onValueChange = { signUpViewModel.onEmailChange(it) }, label = { Text("Email") }, colors = TextFieldDefaults.outlinedTextFieldColors( focusedTextColor = Color.White, unfocusedTextColor = Color.White, focusedLabelColor = Color.White, // Label color when focused unfocusedLabelColor = Color.White, // Label color when not focused focusedBorderColor = Color.White, // Border color when focused unfocusedBorderColor = Color.White, // Border color when not focused ), shape = RoundedCornerShape(60.dp) ) Spacer(modifier = Modifier.height(1.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = password.value, onValueChange = { signUpViewModel.onPasswordChange(it) }, label = { Text("Password") }, visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), colors = TextFieldDefaults.outlinedTextFieldColors( focusedTextColor = Color.White, unfocusedTextColor = Color.White, focusedLabelColor = Color.White, // Label color when focused unfocusedLabelColor = Color.White, // Label color when not focused focusedBorderColor = Color.White, // Border color when focused unfocusedBorderColor = Color.White, // Border color when not focused ), shape = RoundedCornerShape(60.dp) ) Spacer(modifier = Modifier.height(1.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = confirmPassword, onValueChange = { confirmPassword = it }, label = { Text("Confirm Password") }, visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), colors = TextFieldDefaults.outlinedTextFieldColors( focusedTextColor = Color.White, unfocusedTextColor = Color.White, focusedLabelColor = Color.White, // Label color when focused unfocusedLabelColor = Color.White, // Label color when not focused focusedBorderColor = Color.White, // Border color when focused unfocusedBorderColor = Color.White, // Border color when not focused ), shape = RoundedCornerShape(60.dp) ) Spacer(modifier = Modifier.height(1.dp)) Button( onClick = { // Check if passwords match if (confirmPassword.equals(password.value)) { // Call the ViewModel's onSignUp method signUpViewModel.onSignUp(navController, context) // Navigate to the next page upon successful sign up // } else { // Show error message indicating passwords do not match Toast.makeText(context, "Passwords did not match", Toast.LENGTH_SHORT).show() } }, modifier = Modifier .fillMaxWidth() .height(50.dp), shape = RoundedCornerShape(60.dp), colors = ButtonDefaults.buttonColors( containerColor = Color(0xFFFCE4B3) ) ) { Text( "Sign Up", fontSize = 24.sp, fontWeight = FontWeight.W800, color = Color(red = 100, green = 110, blue = 245) ) } } } }
0
Kotlin
0
0
55614c3a827d116f2a98a37f74ef534c0b332d3b
10,273
RocketJournal
MIT License
src/test/kotlin/no/nav/dagpenger/datadeling/testutil/ConfigLoader.kt
navikt
639,375,864
false
{"Kotlin": 63948, "Dockerfile": 106}
package no.nav.dagpenger.datadeling.testutil import com.sksamuel.hoplite.ConfigLoader import com.sksamuel.hoplite.sources.MapPropertySource import io.ktor.server.config.* import no.nav.dagpenger.datadeling.AppConfig fun loadConfig(config: ApplicationConfig): AppConfig { return ConfigLoader.builder() .addPropertySource(MapPropertySource(config.toMap())) .build() .loadConfigOrThrow() }
1
Kotlin
0
1
ed17f681e901b530f99d2c172136397c8ce85521
416
dp-datadeling
MIT License
mobile/app/src/main/java/org/una/mobile/viewmodel/PurchaseViewModel.kt
datwaft
347,226,418
false
null
package org.una.mobile.viewmodel import androidx.compose.material.ScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.res.stringResource import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.una.mobile.R import org.una.mobile.client.PurchaseWebSocketClient import org.una.mobile.client.PurchaseWebSocketClient.Event.Input import org.una.mobile.client.PurchaseWebSocketClient.Event.Output import org.una.mobile.model.Purchase import org.una.mobile.ui.layout.SnackbarState import org.una.mobile.viewmodel.PurchaseViewModel.Event.Create import org.una.mobile.viewmodel.PurchaseViewModel.Event.Error class PurchaseViewModel : ViewModel() { private val client = PurchaseWebSocketClient private val _items = MutableLiveData<List<Purchase>>(emptyList()) val items: LiveData<List<Purchase>> = _items var token: String? = null fun viewAll(token: String) { viewModelScope.launch { client.outputEventChannel.send(Output.ViewAll(token)) } } fun viewAll() { token ?: return viewModelScope.launch { client.outputEventChannel.send(Output.ViewAll(token!!)) } } fun create(ticketNumber: Int, flight: Long) { token ?: return viewModelScope.launch { client.outputEventChannel.send(Output.Create(token!!, ticketNumber, flight)) } } init { viewModelScope.launch { client.inputEventChannel.consumeEach { when (it) { is Input.ViewAll -> _items.postValue(it.payload) is Input.Create -> { eventChannel.send(Create) FlightViewModel.internalChannel.send(FlightViewModel.InternalEvent.ViewAll) } else -> Unit } } } } init { viewModelScope.launch { internalChannel.consumeEach { when (it) { is InternalEvent.ViewAll -> viewAll() } } } } sealed class Event { data class Error(val message: String) : Event() object Create : Event() } sealed class InternalEvent { object ViewAll : InternalEvent() } companion object { val eventChannel: Channel<Event> = Channel(10) val internalChannel: Channel<InternalEvent> = Channel(10) } } @Composable fun PurchaseListener( scaffoldState: ScaffoldState, ) { val createdMessage = stringResource(R.string.event_purchase_create_message) LaunchedEffect(scaffoldState.snackbarHostState) { PurchaseViewModel.eventChannel.consumeEach { when (it) { is Error -> scaffoldState.snackbarHostState.showSnackbar( Json.encodeToString(SnackbarState(SnackbarState.Type.ERROR, it.message)) ) Create -> scaffoldState.snackbarHostState.showSnackbar( Json.encodeToString(SnackbarState(SnackbarState.Type.INFORMATION, createdMessage)) ) } } } }
1
null
1
1
492f64411367783b063843cdad4ae367b3c166e1
3,532
UNA-Mobiles-Repository
MIT License
android/app/src/main/java/com/stasbar/app/android/MainApplication.kt
stanbar
162,640,520
false
{"Shell": 5, "Gradle": 10, "YAML": 2, "Ignore List": 9, "Procfile": 1, "Java Properties": 2, "Text": 3, "Batchfile": 1, "Kotlin": 67, "EditorConfig": 2, "JSON": 19, "Markdown": 1, "JSON with Comments": 4, "JavaScript": 22, "Dockerfile": 2, "SVG": 16, "CSS": 3, "TSX": 14, "XML": 60, "HTML": 5, "INI": 2, "Proguard": 1, "Java": 14, "Python": 1}
package com.stasbar.app.android import com.google.android.play.core.splitcompat.SplitCompatApplication import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import com.stasbar.app.android.books.BooksViewModel import com.stasbar.app.android.features.BackendApi import com.stasbar.app.android.features.BackendService import com.stasbar.app.android.features.books.BooksAdapter import com.stasbar.app.android.features.books.GetAllBooks import com.stasbar.app.android.features.books.GetFeaturedBooks import com.stasbar.app.android.features.quotes.GetAllQuotes import com.stasbar.app.android.features.quotes.GetFeaturedQuotes import com.stasbar.app.android.features.quotes.QuotesAdapter import com.stasbar.app.android.quotes.QuotesViewModel import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidFileProperties import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import timber.log.Timber @Suppress("unused") //Manifest class MainApplication : SplitCompatApplication() { override fun onCreate() { super.onCreate() // Print logs only in debug mode if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } startKoin { androidContext(this@MainApplication) androidFileProperties() modules(mainModule) } } } val mainModule = module { single<OkHttpClient> { OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)) .build() } single<BackendApi> { Retrofit.Builder() .baseUrl(getProperty("stasbar_base_url", "https://backend.stasbar.com/")) .client(get<OkHttpClient>()) .addConverterFactory(MoshiConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() .create(BackendApi::class.java) } single { BackendService(get()) } single { GetFeaturedBooks(get()) } single { GetFeaturedQuotes(get()) } factory { QuotesAdapter() } factory { BooksAdapter() } single { GetAllBooks(get()) } single { GetAllQuotes(get()) } single { } viewModel { BooksViewModel(get(), get()) } viewModel { QuotesViewModel(get(), get()) } }
8
null
1
1
3869ac8147d854b9fde6442398d89cfc51f5b401
2,408
stasbar-app
Apache License 2.0
core/src/main/java/com/alamkanak/weekview/Navigator.kt
david-qualias
351,357,972
true
{"Kotlin": 269788}
package com.alamkanak.weekview import android.os.Build import android.os.Handler import android.os.Looper import java.util.Calendar internal class Navigator( private val viewState: ViewState, private val listener: NavigationListener ) { private val animator = ValueAnimator() val isNotRunning: Boolean get() = !animator.isRunning fun scrollHorizontallyBy(distance: Float) { viewState.currentOrigin.x -= distance viewState.currentOrigin.x = viewState.currentOrigin.x.coerceIn( minimumValue = viewState.minX, maximumValue = viewState.maxX ) listener.onHorizontalScrollPositionChanged() } fun scrollVerticallyBy(distance: Float) { viewState.currentOrigin.y -= distance listener.onVerticalScrollPositionChanged() } fun scrollHorizontallyTo(date: Calendar, onFinished: () -> Unit = {}) { val destinationOffset = viewState.getXOriginForDate(date) val adjustedDestinationOffset = destinationOffset.coerceIn( minimumValue = viewState.minX, maximumValue = viewState.maxX ) scrollHorizontallyTo(offset = adjustedDestinationOffset, onFinished = onFinished) } fun scrollHorizontallyTo(offset: Float, onFinished: () -> Unit = {}) { animator.animate( fromValue = viewState.currentOrigin.x, toValue = offset, onUpdate = { viewState.currentOrigin.x = it listener.onHorizontalScrollPositionChanged() }, onEnd = { if (Build.VERSION.SDK_INT > 25) { listener.onHorizontalScrollingFinished() onFinished() } else { // Delay calling the listener to avoid navigator.isNotRunning still // being false on API 25 and below. // See: https://github.com/thellmund/Android-Week-View/issues/227 Handler(Looper.getMainLooper()).post { listener.onHorizontalScrollingFinished() onFinished() } } } ) } fun scrollVerticallyTo(offset: Float) { val dayHeight = viewState.hourHeight * viewState.hoursPerDay val viewHeight = viewState.viewHeight val minY = (dayHeight + viewState.headerHeight - viewHeight) * -1 val maxY = 0f val finalOffset = offset.coerceIn( minimumValue = minY, maximumValue = maxY ) animator.animate( fromValue = viewState.currentOrigin.y, toValue = finalOffset, onUpdate = { viewState.currentOrigin.y = it listener.onVerticalScrollPositionChanged() } ) } fun stop() { animator.stop() } fun requestInvalidation() { listener.requestInvalidation() } internal interface NavigationListener { fun onHorizontalScrollPositionChanged() fun onHorizontalScrollingFinished() fun onVerticalScrollPositionChanged() fun requestInvalidation() } }
0
Kotlin
1
0
e2b3fe0cb984538768faeef6423bba85d6b96897
3,215
Android-Week-View
Apache License 2.0
app/src/main/java/com/novasa/sectioningadapterexample/data/ExampleDataSource.kt
Novasa
178,013,140
false
null
package com.novasa.sectioningadapterexample.data import io.reactivex.Observable import javax.inject.Inject import kotlin.random.Random class ExampleDataSource @Inject constructor() : DataSource { companion object { private const val ITEM_COUNT = 20 private const val SECTION_COUNT = 5 } private val rng = Random(0) override fun data(): Observable<Data> = Observable.just(Data(ArrayList<Item>().also { for (i in 1..ITEM_COUNT) { it.add(Item(i, rng.nextInt(SECTION_COUNT) + 1)) } })) }
1
null
1
1
fa7f4f6d0f8ee24e944c2c41389785a0c7d967bb
552
SectioningAdapter
Apache License 2.0
compose-ide-plugin/src/main/java/androidx/compose/plugins/idea/ComposePluginUtils.kt
JetBrains
60,701,247
false
null
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.plugins.idea import com.intellij.openapi.module.ModuleUtilCore import com.intellij.psi.PsiElement fun isComposeEnabled(element: PsiElement): Boolean { val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return false val kotlinFacet = org.jetbrains.kotlin.idea.facet.KotlinFacet.get(module) ?: return false val commonArgs = kotlinFacet.configuration.settings.mergedCompilerArguments ?: return false val modeOption = commonArgs.pluginOptions?.firstOrNull { it.startsWith("plugin:androidx.compose.plugins.idea:enabled=") } ?: return false val value = modeOption.substring(modeOption.indexOf("=") + 1) return value == "true" }
0
null
187
751
16d17317f2c44ec46e8cd2180faf9c349d381a06
1,315
android
Apache License 2.0
programming/kotlin/cli/TestLoad.kt
morten-andersen
256,015,591
false
{"Java": 4453, "R": 3218, "SCSS": 1587, "Kotlin": 913, "Elixir": 206}
// main function to return the length of array // call as `main(arrayOf("elem1", "elem2"))` // https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/array-of.html fun main(args: Array<String>) = args.size
0
Java
0
3
8f22515513d2c92ada5bbc3eee1afe64b14c64e5
203
tech-notes
Creative Commons Attribution 4.0 International
XBar/src/main/java/site/xzwzz/xbar/statusbar/StatusBarUtil.kt
MyMrXu
285,248,346
false
null
package site.xzwzz.xbar.statusbar import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.content.res.Resources import android.graphics.Color import android.os.Build import android.util.Log import android.util.TypedValue import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager import androidx.annotation.FloatRange import androidx.annotation.RequiresApi import site.xzwzz.xbar.SizeUtils import java.util.regex.Pattern /** * 状态栏透明 */ class StatusBarUtil { companion object { private var DEFAULT_COLOR = Color.WHITE private var DEFAULT_ALPHA = 0f//if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 0.2f else 0.3f; private val MIN_API = 19 /** 判断是否Flyme4以上 */ private val isFlyme4Later: Boolean get() = (Build.FINGERPRINT.contains("Flyme_OS_4") || Build.VERSION.INCREMENTAL.contains("Flyme_OS_4") || Pattern.compile("Flyme OS [4|5]", Pattern.CASE_INSENSITIVE) .matcher(Build.DISPLAY).find()) /** 判断是否为MIUI6以上 */ private val isMIUI6Later: Boolean get() { return try { val clz = Class.forName("android.os.SystemProperties") val mtd = clz.getMethod("get", String::class.java) var `val` = mtd.invoke(null, "ro.miui.ui.version.name") as String `val` = `val`.replace("[vV]".toRegex(), "") val version = Integer.parseInt(`val`) version >= 6 } catch (e: Exception) { false } } @JvmOverloads fun immersive( activity: Activity, color: Int = DEFAULT_COLOR, @FloatRange(from = 0.0, to = 1.0) alpha: Float = DEFAULT_ALPHA ) { immersive(activity.window, color, alpha) } fun immersive(window: Window) { immersive(window, DEFAULT_COLOR, DEFAULT_ALPHA) } @JvmOverloads fun immersive( window: Window, color: Int, @FloatRange(from = 0.0, to = 1.0) alpha: Float = 1f ) { if (Build.VERSION.SDK_INT >= 21) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = mixtureColor(color, alpha) var systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.decorView.systemUiVisibility = systemUiVisibility } else if (Build.VERSION.SDK_INT >= 19) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) setTranslucentView(window.decorView as ViewGroup, color, alpha) } else if (Build.VERSION.SDK_INT >= MIN_API && Build.VERSION.SDK_INT > 19) { var systemUiVisibility = window.decorView.systemUiVisibility systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.decorView.systemUiVisibility = systemUiVisibility } } //-------------------------> /** * 设置字体颜色 */ @TargetApi(Build.VERSION_CODES.M) fun darkMode(activity: Activity?, dark: Boolean) { darkMode(activity, DEFAULT_COLOR, DEFAULT_ALPHA, dark) } /** 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */ fun darkMode(activity: Activity?) { darkMode(activity, DEFAULT_COLOR, DEFAULT_ALPHA) } fun darkMode( activity: Activity?, color: Int, @FloatRange(from = 0.0, to = 1.0) alpha: Float, dark: Boolean = true ) { if (activity == null) { return } darkMode(activity.window, color, alpha, dark) } /** 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */ @TargetApi(Build.VERSION_CODES.M) fun darkMode( window: Window, color: Int, @FloatRange(from = 0.0, to = 1.0) alpha: Float, dark: Boolean = true ) { when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> { darkModeForM(window, dark) // immersive(window, color, alpha) } isFlyme4Later -> { darkModeForFlyme4(window, dark) // immersive(window, color, alpha) } isMIUI6Later -> { darkModeForMIUI6(window, dark) // immersive(window, color, alpha) } OSUtils.isOppo() -> { darkModeForOppo(window, dark) } Build.VERSION.SDK_INT >= 19 -> { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) setTranslucentView(window.decorView as ViewGroup, color, alpha) } else -> immersive(window, color, alpha) } } //-------------------------> /** android 6.0设置字体颜色 */ @RequiresApi(Build.VERSION_CODES.M) private fun darkModeForM(window: Window, dark: Boolean) { var systemUiVisibility = window.decorView.systemUiVisibility systemUiVisibility = if (dark) { systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } window.decorView.systemUiVisibility = systemUiVisibility } /** * 设置Flyme4+的darkMode,darkMode时候字体颜色及icon变黑 * http://open-wiki.flyme.cn/index.php?title=Flyme%E7%B3%BB%E7%BB%9FAPI */ private fun darkModeForFlyme4(window: Window?, dark: Boolean): Boolean { var result = false if (window != null) { try { val e = window.attributes val darkFlag = WindowManager.LayoutParams::class.java.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON") val meizuFlags = WindowManager.LayoutParams::class.java.getDeclaredField("meizuFlags") darkFlag.isAccessible = true meizuFlags.isAccessible = true val bit = darkFlag.getInt(null) var value = meizuFlags.getInt(e) if (dark) { value = value or bit } else { value = value and bit.inv() } meizuFlags.setInt(e, value) window.attributes = e result = true } catch (var8: Exception) { Log.e("StatusBar", "darkIcon: failed") } } return result } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) /** * 设置MIUI6+的状态栏是否为darkMode,darkMode时候字体颜色及icon变黑 * http://dev.xiaomi.com/doc/p=4769/ */ private fun darkModeForMIUI6(window: Window, darkmode: Boolean): Boolean { val clazz = window.javaClass return try { val darkModeFlag: Int val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams") val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE") darkModeFlag = field.getInt(layoutParams) val extraFlagField = clazz.getMethod("setExtraFlags", Int::class.java, Int::class.java) extraFlagField.invoke(window, if (darkmode) darkModeFlag else 0, darkModeFlag) if (darkmode) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { val flag = window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR window.decorView.systemUiVisibility = flag } true } catch (e: Exception) { e.printStackTrace() false } return true } private const val SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT = 0x00000010 private fun darkModeForOppo(window: Window, darkMode: Boolean) { var vis = window.decorView.systemUiVisibility if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { vis = if (darkMode) { vis or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { vis and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { vis = if (darkMode) { vis or SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT } else { vis and SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT.inv() } } window.decorView.systemUiVisibility = vis } /** 增加View的paddingTop,增加的值为状态栏高度 (智能判断,并设置高度) */ fun setPaddingSmart(context: Context, view: View) { if (Build.VERSION.SDK_INT >= MIN_API) { val lp = view.layoutParams if (lp != null) { if (lp.height < 0) { lp.height = getActionBarHeight(context); } lp.height += getStatusBarHeight(context)//增高 if (view.paddingTop < getStatusBarHeight(context)) { view.setPadding( view.paddingLeft, view.paddingTop + getStatusBarHeight(context), view.paddingRight, view.paddingBottom ) } view.layoutParams = lp } } } /** 增加View上边距(MarginTop)一般是给高度为 WARP_CONTENT 的小控件用的 */ fun setMargin(context: Context, view: View) { if (Build.VERSION.SDK_INT >= MIN_API) { val lp = view.layoutParams if (lp is ViewGroup.MarginLayoutParams) { lp.topMargin += getStatusBarHeight(context)//增高 } view.layoutParams = lp } } /** * 创建假的透明栏 */ fun setTranslucentView( container: ViewGroup, color: Int, @FloatRange(from = 0.0, to = 1.0) alpha: Float ) { if (Build.VERSION.SDK_INT >= 19) { val mixtureColor = mixtureColor(color, alpha) var translucentView: View? = container.findViewById(android.R.id.custom) if (translucentView == null && mixtureColor != 0) { translucentView = View(container.context) translucentView.id = android.R.id.custom val lp = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.context) ) container.addView(translucentView, lp) } if (translucentView != null) { translucentView.setBackgroundColor(mixtureColor) } } } /** * 检测是否有虚拟导航栏 * * @param context * @return */ fun checkDeviceHasNavigationBar(context: Context): Boolean { var hasNavigationBar = false val rs = context.resources val id = rs.getIdentifier("config_showNavigationBar", "bool", "android") if (id > 0) { hasNavigationBar = rs.getBoolean(id) } try { val systemPropertiesClass = Class.forName("android.os.SystemProperties") val m = systemPropertiesClass.getMethod("get", String::class.java) val navBarOverride = m.invoke(systemPropertiesClass, "qemu.hw.mainkeys") as String if ("1" == navBarOverride) { hasNavigationBar = false } else if ("0" == navBarOverride) { hasNavigationBar = true } } catch (e: java.lang.Exception) { e.printStackTrace() } return hasNavigationBar } fun mixtureColor(color: Int, @FloatRange(from = 0.0, to = 1.0) alpha: Float): Int { val a = if (color and -0x1000000 == 0) 0xff else color.ushr(24) return color and 0x00ffffff or ((a * alpha).toInt() shl 24) } /** 获取状态栏高度 */ fun getStatusBarHeight(context: Context): Int { var result = 24 val resId = context.resources.getIdentifier("status_bar_height", "dimen", "android") result = if (resId > 0) { context.resources.getDimensionPixelSize(resId) } else { TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, result.toFloat(), Resources.getSystem().displayMetrics ).toInt() } return result } fun getActionBarHeight(context: Context): Int { return SizeUtils.dp2px(56f) // val tv = TypedValue() // return if (context.theme.resolveAttribute(R.attr.actionBarSize, tv, true)) { // TypedValue.complexToDimensionPixelSize(tv.data, // context.resources.displayMetrics) // } else 0 } } }
1
null
1
1
c69204968edcafe8fdcae4c48d2c9482ef018e71
14,395
XToolbar
MIT License
app/src/main/java/com/seven/simpleandroid/utils/QRCodeUtil.kt
wen-carl
135,954,275
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 91, "Kotlin": 52, "Java": 4}
package com.seven.simpleandroid.utils import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.text.TextUtils import androidx.annotation.ColorInt import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.MultiFormatWriter import com.google.zxing.WriterException import com.google.zxing.qrcode.QRCodeWriter /** * https://www.jianshu.com/p/c75f16de1b2c */ class QRCodeUtil { companion object { /* fun createQRCode(str: String) : Bitmap? { return createQRCode(str, 200) } fun createQRCode(str: String, size : Int): Bitmap? { val multiFormatWriter = MultiFormatWriter() var bitmap : Bitmap? = null try { val matrix = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, size, size) val mWidth = matrix.width val mHeight = matrix.height val pixels = IntArray(mWidth * mHeight) for (y in 0 until mHeight) { val offset = y * mWidth for (x in 0 until mWidth) { pixels[offset + x] = if (matrix.get(x, y)) -0x1000000 else -0x1 //黑色和白色 } } bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888) bitmap.setPixels(pixels, 0, mWidth, 0, 0, mWidth, mHeight) } catch (e: WriterException) { e.printStackTrace() } return bitmap } */ /** * 创建二维码位图 * * @param content 字符串内容 * @param size 位图宽&高(单位:px) * @return */ fun createQRCodeBitmap(content: String?, size : Int) : Bitmap? { return createQRCodeBitmap(content, size, "UTF-8", "H", "4", Color.BLACK, Color.WHITE, null, null, 0F); } /** * 创建二维码位图 (自定义黑、白色块颜色) * * @param content 字符串内容 * @param size 位图宽&高(单位:px) * @param color_black 黑色色块的自定义颜色值 * @param color_white 白色色块的自定义颜色值 * @return */ fun createQRCodeBitmap(content : String?, size : Int, @ColorInt color_black : Int, @ColorInt color_white : Int) : Bitmap? { return createQRCodeBitmap(content, size, "UTF-8", "H", "4", color_black, color_white, null, null, 0F); } /** * 创建二维码位图 (带Logo小图片) * * @param content 字符串内容 * @param size 位图宽&高(单位:px) * @param logoBitmap logo图片 * @param logoPercent logo小图片在二维码图片中的占比大小,范围[0F,1F]。超出范围->默认使用0.2F * @return */ fun createQRCodeBitmap(content : String, size : Int, logoBitmap : Bitmap?, logoPercent : Float) : Bitmap? { return createQRCodeBitmap(content, size, "UTF-8", "H", "4", Color.BLACK, Color.WHITE, null, logoBitmap, logoPercent); } /** * 创建二维码位图 (Bitmap颜色代替黑色) 注意!!!注意!!!注意!!! 选用的Bitmap图片一定不能有白色色块,否则会识别不出来!!! * * @param content 字符串内容 * @param size 位图宽&高(单位:px) * @param targetBitmap 目标图片 (如果targetBitmap != null, 黑色色块将会被该图片像素色值替代) * @return */ fun createQRCodeBitmap(content : String, size : Int, targetBitmap : Bitmap ) : Bitmap? { return createQRCodeBitmap(content, size, "UTF-8", "H", "4", Color.BLACK, Color.WHITE, targetBitmap, null, 0F); } /** * 创建二维码位图 (支持自定义配置和自定义样式) * * @param content 字符串内容 * @param size 位图宽&高(单位:px) * @param character_set 字符集/字符转码格式 (支持格式:{@link CharacterSetECI })。传null时,zxing源码默认使用 "ISO-8859-1" * @param error_correction 容错级别 (支持级别:{@link ErrorCorrectionLevel })。传null时,zxing源码默认使用 "L" * @param margin 空白边距 (可修改,要求:整型且>=0), 传null时,zxing源码默认使用"4"。 * @param color_black 黑色色块的自定义颜色值 * @param color_white 白色色块的自定义颜色值 * @param targetBitmap 目标图片 (如果targetBitmap != null, 黑色色块将会被该图片像素色值替代) * @param logoBitmap logo小图片 * @param logoPercent logo小图片在二维码图片中的占比大小,范围[0F,1F],超出范围->默认使用0.2F。 * @return */ fun createQRCodeBitmap(content : String?, size : Int, character_set : String?, error_correction : String?, margin : String?, @ColorInt color_black : Int, @ColorInt color_white : Int, targetBitmap : Bitmap?, logoBitmap : Bitmap?, logoPercent : Float) : Bitmap? { /** 1.参数合法性判断 */ if(TextUtils.isEmpty(content)){ // 字符串内容判空 return null } if(size <= 0){ // 宽&高都需要>0 return null } try { /** 2.设置二维码相关配置,生成BitMatrix(位矩阵)对象 */ //Hashtable<EncodeHintType, String> hints = new Hashtable<>(); val hints = hashMapOf<EncodeHintType, String>() if(!character_set.isNullOrEmpty()) { // 字符转码格式设置 hints[EncodeHintType.CHARACTER_SET] = character_set!! } if(!error_correction.isNullOrEmpty()){ // 容错级别设置 hints[EncodeHintType.ERROR_CORRECTION] = error_correction!! } if(!margin.isNullOrEmpty()){ // 空白边距设置 hints[EncodeHintType.MARGIN] = margin!! } val bitMatrix = QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, size, size, hints); /** 3.根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */ var mTargetBitmap = targetBitmap if(mTargetBitmap != null){ mTargetBitmap = Bitmap.createScaledBitmap(mTargetBitmap, size, size, false) } val pixels = IntArray(size * size) for(y in 0 until size){ for(x in 0 until size){ if(bitMatrix.get(x, y)){ // 黑色色块像素设置 if(targetBitmap != null) { pixels[y * size + x] = mTargetBitmap!!.getPixel(x, y) } else { pixels[y * size + x] = color_black } } else { // 白色色块像素设置 pixels[y * size + x] = color_white } } } /** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,之后返回Bitmap对象 */ val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, size, 0, 0, size, size); /** 5.为二维码添加logo小图标 */ if(logoBitmap != null){ return addLogo(bitmap, logoBitmap, logoPercent); } return bitmap } catch (e : WriterException) { e.printStackTrace() } return null } /** * 向一张图片中间添加logo小图片(图片合成) * * @param srcBitmap 原图片 * @param logoBitmap logo图片 * @param logoPercent 百分比 (用于调整logo图片在原图片中的显示大小, 取值范围[0,1], 传值不合法时使用0.2F)原图片是二维码时,建议使用0.2F,百分比过大可能导致二维码扫描失败。 * @return */ fun addLogo(srcBitmap : Bitmap, logoBitmap : Bitmap?, logoPercent : Float = 0.2f) : Bitmap? { if(logoBitmap == null){ return srcBitmap } var mPercent = logoPercent if(mPercent < 0F || mPercent > 1F) { mPercent = 0.2F } /** 2. 获取原图片和Logo图片各自的宽、高值 */ val srcWidth = srcBitmap.width val srcHeight = srcBitmap.height val logoWidth = logoBitmap.width val logoHeight = logoBitmap.height /** 3. 计算画布缩放的宽高比 */ val scaleWidth = srcWidth * mPercent / logoWidth val scaleHeight = srcHeight * mPercent / logoHeight /** 4. 使用Canvas绘制,合成图片 */ val bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) canvas.drawBitmap(srcBitmap, 0f, 0f, null) canvas.scale(scaleWidth, scaleHeight, srcWidth/2f, srcHeight/2f) canvas.drawBitmap(logoBitmap, srcWidth/2f - logoWidth/2f, srcHeight/2f - logoHeight/2f, null) return bitmap } /** * 生成条形码 * @param contents 条形码内容 * @param desiredWidth 宽度 * @param desiredHeight 高度 * @return bitmap * @throws WriterException 异常 */ @Throws(WriterException::class) fun createBarcode(contents: String, desiredWidth: Int, desiredHeight: Int): Bitmap { val writer = MultiFormatWriter() val result = writer.encode(contents, BarcodeFormat.CODE_128, desiredWidth, desiredHeight) val width = result.width val height = result.height val pixels = IntArray(width * height) // All are 0, or black, by default for (y in 0 until height) { val offset = y * width for (x in 0 until width) { pixels[offset + x] = if (result.get(x, y)) Color.BLACK else Color.WHITE } } val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) bitmap.setPixels(pixels, 0, width, 0, 0, width, height) return bitmap } } }
0
Kotlin
0
0
f3b50861b8b809c2c1d3bf49c364c9ebf977ad68
9,484
SimpleAndroid
MIT License
app/src/main/java/pl/gmat/users/common/database/UsersDatabase.kt
gmatyszczak
244,174,218
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 54, "XML": 18, "Java": 1}
package pl.gmat.users.common.database import androidx.room.Database import androidx.room.RoomDatabase import pl.gmat.users.common.database.dao.AddressDao import pl.gmat.users.common.database.dao.UserDao import pl.gmat.users.common.database.entity.AddressEntity import pl.gmat.users.common.database.entity.UserEntity private const val DATABASE_VERSION = 1 @Database( entities = [ UserEntity::class, AddressEntity::class ], version = DATABASE_VERSION ) abstract class UsersDatabase : RoomDatabase() { abstract fun userDao(): UserDao abstract fun addressDao(): AddressDao }
1
null
1
1
b280b0b2796ead293d27a3cac1a4b2530bfcaba0
610
users-sample
Apache License 2.0
app/src/main/kotlin/com/example/app/domains/home/HomeController.kt
teambankrupt
169,073,286
false
{"Java": 36166, "Kotlin": 8540, "HTML": 1591}
package com.example.app.domains.home import com.example.auth.config.security.SecurityContext import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.GetMapping import springfox.documentation.annotations.ApiIgnore @Controller @ApiIgnore class HomeController { @GetMapping("") fun home(model: Model): String { val auth = SecurityContext.getCurrentUser() model.addAttribute("auth", auth) return "index" } }
1
Java
47
74
e39618a750bd10c43e634ac2b4799ed6fc5e40f7
519
open-project-bankrupt
Apache License 2.0
common/src/commonMain/kotlin/kotlinx/ast/common/AstParserType.kt
kotlinx
207,099,876
false
null
package kotlinx.ast.common interface AstParserType
27
Java
20
265
965f945a27a3f6460c7a090a067158c74f29cd7f
52
ast
Apache License 2.0
app/src/main/java/com/mindorks/framework/mvp/ui/login/interactor/LoginMVPInteractor.kt
janishar
115,260,052
false
null
package com.mindorks.framework.mvp.ui.login.interactor import com.mindorks.framework.mvp.data.network.LoginResponse import com.mindorks.framework.mvp.ui.base.interactor.MVPInteractor import com.mindorks.framework.mvp.util.AppConstants import io.reactivex.Observable /** * Created by jyotidubey on 10/01/18. */ interface LoginMVPInteractor : MVPInteractor { fun doServerLoginApiCall(email: String, password: String): Observable<LoginResponse> fun doFBLoginApiCall(): Observable<LoginResponse> fun doGoogleLoginApiCall(): Observable<LoginResponse> fun updateUserInSharedPref(loginResponse: LoginResponse, loggedInMode: AppConstants.LoggedInMode) }
17
null
199
702
5ac97334d417aff636dd587c82ad97c661c38666
670
android-kotlin-mvp-architecture
Apache License 2.0
app/src/main/java/com/multiaddress/transactions/ui/activities/TransactionsListActivity.kt
lomza
292,776,760
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 37, "XML": 22, "Java": 1}
package com.multiaddress.transactions.ui.activities import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import androidx.annotation.StringRes import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.multiaddress.transactions.R import com.multiaddress.transactions.data.Transactions import com.multiaddress.transactions.data.Wallet import com.multiaddress.transactions.ui.adapters.TransactionsListAdapter import com.multiaddress.transactions.ui.viewmodels.TransactionsViewModel import com.multiaddress.transactions.ui.viewmodels.TransactionsViewModel.UiEvent.ShowError import com.multiaddress.transactions.ui.viewmodels.TransactionsViewModel.UiEvent.ShowWalletAndTransactions import com.multiaddress.transactions.ui.viewmodels.TransactionsViewModel.UiEvent.ShowLoader import com.multiaddress.transactions.ui.viewmodels.TransactionsViewModelFactory import com.multiaddress.transactions.utils.satoshisToBtc import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.activity_transactions_list.* import javax.inject.Inject /** * This is the main and only activity, which contains a wallet and transactions information. */ @AndroidEntryPoint class TransactionsListActivity : AppCompatActivity() { private var listAdapter: TransactionsListAdapter? = null @Inject lateinit var viewModelFactory: TransactionsViewModelFactory private lateinit var viewModel: TransactionsViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_transactions_list) init() observeUiEvents() viewModel.fetchWalletAndTransactions() } private fun init() { viewModel = ViewModelProvider(this, viewModelFactory).get(TransactionsViewModel::class.java) vTransactionsList.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false) } private fun observeUiEvents() { viewModel.uiEvent.observe(this, Observer { it?.let { when (it) { is ShowWalletAndTransactions -> { vTransactionsProgress.visibility = View.GONE vTransactionsErrorText.visibility = View.GONE showWallet(it.wallet) showTransactionList(it.transactions) } is ShowLoader -> showLoader() is ShowError -> showError(it.messageId) } } }) } private fun hideContent() { vWalletBalanceCard.visibility = View.GONE vTransactionsHeader.visibility = View.GONE vTransactionsList.visibility = View.GONE } private fun showError(@StringRes messageId: Int) { hideContent() vTransactionsProgress.visibility = View.GONE vTransactionsErrorText.text = getString(messageId) vTransactionsErrorText.visibility = View.VISIBLE } private fun showLoader() { hideContent() vTransactionsErrorText.visibility = View.GONE vTransactionsProgress.visibility = View.VISIBLE } private fun showWallet(wallet: Wallet) { vWalletBalance.text = getString(R.string.btc_value, wallet.finalBalance.satoshisToBtc()) vWalletBalanceCard.visibility = View.VISIBLE } private fun showTransactionList(transactions: Transactions) { vTransactionsHeader.text = getString(R.string.transactions_header, transactions.size) vTransactionsHeader.visibility = View.VISIBLE vTransactionsList.visibility = View.VISIBLE listAdapter = TransactionsListAdapter(transactions) vTransactionsList.adapter = listAdapter } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_transactions_list, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_refresh -> { viewModel.fetchWalletAndTransactions() true } else -> super.onOptionsItemSelected(item) } } }
1
null
1
1
7eee907fbe42e37f6b27f50bb11a7a7f94cb79d3
4,413
my-blockchain-wallet
MIT License
core-mvp-binding/sample/src/main/java/ru/surfstudio/android/mvp/binding/rx/sample/checkbox/CheckboxActivityView.kt
surfstudio
139,034,657
false
null
/* * Copyright (c) 2019-present, SurfStudio LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.surfstudio.android.mvp.binding.rx.sample.checkbox import android.os.Bundle import android.os.PersistableBundle import android.widget.Toast import com.jakewharton.rxbinding2.view.clicks import com.jakewharton.rxbinding2.widget.checkedChanges import kotlinx.android.synthetic.main.activity_checkboxes.* import ru.surfstudio.android.core.mvp.binding.rx.ui.BaseRxActivityView import ru.surfstudio.android.core.mvp.binding.sample.R import javax.inject.Inject /** * Экран демострирующий возможность работы со связными данными напримере чекбоксов */ class CheckboxActivityView : BaseRxActivityView() { @Inject lateinit var bm: CheckboxBindModel override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?, viewRecreated: Boolean) { super.onCreate(savedInstanceState, persistentState, viewRecreated) bind() } fun bind() { bm.checkBond1 bindTo checkbox_1::setChecked checkbox_1.checkedChanges() bindTo bm.checkBond1 checkbox_2.checkedChanges() bindTo bm.checkAction2 checkbox_3.checkedChanges() bindTo bm.checkAction3 send_btn.clicks() bindTo bm.sendAction bm.count bindTo { counter_et.text = it.toString() } bm.messageCommand bindTo { Toast.makeText(this, it, Toast.LENGTH_SHORT).show() } } override fun createConfigurator() = CheckboxScreenConfigurator(intent) override fun getScreenName(): String = "CheckboxActivityView" override fun getContentView(): Int = R.layout.activity_checkboxes }
5
null
30
249
6d73ebcaac4b4bd7186e84964cac2396a55ce2cc
2,150
SurfAndroidStandard
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/hierarchical-mpp-multi-modules/top-mpp/src/jvm18Main/kotlin/transitiveStory/bottomActual/mppBeginning/sourceSetName.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
package transitiveStory.bottomActual.mppBeginning actual val sourceSetName: String = "jvmMain"
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
95
kotlin
Apache License 2.0
app/src/main/java/ar/com/wolox/android/example/ui/home/HomeFragment.kt
wolox-training
197,433,230
false
{"Gradle": 7, "Markdown": 2, "Java Properties": 2, "Shell": 4, "Ignore List": 2, "Batchfile": 1, "YAML": 2, "Ruby": 1, "Proguard": 1, "Kotlin": 40, "XML": 33, "Java": 15, "Python": 2}
package ar.com.wolox.android.example.ui.home import androidx.core.util.Pair import ar.com.wolox.android.R import ar.com.wolox.android.example.ui.home.news.NewsFragment import ar.com.wolox.android.example.ui.home.profile.ProfileFragment import ar.com.wolox.wolmo.core.adapter.viewpager.SimpleFragmentPagerAdapter import ar.com.wolox.wolmo.core.fragment.WolmoFragment import com.google.android.material.tabs.TabLayout import kotlinx.android.synthetic.main.fragment_home.* import javax.inject.Inject class HomeFragment : WolmoFragment<HomePresenter>(), HomeView { @Inject internal lateinit var pageNews: NewsFragment @Inject internal lateinit var pageProfile: ProfileFragment private lateinit var fragmentHomePagerAdapter: SimpleFragmentPagerAdapter override fun layout(): Int { return R.layout.fragment_home } override fun init() { vHomeTabLayout.setupWithViewPager(vHomeViewPager) fragmentHomePagerAdapter = SimpleFragmentPagerAdapter(childFragmentManager).apply { addFragments( Pair(pageNews, getString(R.string.home_news_fragment)), Pair(pageProfile, getString(R.string.hhome_profile_fragment)) ) } vHomeViewPager.apply { adapter = fragmentHomePagerAdapter addOnPageChangeListener( TabLayout.TabLayoutOnPageChangeListener(vHomeTabLayout) ) } onTabInit() } private fun onTabInit() { vHomeTabLayout.run { getTabAt(0)!!.setIcon(R.drawable.ic_news_selected) getTabAt(1)!!.setIcon(R.drawable.ic_profile_selected) } } }
3
Kotlin
0
0
1d84390501852063ae54964addf7a575912d591a
1,675
gl-android
MIT License