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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ui/src/main/java/com/pyamsoft/pydroid/ui/navigator/FragmentNavigator.kt | pyamsoft | 48,562,480 | false | null | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.pyamsoft.pydroid.ui.navigator
import android.os.Bundle
import androidx.annotation.CheckResult
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.LifecycleOwner
import com.pyamsoft.pydroid.core.Logger
import com.pyamsoft.pydroid.core.requireNotNull
import com.pyamsoft.pydroid.ui.util.commit
import com.pyamsoft.pydroid.ui.util.commitNow
/** A navigator backed by AndroidX Fragment transactions */
public abstract class FragmentNavigator<S : Any>
protected constructor(
lifecycleOwner: () -> LifecycleOwner,
fragmentManager: () -> FragmentManager,
@IdRes private val fragmentContainerId: Int,
) : BaseNavigator<S>(), BackstackNavigator<S> {
protected constructor(
activity: FragmentActivity,
@IdRes fragmentContainerId: Int,
) : this(
lifecycleOwner = { activity },
fragmentManager = { activity.supportFragmentManager },
fragmentContainerId = fragmentContainerId,
)
private val fragmentTagMap: Map<S, FragmentTag> by
lazy(LazyThreadSafetyMode.NONE) { provideFragmentTagMap() }
private val lifecycleOwner by lazy(LazyThreadSafetyMode.NONE) { lifecycleOwner() }
private val fragmentManager by lazy(LazyThreadSafetyMode.NONE) { fragmentManager() }
/** Provides a map of Screen types to FragmentTypes */
@CheckResult protected abstract fun provideFragmentTagMap(): Map<S, FragmentTag>
/** Performs a fragment transaction */
protected abstract fun performFragmentTransaction(
container: Int,
data: FragmentTag,
newScreen: Navigator.Screen<S>,
previousScreen: S?
)
@CheckResult
private fun getPossibleCurrentFragment(): Fragment? {
return fragmentManager.findFragmentById(fragmentContainerId)
}
final override fun restore(onLoadDefaultScreen: (Selector<S>) -> Unit) {
val existing = getPossibleCurrentFragment()
if (existing == null) {
Logger.d("No existing Fragment, load default screen")
onLoadDefaultScreen(this)
} else {
// Look up the previous screen in the map
val currentScreen =
fragmentTagMap.entries.find { it.value.tag == existing.tag }?.key.requireNotNull {
"Failed to restore current screen from fragment tag map."
}
Logger.d("Restore current screen from fragment tag map")
updateCurrentScreen(currentScreen)
}
}
final override fun handleBack() {
fragmentManager.popBackStack()
}
/** Go back immediately based on the FM back stack */
protected fun handleBackNow() {
fragmentManager.popBackStackImmediate()
}
final override fun backStackSize(): Int {
return fragmentManager.backStackEntryCount
}
final override fun select(screen: Navigator.Screen<S>, force: Boolean): Boolean {
val entry = fragmentTagMap[screen.screen].requireNotNull()
val previousScreen: S?
val pushNew: Boolean
val existing = getPossibleCurrentFragment()
if (existing == null) {
Logger.d("Pushing a brand new fragment")
pushNew = true
previousScreen = null
} else {
val tag = existing.tag
// Look up the previous screen in the map
previousScreen = fragmentTagMap.entries.find { it.value.tag == tag }?.key
pushNew =
if (entry.tag == tag) {
Logger.d("Pushing the same fragment")
false
} else {
Logger.d("Pushing a new fragment over an old one")
true
}
}
if (pushNew || force) {
if (force) {
Logger.d("Force commit fragment: ${entry.tag}")
} else {
Logger.d("Commit fragment: ${entry.tag}")
}
updateCurrentScreen(newScreen = screen.screen)
performFragmentTransaction(
fragmentContainerId,
entry,
screen,
previousScreen,
)
return true
} else {
return false
}
}
/** Perform a fragment transaction commit */
@JvmOverloads
protected fun commit(
immediate: Boolean = false,
transaction: FragmentTransaction.() -> FragmentTransaction,
) {
fragmentManager.commit(
owner = lifecycleOwner,
immediate = immediate,
transaction = transaction,
)
}
/** Perform a fragment transaction commitNow */
protected fun commitNow(transaction: FragmentTransaction.() -> FragmentTransaction) {
fragmentManager.commitNow(
owner = lifecycleOwner,
transaction = transaction,
)
}
/** A mapping of string Tags to Fragment providers */
public interface FragmentTag {
/** Tag */
public val tag: String
/** Fragment provider */
public val fragment: (arguments: Bundle?) -> Fragment
}
}
| 6 | null | 3 | 8 | 8f3f1e3c77f6caeaea58036b1091bb7ddf283485 | 5,431 | pydroid | Apache License 2.0 |
src/main/kotlin/com/cyb3rko/m3okotlin/data/Nfts.kt | cyb3rko | 464,602,194 | false | {"Kotlin": 236737} | package com.cyb3rko.m3okotlin.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.JsonTransformingSerializer
import kotlinx.serialization.serializer
// Requests & Responses + Data (single use)
@Serializable
internal data class NftsAssetRequest(
@SerialName("contract_address")
val contractAddress: String,
@SerialName("token_id")
val tokenId: String
)
@Serializable
data class NftsAssetResponse(val asset: NftsAsset)
@Serializable
internal data class NftsAssetsRequest(
val collection: String,
val cursor: String,
val limit: Int,
val order: String,
@SerialName("order_by")
val orderBy: String
)
@Serializable
data class NftsAssetsResponse(
val assets: List<NftsAsset>,
val next: String,
val previous: String
)
@Serializable
internal data class NftsCollectionRequest(val slug: String)
@Serializable
data class NftsCollectionResponse(val collection: NftsCollection)
@Serializable
internal data class NftsCollectionsRequest(val limit: Int, val offset: Int)
@Serializable
data class NftsCollectionsResponse(val collections: List<NftsCollection>)
// Data (multiple use)
@Serializable
data class NftsAccount(
val address: String,
@SerialName("profile_url")
val profileUrl: String,
val username: String
)
@Serializable
data class NftsAsset(
val collection: NftsCollection,
val contract: NftsContract,
val creator: NftsAccount,
val description: String,
val id: Int,
@SerialName("image_url")
val imageUrl: String,
@SerialName("last_sale")
val lastSale: NftsSale,
@SerialName("listing_date")
val listingDate: String,
val name: String,
val owner: NftsAccount,
val permalink: String,
val presale: Boolean,
val sales: Int,
@SerialName("token_id")
val tokenId: String,
val traits: List<NftsAssetTrait>
)
@Serializable
data class NftsAssetTrait(
@SerialName("display_type")
val displayType: String? = null,
@SerialName("max_value")
val maxValue: String? = null,
val order: String? = null,
@SerialName("trait_count")
val traitCount: Int,
@SerialName("trait_type")
val traitType: String,
@Serializable(with = NftsAssetTraitValueSerializer::class)
val value: String
) {
private object NftsAssetTraitValueSerializer: JsonTransformingSerializer<String>(serializer<String>()) {
override fun transformDeserialize(element: JsonElement): JsonElement {
return JsonPrimitive(element.toString())
}
}
}
@Serializable
data class NftsCollection(
@SerialName("banner_image_url")
val bannerImageUrl: String,
@SerialName("created_at")
val createdAt: String,
val description: String,
val editors: List<String>,
@SerialName("external_link")
val externalLink: String,
@SerialName("image_url")
val imageUrl: String,
val name: String,
@SerialName("payment_tokens")
val paymentTokens: List<NftsPaymentToken>,
@SerialName("payout_address")
val payoutAddress: String,
@SerialName("primary_asset_contracts")
val primaryAssetContracts: List<NftsContract>,
@SerialName("safelist_request_status")
val safelistRequestStatus: String,
@SerialName("seller_fees")
val sellerFees: String,
val slug: String,
val stats: NftsCollectionStats,
val traits: Map<String, Map<String, Float>>
)
@Serializable
data class NftsContract(
val address: String,
@SerialName("created_at")
val createdAt: String,
val description: String,
val name: String,
val owner: Int,
@SerialName("payout_address")
val payoutAddress: String,
val schema: String,
@SerialName("seller_fees")
val sellerFees: String,
val symbol: String,
val type: String
)
@Serializable
data class NftsPaymentToken(
val address: String,
val decimals: Int,
@SerialName("eth_price")
val ethPrice: String,
val id: Int,
@SerialName("image_url")
val imageUrl: String,
val name: String,
val symbol: String,
@SerialName("usd_price")
val usdPrice: String
)
@Serializable
data class NftsSale(
@SerialName("asset_decimals")
val assetDecimals: Int,
@SerialName("asset_token_id")
val assetTokenId: String,
@SerialName("created_at")
val createdAt: String,
@SerialName("event_timestamp")
val eventTimestamp: String,
@SerialName("event_type")
val eventType: String,
@SerialName("payment_token")
val paymentToken: NftsPaymentToken? = null,
val quantity: String,
@SerialName("total_price")
val totalPrice: String,
val transaction: NftsTransaction? = null
)
@Serializable
data class NftsCollectionStats(
@SerialName("average_price")
val averagePrice: Double? = null,
val count: Int? = null,
@SerialName("floor_price")
val floorPrice: Double? = null,
@SerialName("market_cap")
val marketCap: Double? = null,
@SerialName("num_owners")
val numOwners: Int? = null,
@SerialName("num_reports")
val numReports: Int? = null,
@SerialName("one_day_average_price")
val oneDayAveragePrice: Double? = null,
@SerialName("one_day_change")
val oneDayChange: Double? = null,
@SerialName("one_day_sales")
val oneDaySales: Int? = null,
@SerialName("one_day_volume")
val oneDayVolume: Double? = null,
@SerialName("seven_day_average_price")
val sevenDayAveragePrice: Double? = null,
@SerialName("seven_day_change")
val sevenDayChange: Double? = null,
@SerialName("seven_day_sales")
val sevenDaySales: Int? = null,
@SerialName("seven_day_volume")
val sevenDayVolume: Double? = null,
@SerialName("thirty_day_average_price")
val thirtyDayAveragePrice: Double? = null,
@SerialName("thirty_day_change")
val thirtyDayChange: Double? = null,
@SerialName("thirty_day_sales")
val thirtyDaySales: Int? = null,
@SerialName("thirty_day_volume")
val thirtyDayVolume: Double? = null,
@SerialName("total_sales")
val totalSales: Int? = null,
@SerialName("total_supply")
val totalSupply: Int? = null,
@SerialName("total_volume")
val totalVolume: Double? = null,
)
@Serializable
data class NftsTransaction(
@SerialName("block_hash")
val blockHash: String,
@SerialName("block_number")
val blockNumber: String,
@SerialName("from_account")
val fromAccount: NftsAccount,
val id: Int,
val timestamp: String,
@SerialName("to_account")
val toAccount: NftsAccount,
@SerialName("transaction_hash")
val transactionHash: String,
@SerialName("transaction_index")
val transactionIndex: String
)
| 0 | Kotlin | 0 | 1 | 6f175f9c1fb329664b130d04aad6e465f75d18c0 | 6,805 | m3o-kotlin | Apache License 2.0 |
data/src/main/java/com/sucho/data/usecase/GetSwansonQuoteUseCase.kt | suchoX | 375,678,376 | false | null | package com.sucho.data.usecase
import com.sucho.data.repository.SwansonQuoteWithImageRepo
import com.sucho.domain.model.SwansonQuoteWithImage
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class GetSwansonQuoteUseCase @Inject constructor(
private val swansonQuoteWithImageRepo: SwansonQuoteWithImageRepo
) : BaseUseCase<Flow<SwansonQuoteWithImage>, Unit> {
override suspend fun perform(): Flow<SwansonQuoteWithImage> {
return swansonQuoteWithImageRepo.swansonQuote
}
} | 0 | Kotlin | 0 | 1 | 1b6b1b49ab54763ba96e1837d38ac79fb59b7771 | 537 | PlaygroundAndroid | MIT License |
app/src/main/java/com/app/skyss_companion/model/travelplanner/Intermediate.kt | martinheitmann | 339,335,251 | false | null | package com.app.skyss_companion.model.travelplanner
data class Intermediate(
val stopName: String? = null,
val status: String? = null,
val aimedTime: String? = null
) | 0 | Kotlin | 0 | 1 | a4a79e658643731cd76617cdb9458aa1f742d4c3 | 179 | bus-companion | MIT License |
libB/src/main/java/package_B_13/Foo_B_1313.kt | lekz112 | 118,451,085 | false | null | package package_B_13
class Foo_B_1313 {
fun foo0() {
var i=0
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
Foo_B_1312().foo0()
}
} | 0 | Kotlin | 0 | 0 | 8182b7f6e92f9d65efb954c32ca640fe50ae6b79 | 584 | ModuleTest | Apache License 2.0 |
app/src/main/java/lijewski/template/di/module/ViewModelModule.kt | DawidLijewski | 216,089,329 | false | {"Kotlin": 13529} | package lijewski.template.di.module
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
import lijewski.template.di.factory.ViewModelFactory
import lijewski.template.di.key.ViewModelKey
import lijewski.template.presentation.main.MainViewModel
@Suppress("unused")
@Module
abstract class ViewModelModule {
@Binds
abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
abstract fun bindDashboardViewModel(dashboardViewModel: MainViewModel): ViewModel
}
| 0 | Kotlin | 0 | 0 | 2f681465138b832a31111e03a28cd2c230dccfe8 | 667 | template-android | MIT License |
chess-service/src/test/kotlin/com/michibaum/chess_service/domain/PersonProvider.kt | MichiBaum | 246,055,538 | false | {"Kotlin": 152355, "TypeScript": 36802, "HTML": 11408, "CSS": 3150, "Java": 1289, "JavaScript": 969, "SCSS": 393} | package com.michibaum.chess_service.domain
class PersonProvider {
companion object {
fun person(accounts: Set<Account> = emptySet()): Person {
return Person(firstname = "Michi", lastname = "Baum", accounts = accounts)
}
}
} | 0 | Kotlin | 0 | 1 | 77911b5f9d53f6630e34e3cd89b69ba277ad2b87 | 262 | Microservices | Apache License 2.0 |
app/src/main/java/jp/juggler/subwaytooter/util/AudioPicker.kt | tateisu | 89,120,200 | false | {"Kotlin": 4343773, "Java": 324536, "Perl": 47551} | package jp.juggler.subwaytooter.util
import androidx.appcompat.app.AppCompatActivity
import jp.juggler.subwaytooter.R
import jp.juggler.util.coroutine.launchAndShowError
import jp.juggler.util.data.UriAndType
import jp.juggler.util.data.checkMimeTypeAndGrant
import jp.juggler.util.data.intentGetContent
import jp.juggler.util.log.LogCategory
import jp.juggler.util.ui.ActivityResultHandler
import jp.juggler.util.ui.isOk
import jp.juggler.util.ui.launch
class AudioPicker(
private val onPicked: suspend (list: List<UriAndType>?) -> Unit,
) {
companion object {
private val log = LogCategory("AudioPicker")
}
private lateinit var activity: AppCompatActivity
private val prPickAudio = permissionSpecAudioPicker.requester {
activity.launchAndShowError {
open()
}
}
private val arPickAudio = ActivityResultHandler(log) { r ->
activity.launchAndShowError {
if (r.isOk) {
onPicked(r.data?.checkMimeTypeAndGrant(activity.contentResolver))
}
}
}
fun register(activity: AppCompatActivity) {
this.activity = activity
prPickAudio.register(activity)
arPickAudio.register(activity)
}
fun open() {
if (!prPickAudio.checkOrLaunch()) return
intentGetContent(
allowMultiple = true,
caption = activity.getString(R.string.pick_audios),
mimeTypes = arrayOf("audio/*"),
).launch(arPickAudio)
}
}
| 37 | Kotlin | 23 | 238 | f20f9fee8ef29bfcbba0f4c610ca8c2fb1c29d4f | 1,506 | SubwayTooter | Apache License 2.0 |
src/main/kotlin/com/exactpro/th2/check1/StreamContainer.kt | th2-net | 314,775,556 | false | null | /*
* Copyright 2020-2021 Exactpro (Exactpro Systems Limited)
* 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.exactpro.th2.check1
import com.exactpro.th2.common.grpc.Message
import io.reactivex.Observable
class StreamContainer(val sessionKey : SessionKey,
limitSize : Int,
messageObservable : Observable<Message>) {
val bufferedMessages : Observable<Message>
private val currentMessage : Observable<Message>
init {
val replay = messageObservable.replay(1)
currentMessage = replay
bufferedMessages = currentMessage.replay(limitSize).apply { connect() }
// if we connect it before [bufferedMessages] stream is constructed we might lose some data
replay.connect()
}
val lastMessage : Message
get() = currentMessage.firstElement().blockingGet()
override fun equals(other: Any?): Boolean =
if (other is StreamContainer) {
sessionKey == other.sessionKey
} else false
override fun hashCode(): Int = sessionKey.hashCode()
} | 5 | Kotlin | 1 | 1 | 60c788bc848b5dc799fc6d81d45e40fea0b24bae | 1,584 | th2-check1 | Apache License 2.0 |
misk-cron/src/main/kotlin/misk/cron/CronService.kt | cashapp | 113,107,217 | false | {"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58} | package misk.cron
import com.google.common.util.concurrent.AbstractIdleService
import com.google.inject.Injector
import wisp.logging.getLogger
import jakarta.inject.Inject
import jakarta.inject.Singleton
@Singleton
internal class CronService @Inject constructor(
private val injector: Injector
) : AbstractIdleService() {
@Inject private lateinit var cronManager: CronManager
@Inject private lateinit var cronRunnableEntries: List<CronRunnableEntry>
override fun startUp() {
logger.info { "CronService started" }
cronRunnableEntries.forEach { cronRunnable ->
val name = cronRunnable.runnableClass.qualifiedName!!
val annotations = cronRunnable.runnableClass.annotations
val cronPattern = annotations.find { it is CronPattern } as? CronPattern
?: throw IllegalArgumentException("Expected $name to have @CronPattern specified")
val runnable = injector.getProvider(cronRunnable.runnableClass.java).get()
cronManager.addCron(name, cronPattern.pattern, runnable)
}
}
override fun shutDown() {
cronManager.removeAllCrons()
logger.info { "CronService stopped" }
}
companion object {
private val logger = getLogger<CronService>()
}
}
| 169 | Kotlin | 169 | 400 | 13dcba0c4e69cc2856021270c99857e7e91af27d | 1,213 | misk | Apache License 2.0 |
ANALYTICS/src/main/kotlin/org/example/analytics/controllers/SkillController.kt | M4tT3d | 874,249,564 | false | {"Kotlin": 354206, "TypeScript": 180680, "JavaScript": 3610, "Dockerfile": 2844, "CSS": 2078, "HTML": 302} | package org.example.analytics.controllers
import org.example.analytics.dtos.toCombine
import org.example.analytics.dtos.toResponse
import org.example.analytics.services.SkillJobOfferService
import org.example.analytics.services.SkillProfessionalService
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("api/skill")
class SkillController(
val skillJobOfferService: SkillJobOfferService,
val skillProfessionalService: SkillProfessionalService
) {
private val logger = LoggerFactory.getLogger(SkillController::class.java)
// JOB OFFER
@GetMapping("/jo", "/jo/")
fun listAllJO(): ResponseEntity<List<Map<String, Any?>>> {
val response = skillJobOfferService.listAll().map {
it.toResponse()
}
logger.info("Retrieving skills of job offers")
return ResponseEntity(response, HttpStatus.OK)
}
@GetMapping("/jo/mostAndLeast", "jo/mostAndLeast/")
fun mostAndLeastRequestJO(): ResponseEntity<Map<String, Any?>> {
val response = skillJobOfferService.mostAndLeastRequest()
logger.info("Retrieving most and least requested skills of job offers")
return ResponseEntity(response, HttpStatus.OK)
}
// PROFESSIONAL
@GetMapping("/p", "/p/")
fun listAllP(): ResponseEntity<List<Map<String, Any?>>> {
val response = skillProfessionalService.listAll().map {
it.toResponse()
}
logger.info("Retrieving skills of professionals")
return ResponseEntity(response, HttpStatus.OK)
}
@GetMapping("/p/mostAndLeast", "/p/mostAndLeast/")
fun mostAndLeastRequestP(): ResponseEntity<Map<String, Any?>> {
val response = skillProfessionalService.mostAndLeastRequest()
logger.info("Retrieving most and least requested skills of professionals")
return ResponseEntity(response, HttpStatus.OK)
}
//COMBINED
@GetMapping("/all", "/all/")
fun listAll(): ResponseEntity<List<Map<String, Any?>>> {
val skillJO = skillJobOfferService.listAll().map {
it.toCombine()
}
val skillP = skillProfessionalService.listAll().map {
it.toCombine()
}
val response = convertToGraph(skillJO, skillP)
logger.info("Retrieving all skills")
return ResponseEntity(response, HttpStatus.OK)
}
}
fun convertToGraph(skillsJO: List<Map<String, Any?>>, skillsP: List<Map<String, Any?>>): List<Map<String, Any?>> {
val response = skillsJO.map { it.toMutableMap() }.toMutableList()
var added: Int
for (skillP in skillsP) {
added = 0
for (skill in response) {
if (skill["name"] == skillP["name"]) {
skill["professional"] = skillP["professional"]
added = 1
break
}
}
if (added == 0) {
val new = mapOf(
"name" to skillP["name"],
"jobOffer" to 0,
"professional" to skillP["professional"]
)
response.add(new.toMutableMap())
}
}
return response
} | 0 | Kotlin | 0 | 0 | ccad8f0a41e77e03935e548b4f03969fc051a61f | 3,376 | wa2-project-job-placement | MIT License |
android/src/main/kotlin/com/aiuta/flutter/fashionsdk/domain/mappers/configuration/theme/gradients/GradientsMapper.kt | aiuta-com | 869,372,273 | false | {"Kotlin": 63874, "Dart": 35479, "Swift": 3001, "Ruby": 2342, "Objective-C": 38} | package com.aiuta.flutter.fashionsdk.domain.mappers.configuration.theme.gradients
import com.aiuta.fashionsdk.compose.tokens.gradient.AiutaGradients
import com.aiuta.flutter.fashionsdk.domain.mappers.configuration.theme.colors.toColor
import com.aiuta.flutter.fashionsdk.domain.models.configuration.theme.gradients.PlatformAiutaGradients
fun PlatformAiutaGradients.toAiutaGradients(): AiutaGradients {
return AiutaGradients(
loadingAnimation = this.loadingAnimation.map { argbString -> argbString.toColor() }
)
}
| 3 | Kotlin | 0 | 0 | 8aa5ca6542f68df1c3f3ccb7ac373c3b8bb15dbe | 531 | flutter-sdk | Apache License 2.0 |
cinescout/suggestions/presentation/src/main/kotlin/cinescout/suggestions/presentation/worker/UpdateSuggestionsWorker.kt | fardavide | 280,630,732 | false | null | package cinescout.suggestions.presentation.worker
import android.annotation.SuppressLint
import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import arrow.core.Either
import arrow.core.left
import cinescout.error.NetworkError
import cinescout.notification.UpdateSuggestionsNotifications
import cinescout.screenplay.domain.model.ScreenplayTypeFilter
import cinescout.suggestions.domain.model.SuggestionsMode
import cinescout.suggestions.domain.usecase.UpdateSuggestions
import cinescout.utils.android.createOutput
import cinescout.utils.android.requireInput
import cinescout.utils.android.setInput
import cinescout.utils.kotlin.IoDispatcher
import co.touchlab.kermit.Logger
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.logEvent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.koin.android.annotation.KoinWorker
import org.koin.core.annotation.Named
import kotlin.time.Duration
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.measureTimedValue
import kotlin.time.toJavaDuration
@KoinWorker
class UpdateSuggestionsWorker(
appContext: Context,
params: WorkerParameters,
private val analytics: FirebaseAnalytics,
@Named(IoDispatcher) private val ioDispatcher: CoroutineDispatcher,
private val notifications: UpdateSuggestionsNotifications,
private val updateSuggestions: UpdateSuggestions
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result = withContext(ioDispatcher) {
val input = requireInput<SuggestionsMode>()
setForeground(notifications.foregroundInfo())
val (result, time) = measureTimedValue {
withTimeoutOrNull(10.minutes) { updateSuggestions(ScreenplayTypeFilter.All, input) }
?: NetworkError.Unknown.left()
}
handleResult(input, time, result)
return@withContext toWorkerResult(result)
}
@SuppressLint("MissingPermission")
private fun handleResult(
input: SuggestionsMode,
time: Duration,
result: Either<NetworkError, Unit>
) {
logAnalytics(input, time, result)
result
.onRight {
Logger.i("Successfully updated suggestions for ${input.name}")
notifications.success().show()
}
.onLeft { error ->
Logger.e("Error updating suggestions for ${input.name}: $error")
notifications.error().show()
}
}
private fun logAnalytics(
input: SuggestionsMode,
time: Duration,
result: Either<NetworkError, Unit>
) {
analytics.logEvent(Analytics.EventName) {
param(Analytics.TypeParameter, input.name)
param(Analytics.TimeParameter, time.inWholeSeconds)
param(
Analytics.ResultParameter,
result.fold(
ifLeft = { "${Analytics.ErrorWithReason}$it" },
ifRight = { Analytics.Success }
)
)
}
}
private fun toWorkerResult(result: Either<NetworkError, Unit>): Result = result.fold(
ifRight = { Result.success() },
ifLeft = { error ->
when {
runAttemptCount < MaxAttempts -> Result.retry()
else -> Result.failure(createOutput(error.toString()))
}
}
)
class Scheduler(private val workManager: WorkManager) {
operator fun invoke(suggestionsMode: SuggestionsMode) {
when (suggestionsMode) {
SuggestionsMode.Deep -> schedulePeriodic()
SuggestionsMode.Quick -> scheduleExpedited()
}
}
private fun scheduleExpedited() {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val requestBuilder = OneTimeWorkRequestBuilder<UpdateSuggestionsWorker>()
val request = requestBuilder
.setConstraints(constraints)
.setInput(SuggestionsMode.Quick)
.setBackoffCriteria(BackoffPolicy.LINEAR, Backoff.toJavaDuration())
.build()
workManager.enqueueUniqueWork(
ExpeditedName,
ExistingWorkPolicy.REPLACE,
request
)
}
private fun schedulePeriodic() {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresDeviceIdle(true)
.build()
val requestBuilder = PeriodicWorkRequestBuilder<UpdateSuggestionsWorker>(
repeatInterval = Interval.toJavaDuration(),
flexTimeInterval = FlexInterval.toJavaDuration()
)
val request = requestBuilder
.setConstraints(constraints)
.setInput(SuggestionsMode.Deep)
.build()
workManager.enqueueUniquePeriodicWork(
PeriodicName,
ExistingPeriodicWorkPolicy.KEEP,
request
)
}
}
companion object {
const val MaxAttempts = 5
const val ExpeditedName = "UpdateSuggestionsWorker.expedited"
const val PeriodicName = "UpdateSuggestionsWorker.periodic"
val Backoff = 10.seconds
val Interval = 1.days
val FlexInterval = 3.days
}
private object Analytics {
const val ErrorWithReason = "Error: "
const val EventName = "update_suggestions"
const val ResultParameter = "result"
const val Success = "Success"
const val TimeParameter = "time_seconds"
const val TypeParameter = "type"
}
}
| 10 | Kotlin | 2 | 6 | 7a875cd67a3df0ab98af520485122652bd5de560 | 6,331 | CineScout | Apache License 2.0 |
src/main/kotlin/com/intershop/gradle/icm/extension/FilePackage.kt | IntershopCommunicationsAG | 202,111,872 | false | {"Kotlin": 159788, "Groovy": 125109} | /*
* Copyright 2019 Intershop Communications AG.
*
* 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.intershop.gradle.icm.extension
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import javax.inject.Inject
/**
* Object to configure a simple file object to copy.
*/
open class FilePackage @Inject constructor(objectFactory: ObjectFactory ) {
/**
* This list contains includes for file list.
*
* @property includes list of includes
*/
@get:Input
var includes: SetProperty<String> = objectFactory.setProperty(String::class.java)
/**
* Add pattern to include.
*
* @param pattern Ant style pattern
*/
fun include(pattern: String) {
includes.add(pattern)
}
/**
* Add a list of patterns to include.
*
* @param patterns Ant style pattern
*/
fun includes(patterns: Collection<String>) {
includes.addAll(patterns)
}
/**
* This list contains excludes for file list.
*
* @property excludes list of includes
*/
@get:Input
var excludes: SetProperty<String> = objectFactory.setProperty(String::class.java)
/**
* Add pattern to include.
*
* @param pattern Ant style pattern
*/
fun exclude(pattern: String) {
excludes.add(pattern)
}
/**
* Add a list of patterns to include.
*
* @param patterns Ant style pattern
*/
fun excludes(patterns: Collection<String>) {
excludes.addAll(patterns)
}
/**
* The duplication strategy for this package.
*
* @property duplicateStrategy duplication strategy.
*/
@get:Input
val duplicateStrategy: Property<DuplicatesStrategy> = objectFactory.property(DuplicatesStrategy::class.java)
@get:Optional
@get:Input
val targetPath: Property<String> = objectFactory.property(String::class.java)
init {
duplicateStrategy.set(DuplicatesStrategy.INHERIT)
}
}
| 0 | Kotlin | 1 | 3 | 4a3a5df22a779cf76aa9d4d9147a1c8f96f5dc78 | 2,680 | icm-gradle-plugin | Apache License 2.0 |
domain/src/main/java/com/yoti/domain/base/SubjectUseCase.kt | mmbehroozfar | 672,992,569 | false | null | package com.yoti.domain.base
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
abstract class SubjectUseCase<in PARAMS, out TYPE>(private val coroutineDispatcher: CoroutineDispatcher) {
// Ideally this would be buffer = 0, since we use flatMapLatest below, BUT invoke is not
// suspending. This means that we can't suspend while flatMapLatest cancels any
// existing flows. The buffer of 1 means that we can use tryEmit() and buffer the value
// instead, resulting in mostly the same result.
private val paramState = MutableSharedFlow<PARAMS>(
replay = 1,
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
val flow: Flow<TYPE> = paramState
.distinctUntilChanged()
.flatMapLatest { createObservable(it).flowOn(coroutineDispatcher) }
.distinctUntilChanged()
operator fun invoke(params: PARAMS) {
paramState.tryEmit(params)
}
protected abstract suspend fun createObservable(params: PARAMS): Flow<TYPE>
} | 0 | Kotlin | 0 | 0 | 9a38ea84b7c7117c2c7651792d2d1acef69e53b5 | 1,290 | Crypto-Assets | MIT License |
src/main/kotlin/TelegramService.kt | OctoDiary | 616,147,520 | false | null | import com.github.kotlintelegrambot.Bot
import com.github.kotlintelegrambot.bot
import com.github.kotlintelegrambot.dispatch
import com.github.kotlintelegrambot.dispatcher.Dispatcher
import handlers.commandAuth
import handlers.commandDiary
import org.jetbrains.exposed.sql.Database
class TelegramService(
private val botToken: String,
dbHost: String,
dbUser: String,
dbPassword: String
) {
private val bot: Bot = bot {
token = botToken
dispatch { dispatcher() }
}
init {
bot.startPolling()
Database.connect(
url = dbHost,
user = dbUser,
password = <PASSWORD>,
driver = "org.postgresql.Driver"
)
}
context(Dispatcher)
private fun dispatcher() {
commandAuth()
commandDiary()
}
} | 0 | Kotlin | 0 | 0 | 67310616841b88de3eca3895c768c9f7d372d0c8 | 828 | OctoDiary-tg | The Unlicense |
newm-server/src/main/kotlin/io/newm/server/features/distribution/model/OutletStatusCode.kt | projectNEWM | 447,979,150 | false | {"Kotlin": 2068136, "HTML": 153991, "Shell": 2775, "Dockerfile": 2535, "Procfile": 60} | package io.newm.server.features.distribution.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class OutletStatusCode(
val code: Int
) {
@SerialName("1021")
DRAFT(1021),
@SerialName("1022")
READY_TO_DISTRIBUTE(1022),
@SerialName("1208")
READY_TO_SUBMIT(1208),
@SerialName("1201")
DISTRIBUTE_INITIATED(1201),
@SerialName("1202")
DISTRIBUTED(1202),
@SerialName("1203")
TAKEDOWN_INITIATED(1203),
@SerialName("1205")
UPDATE_INITIATED(1205),
@SerialName("1206")
UPDATED(1206),
@SerialName("1207")
REVIEW_PENDING(1207),
@SerialName("1034")
DISAPPROVED(1034),
}
| 1 | Kotlin | 4 | 9 | 395b894082b23560d29dcfe3fa69201e0916565e | 707 | newm-server | Apache License 2.0 |
.space.kts | JetBrains-Research | 244,400,016 | false | null | val jsContainer = "registry.jetbrains.team/p/ki/containers-ci/ci-corretto-17-firefox:1.0.1"
val jvmContainer = "amazoncorretto:17"
job("KInference / Build") {
container("Build With Gradle", jvmContainer) {
kotlinScript { api ->
api.gradlew("assemble", "--parallel", "--console=plain", "--no-daemon")
}
}
}
job("KInference / Test / JVM") {
container("JVM Tests", jvmContainer) {
kotlinScript { api ->
api.gradlew("jvmTest", "--parallel", "--console=plain", "-Pci", "--no-daemon")
}
}
}
job("KInference / Test / JS IR") {
container("JS IR Tests", jsContainer) {
shellScript {
content = xvfbRun("./gradlew jsIrTest jsTest --parallel --console=plain -Pci --no-daemon")
}
}
}
job("KInference / Test / JS Legacy") {
container("JS Legacy Tests", jsContainer) {
shellScript {
content = xvfbRun("./gradlew jsLegacyTest --parallel --console=plain -Pci --no-daemon")
}
}
}
job("KInference / Heavy Test / JVM") {
container("JVM Heavy Tests", jvmContainer) {
addAwsKeys()
kotlinScript { api ->
api.gradlew("jvmHeavyTest", "--console=plain", "-Pci", "--no-daemon")
}
}
}
job("KInference / Heavy Test / JS IR") {
container("JS IR Heavy Tests", jsContainer) {
addAwsKeys()
shellScript {
content = xvfbRun("./gradlew jsIrHeavyTest --console=plain -Pci --no-daemon")
}
}
}
job("KInference / Heavy Test / JS Legacy") {
container("JS Legacy Heavy Tests", jsContainer) {
addAwsKeys()
shellScript {
content = xvfbRun("./gradlew jsLegacyHeavyTest --console=plain -Pci --no-daemon")
}
}
}
job("KInference / Release") {
startOn {
gitPush {
enabled = false
}
}
container("Release", jvmContainer) {
addAwsKeys()
kotlinScript { api ->
api.gradlew("publish", "--parallel", "--console=plain", "--no-daemon")
}
}
}
fun Container.addAwsKeys() {
env["AWS_ACCESS_KEY"] = "{{ project:aws_access_key }}"
env["AWS_SECRET_KEY"] = "{{ project:aws_secret_key }}"
}
fun xvfbRun(command: String): String = "xvfb-run --auto-servernum $command"
| 4 | null | 5 | 95 | e47129b6f1e2a60bf12404d8126701ce7ef4db3a | 2,281 | kinference | Apache License 2.0 |
.space.kts | JetBrains-Research | 244,400,016 | false | null | val jsContainer = "registry.jetbrains.team/p/ki/containers-ci/ci-corretto-17-firefox:1.0.1"
val jvmContainer = "amazoncorretto:17"
job("KInference / Build") {
container("Build With Gradle", jvmContainer) {
kotlinScript { api ->
api.gradlew("assemble", "--parallel", "--console=plain", "--no-daemon")
}
}
}
job("KInference / Test / JVM") {
container("JVM Tests", jvmContainer) {
kotlinScript { api ->
api.gradlew("jvmTest", "--parallel", "--console=plain", "-Pci", "--no-daemon")
}
}
}
job("KInference / Test / JS IR") {
container("JS IR Tests", jsContainer) {
shellScript {
content = xvfbRun("./gradlew jsIrTest jsTest --parallel --console=plain -Pci --no-daemon")
}
}
}
job("KInference / Test / JS Legacy") {
container("JS Legacy Tests", jsContainer) {
shellScript {
content = xvfbRun("./gradlew jsLegacyTest --parallel --console=plain -Pci --no-daemon")
}
}
}
job("KInference / Heavy Test / JVM") {
container("JVM Heavy Tests", jvmContainer) {
addAwsKeys()
kotlinScript { api ->
api.gradlew("jvmHeavyTest", "--console=plain", "-Pci", "--no-daemon")
}
}
}
job("KInference / Heavy Test / JS IR") {
container("JS IR Heavy Tests", jsContainer) {
addAwsKeys()
shellScript {
content = xvfbRun("./gradlew jsIrHeavyTest --console=plain -Pci --no-daemon")
}
}
}
job("KInference / Heavy Test / JS Legacy") {
container("JS Legacy Heavy Tests", jsContainer) {
addAwsKeys()
shellScript {
content = xvfbRun("./gradlew jsLegacyHeavyTest --console=plain -Pci --no-daemon")
}
}
}
job("KInference / Release") {
startOn {
gitPush {
enabled = false
}
}
container("Release", jvmContainer) {
addAwsKeys()
kotlinScript { api ->
api.gradlew("publish", "--parallel", "--console=plain", "--no-daemon")
}
}
}
fun Container.addAwsKeys() {
env["AWS_ACCESS_KEY"] = "{{ project:aws_access_key }}"
env["AWS_SECRET_KEY"] = "{{ project:aws_secret_key }}"
}
fun xvfbRun(command: String): String = "xvfb-run --auto-servernum $command"
| 4 | null | 5 | 95 | e47129b6f1e2a60bf12404d8126701ce7ef4db3a | 2,281 | kinference | Apache License 2.0 |
src/main/kotlin/equalsToStringHashCode/exDataClass/Pessoa.kt | rafamaneschy | 392,862,658 | false | null | package equalsToStringHashCode.exDataClass
data class Pessoa(val nome:String, val cpf:Int)
fun main() {
val pessoaA = Pessoa("Rafael", 1234567)
val pessoaB = Pessoa("Rafael", 1234567)
println(pessoaA.toString() == pessoaB.toString()) //True
println(pessoaB.hashCode() == pessoaA.hashCode()) //True
} | 0 | Kotlin | 0 | 0 | 0d0e60f7f2b19511cabe9202d0fa872d4d3d0c80 | 320 | atividadesDH | MIT License |
app/src/main/java/com/comic_con/museum/ar/injection/CCMComponent.kt | Comic-Con-Museum | 153,692,659 | false | {"Kotlin": 71992} | package com.comic_con.museum.ar.injection
import com.comic_con.museum.ar.MainActivity
import com.comic_con.museum.ar.experience.ExperienceActivity
import com.comic_con.museum.ar.experience.ExperienceFragment
import com.comic_con.museum.ar.experience.content.ContentActivity
import com.comic_con.museum.ar.experience.content.ContentOverviewFragment
import com.comic_con.museum.ar.experience.content.activityfragments.ContentListingFragment
import com.comic_con.museum.ar.experience.content.activityfragments.ContentSingleFragment
import com.comic_con.museum.ar.experience.progress.ProgressFragment
import com.comic_con.museum.ar.experience.progress.ProgressViewModel
import com.comic_con.museum.ar.injection.sharedpreferences.SharedPreferencesModule
import com.comic_con.museum.ar.loading.LoadingScreenFragment
import com.comic_con.museum.ar.overview.OverviewFragment
import com.comic_con.museum.ar.views.ProgressView
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules=[CCMInjector::class,ContextModule::class, SharedPreferencesModule::class])
interface CCMComponent {
// View Model Injection
fun inject(f: OverviewFragment)
fun inject(f: LoadingScreenFragment)
fun inject(f: MainActivity)
fun inject(a: ExperienceActivity)
fun inject(f: ExperienceFragment)
fun inject(f: ProgressFragment)
fun inject(f: ContentOverviewFragment)
fun inject(f: ContentListingFragment)
fun inject(f: ContentSingleFragment)
fun inject(f: ContentActivity)
fun inject(v: ProgressView)
// Context Injection
fun inject(module: SharedPreferencesModule)
// Shared Preferences Injection
fun inject(vm: ProgressViewModel)
} | 18 | Kotlin | 1 | 8 | 6e5396fde31d57f5bcde87f608d1357c468c90d2 | 1,707 | ccm-android | Apache License 2.0 |
composeApp/src/commonMain/kotlin/domain/ArticleRepository.kt | oikvpqya | 865,870,220 | false | {"Kotlin": 24652} | package domain
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import kotlinx.serialization.json.Json
import me.tatarka.inject.annotations.Inject
interface ArticleRepository {
suspend fun fetchAll() : List<Article>
suspend fun fetchByTag(tag: String) : List<Article>
}
@Inject
class DefaultArticleRepository(
private val httpClient: HttpClient,
) : ArticleRepository {
private suspend fun fetch(target: String): List<Article> {
val result = httpClient.get("https://qiita.com/$target")
val json = Json {
ignoreUnknownKeys = true
}
return json.decodeFromString<List<Article>>(result.bodyAsText())
}
override suspend fun fetchAll(): List<Article> {
return fetch("api/v2/items")
}
override suspend fun fetchByTag(tag: String): List<Article> {
return fetch("api/v2/tags/$tag/items")
}
}
| 0 | Kotlin | 0 | 0 | 056f70a9db0135092adc3a05d6bccd95769076f0 | 947 | compose-mvp-architecture | Apache License 2.0 |
reflekt-dsl/src/main/kotlin/io/reflekt/util/TypeStringRepresentation.kt | altavir | 408,735,983 | true | {"Kotlin": 257342} | package io.reflekt.util
import kotlin.reflect.*
/*
* This object has util functions for converting in the same String representation
* for different types in Kotlin compiler, e.g. KType, KotlinType
* */
object TypeStringRepresentationUtil {
private const val SEPARATOR = ", "
private const val NULLABLE_SYMBOL = "?"
const val STAR_SYMBOL = "*"
fun getStringRepresentation(classifierName: String, arguments: List<String>): String {
val argumentsStr = if (arguments.isNotEmpty()) {
"<${arguments.joinToString(separator = SEPARATOR)}>"
} else {
""
}
return "$classifierName$argumentsStr"
}
fun markAsNullable(type: String, isNullable: Boolean): String = if (isNullable) {
"$type$NULLABLE_SYMBOL"
} else {
type
}
}
internal fun KType.stringRepresentation(classifierName: String) =
TypeStringRepresentationUtil.getStringRepresentation(classifierName, arguments.mapNotNull { it.type?.stringRepresentation() })
fun KType.stringRepresentation() : String {
// Get simple classifier name, e.g. kotlin.Function1
val classifierName = (classifier as? KClass<*>)?.qualifiedName ?: (classifier as? KTypeParameter)?.name ?: ""
// If type is null it means we have star projection
return TypeStringRepresentationUtil
.getStringRepresentation(classifierName,
arguments.map {
it.type?.let { t ->
TypeStringRepresentationUtil.markAsNullable(t.stringRepresentation(), t.isMarkedNullable)
} ?: it.toString()
}
)
}
| 0 | null | 0 | 0 | d8938ad12beeb2b53a4abe647ae6f875a1157d29 | 1,614 | reflekt | Apache License 2.0 |
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/types/media/MaskPosition.kt | vendelieu | 496,567,172 | false | null | package eu.vendeli.tgbot.types.media
data class MaskPosition(
val point: String,
val xShift: Float,
val yShift: Float,
val scale: Float,
)
| 4 | Kotlin | 3 | 92 | 162068369ea2e7881d93f2190e49c6b1b0659719 | 156 | telegram-bot | Apache License 2.0 |
kt/godot-library/src/main/kotlin/godot/gen/godot/ENetPacketPeer.kt | utopia-rise | 289,462,532 | false | {"Kotlin": 1455718, "C++": 480143, "GDScript": 464697, "C#": 10278, "C": 8523, "Shell": 7976, "Java": 2136, "CMake": 939, "Python": 75} | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.GodotError
import godot.core.PackedByteArray
import godot.core.VariantType.BOOL
import godot.core.VariantType.DOUBLE
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.PACKED_BYTE_ARRAY
import godot.core.VariantType.STRING
import godot.core.memory.TransferContext
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.jvm.JvmOverloads
@GodotBaseType
public open class ENetPacketPeer internal constructor() : PacketPeer() {
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_ENETPACKETPEER, scriptIndex)
return true
}
@JvmOverloads
public fun peerDisconnect(`data`: Int = 0): Unit {
TransferContext.writeArguments(LONG to data.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_PEER_DISCONNECT, NIL)
}
@JvmOverloads
public fun peerDisconnectLater(`data`: Int = 0): Unit {
TransferContext.writeArguments(LONG to data.toLong())
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_PEER_DISCONNECT_LATER, NIL)
}
@JvmOverloads
public fun peerDisconnectNow(`data`: Int = 0): Unit {
TransferContext.writeArguments(LONG to data.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_PEER_DISCONNECT_NOW,
NIL)
}
public fun ping(): Unit {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_PING, NIL)
}
public fun pingInterval(pingInterval: Int): Unit {
TransferContext.writeArguments(LONG to pingInterval.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_PING_INTERVAL, NIL)
}
public fun reset(): Unit {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_RESET, NIL)
}
public fun send(
channel: Int,
packet: PackedByteArray,
flags: Int,
): GodotError {
TransferContext.writeArguments(LONG to channel.toLong(), PACKED_BYTE_ARRAY to packet, LONG to flags.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_SEND, LONG)
return GodotError.from(TransferContext.readReturnValue(LONG) as Long)
}
public fun throttleConfigure(
interval: Int,
acceleration: Int,
deceleration: Int,
): Unit {
TransferContext.writeArguments(LONG to interval.toLong(), LONG to acceleration.toLong(), LONG to deceleration.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_THROTTLE_CONFIGURE,
NIL)
}
public fun setTimeout(
timeout: Int,
timeoutMin: Int,
timeoutMax: Int,
): Unit {
TransferContext.writeArguments(LONG to timeout.toLong(), LONG to timeoutMin.toLong(), LONG to timeoutMax.toLong())
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_SET_TIMEOUT, NIL)
}
public fun getRemoteAddress(): String {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_GET_REMOTE_ADDRESS,
STRING)
return (TransferContext.readReturnValue(STRING, false) as String)
}
public fun getRemotePort(): Int {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_GET_REMOTE_PORT,
LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
public fun getStatistic(statistic: PeerStatistic): Double {
TransferContext.writeArguments(LONG to statistic.id)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_GET_STATISTIC,
DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double)
}
public fun getState(): PeerState {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_GET_STATE, LONG)
return ENetPacketPeer.PeerState.from(TransferContext.readReturnValue(LONG) as Long)
}
public fun getChannels(): Int {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_GET_CHANNELS, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
public fun isActive(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ENETPACKETPEER_IS_ACTIVE, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public enum class PeerState(
id: Long,
) {
STATE_DISCONNECTED(0),
STATE_CONNECTING(1),
STATE_ACKNOWLEDGING_CONNECT(2),
STATE_CONNECTION_PENDING(3),
STATE_CONNECTION_SUCCEEDED(4),
STATE_CONNECTED(5),
STATE_DISCONNECT_LATER(6),
STATE_DISCONNECTING(7),
STATE_ACKNOWLEDGING_DISCONNECT(8),
STATE_ZOMBIE(9),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class PeerStatistic(
id: Long,
) {
PEER_PACKET_LOSS(0),
PEER_PACKET_LOSS_VARIANCE(1),
PEER_PACKET_LOSS_EPOCH(2),
PEER_ROUND_TRIP_TIME(3),
PEER_ROUND_TRIP_TIME_VARIANCE(4),
PEER_LAST_ROUND_TRIP_TIME(5),
PEER_LAST_ROUND_TRIP_TIME_VARIANCE(6),
PEER_PACKET_THROTTLE(7),
PEER_PACKET_THROTTLE_LIMIT(8),
PEER_PACKET_THROTTLE_COUNTER(9),
PEER_PACKET_THROTTLE_EPOCH(10),
PEER_PACKET_THROTTLE_ACCELERATION(11),
PEER_PACKET_THROTTLE_DECELERATION(12),
PEER_PACKET_THROTTLE_INTERVAL(13),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public companion object {
public final const val PACKET_LOSS_SCALE: Long = 65536
public final const val PACKET_THROTTLE_SCALE: Long = 32
public final const val FLAG_RELIABLE: Long = 1
public final const val FLAG_UNSEQUENCED: Long = 2
public final const val FLAG_UNRELIABLE_FRAGMENT: Long = 8
}
}
| 60 | Kotlin | 28 | 412 | fe7379a450ed32ad069f3b672709a2520b86f092 | 6,699 | godot-kotlin-jvm | MIT License |
feature/channel/src/main/java/com/m3u/feature/channel/components/FormatItem.kt | oxyroid | 592,741,804 | false | null | package com.m3u.features.stream.components
import androidx.compose.foundation.clickable
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.media3.common.C
import androidx.media3.common.Format
@Composable
internal fun FormatItem(
format: Format,
type: @C.TrackType Int,
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
val colorScheme = MaterialTheme.colorScheme
MaterialTheme(
colorScheme = colorScheme.copy(
surface = if (selected) colorScheme.onSurface else colorScheme.surface,
onSurface = if (selected) colorScheme.surface else colorScheme.onSurface,
surfaceVariant = if (selected) colorScheme.onSurfaceVariant else colorScheme.surfaceVariant,
onSurfaceVariant = if (selected) colorScheme.surfaceVariant else colorScheme.onSurfaceVariant
)
) {
ListItem(
headlineContent = {
Text(format.displayText(type))
},
modifier = modifier.clickable { onClick() }
)
}
}
private fun Format.displayText(type: @C.TrackType Int): String = when (type) {
C.TRACK_TYPE_AUDIO -> "$sampleRate $sampleMimeType"
C.TRACK_TYPE_VIDEO -> "$width×$height $sampleMimeType"
C.TRACK_TYPE_TEXT -> buildList {
label?.let { add(it) }
language?.let { add(it) }
sampleMimeType?.let { add(it) }
}
.joinToString(separator = "-")
else -> sampleMimeType.orEmpty()
} | 34 | null | 33 | 375 | ca92e3487c8e22b73b50197baa2d652185cb4f2e | 1,652 | M3UAndroid | Apache License 2.0 |
ProvaCode/app/src/main/java/com/example/provacode/Produto.kt | CHcrocs | 861,710,546 | false | {"Kotlin": 12645} | package com.example.provacode
data class Produto(
var nome: String,
var categoria: String,
var preco: Float,
var quantEstoque: Int
) | 0 | Kotlin | 0 | 0 | 096725d3ff01088175f4dbc9a3ee064a30be2092 | 149 | Prova | MIT License |
Chapter09/Activity09.01/app/src/androidTest/java/com/packt/android/MainActivityTest.kt | PacktPublishing | 810,886,298 | false | {"Kotlin": 989730} | package com.packt.android
import android.app.Application
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.lifecycle.Lifecycle
import androidx.test.core.app.ActivityScenario.launch
import androidx.test.core.app.ApplicationProvider.getApplicationContext
import org.junit.Rule
import org.junit.Test
class MainActivityTest {
@get:Rule
val composeRule = createComposeRule()
@Test
fun verifyItemClicked() {
val scenario = launch(MainActivity::class.java)
scenario.moveToState(Lifecycle.State.RESUMED)
composeRule.onNodeWithText(getApplicationContext<Application>().getString(R.string.press_me))
.performClick()
composeRule.onNodeWithText(
getApplicationContext<Application>().getString(
R.string.item_x,
"9"
)
).performClick()
composeRule.onNodeWithText(
getApplicationContext<Application>().getString(
R.string.clicked_item_x,
"9"
)
).assertIsDisplayed()
}
} | 0 | Kotlin | 2 | 2 | c8aa1dd9b7dbea064681fbb492619aab4e969fbe | 1,223 | How-to-Build-Android-Apps-with-Kotlin-Third-Edition | MIT License |
app/src/main/java/com/example/linkedup/utils/CompanyDao.kt | HaqqiLucky | 871,143,159 | false | {"Kotlin": 87171} | package com.example.linkedup.utils
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
@Dao
interface CompanyDao {
@Query("SELECT * FROM company")
fun getAll(): List<Company>
@Insert
suspend fun insert(vararg company: Company)
@Delete
suspend fun delete(vararg company: Company)
@Update
suspend fun update(vararg company: Company)
} | 0 | Kotlin | 0 | 0 | fad4a9dd41ee4978fed0529a6466b77b897f8a48 | 488 | LinkedUp | MIT License |
src/main/kotlin/collections/03-AsSequences.kt | mkdika | 149,041,144 | false | null | package collections
import kotlin.streams.toList
/**
* Sequences
*
* Use sequence for bigger collections with more than one
* processing step, instead of Iterable (list, array, etc.)
*
*/
fun main(args: Array<String>) {
val people = listOf(Person("Alice",27),
Person("Bob", 31),
Person("Carol", 31),
Person("Andy", 20),
Person("Acung", 45))
// More than one step intermediate processing
val peopleA = people.asSequence()
.map { it.name }
.filter { it.startsWith("A") }
.sorted()
.toList()
println(peopleA)
// use java8 stream
// with same intermediate operation
val peopleB = people.stream()
.map { it.name }
.filter{ it.startsWith("A")}
.sorted()
.toList()
println(peopleB)
} | 0 | Kotlin | 0 | 0 | 4d4aed9f913f9f75fcdee3e81014f3f8e7d5a977 | 866 | learn-kotlin | MIT License |
app/src/main/java/com/no5ing/bbibbi/presentation/ui/navigation/destination/RegisterDestination.kt | depromeet | 738,807,741 | false | {"Kotlin": 649362} | package com.no5ing.bbibbi.presentation.ui.navigation.destination
import android.net.Uri
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.navigation.navArgument
import com.no5ing.bbibbi.presentation.state.register.nickname.rememberRegisterNickNamePageState
import com.no5ing.bbibbi.presentation.state.register.profile_image.rememberRegisterProfileImagePageState
import com.no5ing.bbibbi.presentation.ui.feature.register.day_of_birth.RegisterDayOfBirthPage
import com.no5ing.bbibbi.presentation.ui.feature.register.nickname.RegisterNickNamePage
import com.no5ing.bbibbi.presentation.ui.feature.register.profile_image.RegisterProfileImagePage
object RegisterNicknameDestination : NavigationDestination(
route = registerNickNameRoute,
content = { navController, _ ->
val nickNameState = rememberRegisterNickNamePageState()
RegisterNickNamePage(
state = nickNameState,
onNextPage = {
navController.navigate(
destination = RegisterDayOfBirthDestination,
params = listOf("nickName" to nickNameState.nicknameTextState.value)
)
})
}
)
object RegisterDayOfBirthDestination : NavigationDestination(
route = registerDayOfBirthRoute,
arguments = listOf(navArgument("nickName") { }),
content = { navController, backStackEntry ->
val nickName = backStackEntry.arguments?.getString("nickName")
?: "UNKNOWN"
RegisterDayOfBirthPage(
nickName = nickName,
onNextPage = {
navController.navigate(
destination = RegisterProfileImageDestination,
params = listOf("nickName" to nickName, "dayOfBirth" to it)
)
}
)
}
)
object RegisterProfileImageDestination : NavigationDestination(
route = registerProfileImageRoute,
arguments = listOf(navArgument("nickName") { }, navArgument("dayOfBirth") { }),
content = { navController, backStackEntry ->
val imgState = remember { mutableStateOf<Uri?>(null) }
val imgUrl = backStackEntry.savedStateHandle.remove<Uri?>("imageUrl")
if (imgUrl != null) {
imgState.value = imgUrl
}
RegisterProfileImagePage(
state = rememberRegisterProfileImagePageState(
profileImageUri = imgState,
),
nickName = backStackEntry.arguments?.getString("nickName")
?: throw RuntimeException(),
dayOfBirth = backStackEntry.arguments?.getString("dayOfBirth")
?: throw RuntimeException(),
onNextPage = {
navController.popBackStack(
route = LandingLoginDestination.route,
inclusive = true
)
navController.navigate(
destination = LandingLoginDestination,
)
navController.navigate(
destination = LandingOnBoardingDestination,
)
},
onTapCamera = {
navController.navigate(
destination = CameraViewDestination,
)
}
)
}
) | 0 | Kotlin | 0 | 3 | 5d0d722bf8390b9e75c46bdeabd40485df207251 | 3,302 | 14th-team5-AOS | MIT License |
DITest3/app/src/main/java/com/example/ditest3/service/IGetWebDataService.kt | DokySp-study | 717,329,915 | false | {"Kotlin": 15275} | package com.example.ditest3.service
import com.example.ditest3.domain.WebData
interface IGetWebDataService {
fun getWebDataByUrl(url: String): WebData
} | 0 | Kotlin | 0 | 0 | a11ea446d2e5190e0cbc7ee1c11d18160e3bbcee | 158 | clean-architecture-android | MIT License |
data/src/main/java/io/wax911/challenge/data/credit/entity/CreditEntity.kt | wax911 | 457,808,380 | false | {"Kotlin": 140698} | package io.wax911.challenge.data.credit.entity
import androidx.room.ColumnInfo
import androidx.room.Embedded
import androidx.room.Entity
import io.wax911.challenge.domain.credit.enums.Persona
import io.wax911.challenge.domain.credit.enums.Status
@Entity(
tableName = "credit",
primaryKeys = ["id"]
)
internal data class CreditEntity(
@ColumnInfo(name = "id") val id: String,
@ColumnInfo(name = "expires_at") val expiresAt: Long,
@ColumnInfo(name = "account_idv_status") val accountIDVStatus: Status,
@Embedded(prefix = "credit_") val creditReportInfo: ReportInfo,
@ColumnInfo(name = "dashboard_status") val dashboardStatus: Status,
@ColumnInfo(name = "persona_type") val personaType: Persona,
@Embedded(prefix = "credit_") val coachingSummary: CoachingSummary,
@ColumnInfo(name = "augmented_credit_score") val augmentedCreditScore: String?,
) {
data class ReportInfo(
@ColumnInfo(name ="score") val score: Int,
@ColumnInfo(name ="score_band") val scoreBand: Int,
@ColumnInfo(name ="status") val status: Status,
@ColumnInfo(name ="max_score_value") val maxScoreValue: Int,
@ColumnInfo(name ="min_score_value") val minScoreValue: Int,
@ColumnInfo(name ="months_since_last_defaulted") val monthsSinceLastDefaulted: Int,
@ColumnInfo(name ="has_ever_defaulted") val hasEverDefaulted: Boolean,
@ColumnInfo(name ="months_since_last_delinquent") val monthsSinceLastDelinquent: Int,
@ColumnInfo(name ="has_ever_been_delinquent") val hasEverBeenDelinquent: Boolean,
@ColumnInfo(name ="percentage_credit_used") val percentageCreditUsed: Int,
@ColumnInfo(name ="percentage_credit_used_direction_flag") val percentageCreditUsedDirectionFlag: Int,
@ColumnInfo(name ="changed_score") val changedScore: Int,
@ColumnInfo(name ="current_short_term_debt") val currentShortTermDebt: Int,
@ColumnInfo(name ="current_short_term_non_promotional_debt") val currentShortTermNonPromotionalDebt: Int,
@ColumnInfo(name ="current_short_term_credit_limit") val currentShortTermCreditLimit: Int,
@ColumnInfo(name ="current_short_term_credit_utilisation") val currentShortTermCreditUtilisation: Int,
@ColumnInfo(name ="changeInShort_term_debt") val changeInShortTermDebt: Int,
@ColumnInfo(name ="current_long_term_debt") val currentLongTermDebt: Int,
@ColumnInfo(name ="current_long_term_non_promotional_debt") val currentLongTermNonPromotionalDebt: Int,
@ColumnInfo(name ="current_long_term_credit_limit") val currentLongTermCreditLimit: Int?,
@ColumnInfo(name ="current_long_term_credit_utilisation") val currentLongTermCreditUtilisation: Int?,
@ColumnInfo(name ="change_in_long_term_debt") val changeInLongTermDebt: Int,
@ColumnInfo(name ="num_positive_score_factors") val numPositiveScoreFactors: Int,
@ColumnInfo(name ="num_negative_score_factors") val numNegativeScoreFactors: Int,
@ColumnInfo(name ="equifax_score_band") val equifaxScoreBand: Int,
@ColumnInfo(name ="equifax_score_band_description") val equifaxScoreBandDescription: String,
@ColumnInfo(name ="days_until_next_report") val daysUntilNextReport: Int,
)
data class CoachingSummary(
@ColumnInfo(name = "active_todo") val activeTodo: Boolean,
@ColumnInfo(name = "active_chat") val activeChat: Boolean,
@ColumnInfo(name = "number_of_todo_items") val numberOfTodoItems: Int,
@ColumnInfo(name = "number_of_completed_todo_items") val numberOfCompletedTodoItems: Int,
@ColumnInfo(name = "selected") val selected: Boolean,
)
} | 0 | Kotlin | 0 | 0 | b975c8bbc266bd7a19abeadd585f94407bbb95ec | 3,671 | android-tech-task | Apache License 2.0 |
android/app/src/main/kotlin/technology/unrelenting/freepass/Entry.kt | nhz-io | 70,366,178 | true | {"Rust": 64456, "Swift": 27673, "Kotlin": 14399, "Shell": 5109, "Makefile": 2031, "C": 1309} | package technology.unrelenting.freepass
data class Entry(var fields: Map<String, Field>) | 0 | Rust | 0 | 0 | e83ac7718d2a7718b3c79f5d52cd463e3c391ea0 | 89 | freepass | The Unlicense |
shared/src/commonMain/kotlin/ui/word/WordCard.kt | eloev | 695,826,888 | false | {"Kotlin": 61383, "Swift": 1668, "Shell": 231, "Ruby": 101} | package ui.word
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import domain.entity.Word
import domain.entity.WordType
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import utils.Colors
import utils.AsyncImage
import utils.AudioPlayer
@OptIn(ExperimentalResourceApi::class)
@Composable
fun WordCard(
word: Word,
bottomPadding: Dp
) {
val player = AudioPlayer()
return Column(
modifier = Modifier
.fillMaxSize(1f)
.verticalScroll(state = rememberScrollState()),
horizontalAlignment = Alignment.Start
) {
AsyncImage(
url = word.image,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.aspectRatio(16f / 9f)
.padding(vertical = 16.dp)
.clip(RoundedCornerShape(CornerSize(16.dp)))
.border(
BorderStroke(2.dp, Color(Colors.LITE_GRAY)),
RoundedCornerShape(CornerSize(16.dp))
)
)
Text(
text = word.type.toString(),
fontSize = 15.sp,
letterSpacing = 0.01.sp,
color = Color.Black,
modifier = Modifier
.padding(top = 16.dp)
.clip(RoundedCornerShape(CornerSize(4.dp)))
.background(
Color(
when (word.type) {
WordType.VERB -> Colors.GREEN_8
WordType.NOUN -> Colors.BLUE_8
WordType.PRONOUN -> Colors.CYAN_8
WordType.ADJECTIVE -> Colors.ORANGE_8
}
)
)
.padding(4.dp)
)
Row(
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
verticalAlignment = Alignment.Bottom
) {
Text(
text = word.origin,
fontSize = 34.sp,
fontWeight = FontWeight.Bold,
letterSpacing = 0.01.sp,
color = Color.Black,
)
Image(
painter = painterResource("ic_audio.xml"),
contentDescription = null,
contentScale = ContentScale.None,
modifier = Modifier
.padding(horizontal = 16.dp)
.clip(CircleShape)
.clickable(enabled = true) {
utils.vibrate()
player.play(word.audioUrl)
}
)
}
Text(
text = word.transcription,
fontSize = 17.sp,
letterSpacing = 0.01.sp,
color = Color(Colors.BLACK_65),
modifier = Modifier.padding(top = 4.dp)
)
Text(
text = word.translated,
fontSize = 24.sp,
letterSpacing = 0.01.sp,
color = Color.Black,
modifier = Modifier.padding(top = 20.dp)
)
if (word.examples.isNotEmpty()) {
Text(
text = "Пример из контекста",
fontSize = 20.sp,
letterSpacing = 0.01.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
modifier = Modifier.padding(top = 50.dp)
)
word.examples.forEach { wordExample ->
WordExamplesCard(
wordExample = wordExample,
playAudio = { player.play(it) }
)
}
}
Spacer(modifier = Modifier.size(bottomPadding))
}
} | 0 | Kotlin | 0 | 0 | c691c451cee7dd097a1e5968ef4b6fc536dd0f2d | 5,055 | try_multiplatform_compose | Apache License 2.0 |
utility/bases-android/src/main/java/com/shamlou/bases_android/context/Snackbar.kt | keivanshamlu | 453,712,116 | false | null | package com.shamlou.bases_android.context
import android.view.View
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.Snackbar
fun View.showSnackBar(
@StringRes message: Int,
duration: Int = Snackbar.LENGTH_SHORT
) = Snackbar.make(this, message, duration).show()
fun Fragment.showSnackBar(
@StringRes message: Int,
duration: Int = Snackbar.LENGTH_SHORT
) = view?.showSnackBar(message, duration)
fun View.showSnackBar(
message: String,
duration: Int = Snackbar.LENGTH_SHORT
) = Snackbar.make(this, message, duration).show()
fun Fragment.showSnackBar(
message: String,
duration: Int = Snackbar.LENGTH_SHORT
) = view?.showSnackBar(message, duration) | 0 | Kotlin | 0 | 0 | 631b1d7bd0997d985866f42e25db4f1cc4e11297 | 751 | All-cities | Apache License 2.0 |
lovebird-api/src/main/kotlin/com/lovebird/api/provider/oauth/AppleAuthProvider.kt | wooda-ege | 722,352,043 | false | {"Kotlin": 143743, "HTML": 36994, "Shell": 1811} | package com.lovebird.api.provider.oauth
import com.lovebird.api.dto.param.user.OAuthParam
import com.lovebird.api.provider.PublicKeyProvider
import com.lovebird.api.validator.JwtValidator
import com.lovebird.client.web.AppleAuthClient
import io.jsonwebtoken.Claims
import org.springframework.stereotype.Component
@Component
class AppleAuthProvider(
private val appleAuthClient: AppleAuthClient,
private val publicKeyProvider: PublicKeyProvider,
private val jwtValidator: JwtValidator
) : OAuthProvider {
override fun getProviderId(request: Any): String {
return getClaims(idToken = request as String).subject
}
override fun getOAuthParam(request: Any): OAuthParam {
return OAuthParam.from(getClaims(idToken = request as String))
}
private fun getClaims(idToken: String): Claims {
val publicKey = publicKeyProvider.generatePublicKey(getHeaders(idToken), appleAuthClient.getPublicKeys())
return jwtValidator.getTokenClaims(idToken, publicKey)
}
private fun getHeaders(idToken: String): Map<String, String> {
return jwtValidator.parseHeaders(idToken)
}
}
| 4 | Kotlin | 0 | 9 | f35a7febafc19d34b8aa57063efe930bf0d162ab | 1,079 | lovebird-server | MIT License |
app/src/main/java/com/svape/schools/network/ApiService.kt | Enrique213-VP | 815,585,007 | false | {"Kotlin": 29866} |
/*
interface ApiService {
@POST("DatabaseIE.php")
suspend fun getMunicipios(
@Body request: RequestBody
): Response<ApiResponse<List<Municipio>>>
@POST("DatabaseIE.php")
suspend fun getInstituciones(
@Body request: RequestBody
): Response<ApiResponse<List<Institucion>>>
@POST("DatabaseIE.php")
suspend fun getSedes(
@Body request: RequestBody
): Response<ApiResponse<List<Sede>>>
@POST("DatabaseIE.php")
suspend fun getGrupos(
@Body request: RequestBody
): Response<ApiResponse<List<Grupo>>>
@POST("DatabaseIE.php")
suspend fun getGrupoInfo(
@Body request: RequestBody
): Response<ApiResponse<GrupoInfo>>
}*/
| 0 | Kotlin | 0 | 0 | fca6d77b058d88961aab34a294314e930d2deb64 | 716 | Schools | MIT License |
quickbadger/src/main/java/com/raqun/quickbadger/impl/DefaultBadger.kt | savepopulation | 148,345,469 | false | null | package com.raqun.quickbadger.impl
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import com.raqun.quickbadger.Badger
import com.raqun.quickbadger.ext.canResolveBroadcast
import java.util.*
/**
* A default Badger impl for unsupported launchers
*/
open class DefaultBadger(compName: ComponentName? = null,
con: Context? = null) : Badger {
protected var componentName = compName
protected var context = con?.applicationContext
override fun showBadge(count: Int) {
if (context == null) return
val badgeIntent = Intent(INTENT_ACTION).apply {
putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName?.className)
putExtra(INTENT_EXTRA_PACKAGENAME, componentName?.packageName)
putExtra(INTENT_EXTRA_BADGE_COUNT, count)
}
if (context!!.canResolveBroadcast(badgeIntent)) {
context!!.sendBroadcast(badgeIntent)
}
}
override fun dismissBadge() = showBadge(0)
override fun getSupportedLaunchers(): List<String> = ArrayList()
override fun initComponentName(componentName: ComponentName) {
this.componentName = componentName
}
override fun initContext(context: Context) {
this.context = context.applicationContext
}
companion object {
const val INTENT_ACTION = "android.intent.action.BADGE_COUNT_UPDATE"
private const val INTENT_EXTRA_BADGE_COUNT = "badge_count"
private const val INTENT_EXTRA_PACKAGENAME = "badge_count_package_name"
private const val INTENT_EXTRA_ACTIVITY_NAME = "badge_count_class_name"
}
}
| 1 | Kotlin | 3 | 16 | 9dd75872734e56b36783608ee7761e13484398f8 | 1,665 | quick-badger | Apache License 2.0 |
student/src/main/java/com/solutionteam/mindfulmentor/data/network/BaseRepository.kt | DevSkillSeekers | 746,597,864 | false | {"Kotlin": 412451} | package com.solutionteam.mindfulmentor.data.network
import com.solutionteam.mindfulmentor.data.network.response.BaseResponse
import retrofit2.Response
abstract class BaseRepository() {
private suspend fun <T : Any> wrap(function: suspend () -> Response<BaseResponse<T>>): T {
val response = function()
return if (response.isSuccessful) {
when (response.body()?.code) {
"100" -> response.body()?.payload
else -> throw Throwable(response.body()?.message.toString())
} as T
} else {
throw Throwable("Network Error")
}
}
} | 1 | Kotlin | 0 | 1 | 05d9da5efba3b9ca8b0c2e409d1329d8e22f19dd | 631 | GradesFromGeeks | Apache License 2.0 |
app/src/main/java/com/pimenta/bestv/data/local/MediaLocalRepositoryImpl.kt | Vij4yk | 222,473,642 | true | {"Kotlin": 381718} | /*
* Copyright (C) 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.pimenta.bestv.data.local
import com.pimenta.bestv.data.local.db.dao.MovieDao
import com.pimenta.bestv.data.local.db.dao.TvShowDao
import com.pimenta.bestv.data.local.entity.MovieDbModel
import com.pimenta.bestv.data.local.entity.TvShowDbModel
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.functions.BiFunction
import javax.inject.Inject
/**
* Created by marcus on 20-05-2018.
*/
class MediaLocalRepositoryImpl @Inject constructor(
private val movieDao: MovieDao,
private val tvShowDao: TvShowDao
) : MediaLocalRepository {
override fun hasFavorite(): Single<Boolean> =
Single.zip<List<MovieDbModel>, List<TvShowDbModel>, Pair<List<MovieDbModel>, List<TvShowDbModel>>>(
movieDao.getAll(),
tvShowDao.getAll(),
BiFunction { first, second -> Pair(first, second) }
).map {
it.first.isNotEmpty() || it.second.isNotEmpty()
}
override fun isFavoriteMovie(movieId: Int): Single<Boolean> =
movieDao.getById(movieId)
.map { it == 1 }
override fun isFavoriteTvShow(tvShowId: Int): Single<Boolean> =
tvShowDao.getById(tvShowId)
.map { it == 1 }
override fun saveFavoriteMovie(movieDbModel: MovieDbModel): Completable =
movieDao.create(movieDbModel)
override fun saveFavoriteTvShow(tvShowDbModel: TvShowDbModel): Completable =
tvShowDao.create(tvShowDbModel)
override fun deleteFavoriteMovie(movieDbModel: MovieDbModel): Completable =
movieDao.delete(movieDbModel)
override fun deleteFavoriteTvShow(tvShowDbModel: TvShowDbModel): Completable =
tvShowDao.delete(tvShowDbModel)
override fun getMovies(): Single<List<MovieDbModel>> =
movieDao.getAll()
override fun getTvShows(): Single<List<TvShowDbModel>> =
tvShowDao.getAll()
} | 0 | null | 0 | 1 | c843d997a801389f929b9a1fd754047ae1b348a0 | 2,547 | BesTV | Apache License 2.0 |
embrace-android-core/src/main/kotlin/io/embrace/android/embracesdk/internal/comms/api/ApiClient.kt | embrace-io | 704,537,857 | false | null | package io.embrace.android.embracesdk.internal.comms.api
import io.embrace.android.embracesdk.internal.injection.SerializationAction
/**
* A simple interface to make internal HTTP requests to the Embrace API
*/
public interface ApiClient {
/**
* Executes [ApiRequest] as a GET, returning the response as a [ApiResponse]
*/
public fun executeGet(request: ApiRequest): ApiResponse
/**
* Executes [ApiRequest] as a POST with the supplied action that writes to an outputstream,
* returning the response as a [ApiResponse]. The body will be gzip compressed.
*/
public fun executePost(request: ApiRequest, action: SerializationAction): ApiResponse
public companion object {
public const val NO_HTTP_RESPONSE: Int = -1
public const val TOO_MANY_REQUESTS: Int = 429
public const val defaultTimeoutMs: Int = 60 * 1000
}
}
| 20 | null | 8 | 134 | 896e9aadf568ba527c76ec66f6f440baed29d1ee | 895 | embrace-android-sdk | Apache License 2.0 |
app/src/main/java/com/bottlerocketstudios/brarchitecture/ui/splash/SplashFragmentViewModel.kt | BottleRocketStudios | 323,985,026 | false | null | package com.bottlerocketstudios.brarchitecture.ui.splash
import androidx.lifecycle.viewModelScope
import com.bottlerocketstudios.brarchitecture.R
import com.bottlerocketstudios.brarchitecture.data.repository.BitbucketRepository
import com.bottlerocketstudios.brarchitecture.infrastructure.coroutine.DispatcherProvider
import com.bottlerocketstudios.brarchitecture.navigation.NavigationEvent
import com.bottlerocketstudios.brarchitecture.ui.BaseViewModel
import kotlinx.coroutines.launch
class SplashFragmentViewModel(repo: BitbucketRepository, dispatcherProvider: DispatcherProvider) : BaseViewModel() {
init {
viewModelScope.launch(dispatcherProvider.IO) {
if (repo.authenticate()) {
navigationEvent.postValue(NavigationEvent.Action(R.id.action_splashFragment_to_homeFragment))
} else {
navigationEvent.postValue(NavigationEvent.Action(R.id.action_splashFragment_to_loginFragment))
}
}
}
}
| 0 | Kotlin | 1 | 5 | 779882b37d8f1e100e720c2d0bf42bf5739b59ce | 985 | Android-ArchitectureDemo | Apache License 2.0 |
UdidServer/src/main/kotlin/tools/util/Digest.kt | BillyWei01 | 210,720,192 | false | {"Kotlin": 60675, "Java": 16922} | package tools.util
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
object Digest {
@Throws(NoSuchAlgorithmException::class)
fun getShortMd5(msg: ByteArray?): String {
return Base64.getUrlEncoder().withoutPadding().encodeToString(md5(msg))
}
@Throws(NoSuchAlgorithmException::class)
fun md5(msg: ByteArray?): ByteArray {
return MessageDigest.getInstance("MD5").digest(msg)
}
@Throws(NoSuchAlgorithmException::class)
fun sha1(msg: ByteArray?): ByteArray {
return MessageDigest.getInstance("SHA-1").digest(msg)
}
@Throws(NoSuchAlgorithmException::class)
fun sha256(msg: ByteArray?): ByteArray {
return MessageDigest.getInstance("SHA-256").digest(msg)
}
@Throws(NoSuchAlgorithmException::class)
fun sha512(msg: ByteArray?): ByteArray {
return MessageDigest.getInstance("SHA-512").digest(msg)
}
}
| 0 | Kotlin | 41 | 236 | edfea1974db16661e3dee9a78ffed593aaa4e84c | 950 | Udid | MIT License |
app/src/main/java/com/example/bridge_authorized/DonorAnnoucmentTypeData.kt | Fbayrakci | 804,985,285 | false | {"Kotlin": 140217} | package com.example.bridge_authorized
data class DonorAnnoucmentTypeData(val annoucmentType: String, val annoucmentImg: Int, val activityClass: Class<*>)
| 0 | Kotlin | 0 | 0 | 5cef963db58280297a2f0c022f62145829cdb638 | 157 | Bridge-Disaster-Management | MIT License |
app/src/androidTest/java/com/example/espressoexample/MainActivityTest.kt | buildbro | 544,677,806 | false | {"Kotlin": 2876} | package com.example.espressoexample
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class MainActivityTest {
@get:Rule var activityScenarioRule = activityScenarioRule<MainActivity>()
@Test
fun nigeriaButtonTapped() {
onView(withId(R.id.button_ng)).perform(click())
onView(withId(R.id.messgae_textview)).check(matches(withText("NGN")))
}
}
| 0 | Kotlin | 1 | 0 | 1ff05077e2828baad75e1acc10bc33c0c4e06cf9 | 879 | Espresso-Example | MIT License |
z2-commons/src/commonMain/kotlin/hu/simplexion/z2/localization/text/StaticText.kt | spxbhuhb | 665,463,766 | false | {"Kotlin": 992844, "CSS": 127215, "Java": 7175, "HTML": 1560, "JavaScript": 975} | package hu.simplexion.z2.localization.text
import hu.simplexion.z2.localization.localizedTextStore
class StaticText(
override val key: String,
override var value: String,
) : LocalizedText {
// TODO cleanup StaticText, there are instances in the interface getters
override fun toString(): String {
return localizedTextStore[key]?.value ?: value
}
val localized
get() = toString() // TODO think about storing the value in the store only but not in the object
fun localizedReplace(vararg args : Pair<String, Any>) : String {
var result = toString()
for(arg in args) {
result = result.replace("{${arg.first}}", arg.second.toString())
}
return result
}
} | 0 | Kotlin | 0 | 1 | 1417d2684047f4eef924db54d5edd8d54f60fa11 | 748 | z2 | Apache License 2.0 |
frontend/app/src/main/java/com/kasiry/app/compose/Alert.kt | alfianandinugraha | 585,695,566 | false | null | package com.kasiry.app.compose
import android.view.Gravity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import com.kasiry.app.theme.Typo
import com.kasiry.app.theme.red
class AlertVariant {
}
@Composable
fun Alert(
title: String,
icon: ImageVector,
color: Color = Color.red(),
bgColor: Color= Color.red(50),
onClose: () -> Unit,
content: @Composable () -> Unit
) {
Dialog(onDismissRequest = onClose, properties = DialogProperties(dismissOnClickOutside = true)) {
Column(
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.fillMaxWidth(1f)
.background(Color.White)
.padding(horizontal = 24.dp, vertical = 16.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 12.dp)
) {
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier
.clip(
shape = RoundedCornerShape(999.dp)
)
.background(bgColor)
.padding(16.dp)
.size(32.dp),
tint = color
)
Text(
text = title,
style = Typo.body,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 8.dp),
fontSize = 18.sp,
color = color
)
}
content()
}
}
} | 0 | Kotlin | 0 | 1 | 6dc3a367acc255e7c2b1fe75543311b4bbb38b17 | 2,496 | kasiry | MIT License |
lib/stove-testing-e2e/src/main/kotlin/com/trendyol/stove/testing/e2e/system/abstractions/ExposesConfiguration.kt | Trendyol | 590,452,775 | false | null | package com.trendyol.stove.testing.e2e.system.abstractions
/**
* Marks the dependency which can expose the configuration that is needed to spin up the [ApplicationUnderTest]
* The [configuration] is collected and passed to [ApplicationUnderTest.start]
* For example:
* If kafka has a configuration that exposes as `bootStrapServers` can pass this configuration to the application itself.
* Our application probably depends on this configuration in either `application.yml`(for spring) or in any configuration structure.
* For spring applications, let's say you have `kafka.bootStrapServers` in the `application.yml`, then KafkaSystem needs to expose
* this configuration by implementing [ExposesConfiguration].
*
* @author <NAME>
*/
interface ExposesConfiguration {
/**
* Gets the configurations that dependency exposes.
* It is invoked after [RunAware.run], so docker instances are running at this stage.
*/
fun configuration(): List<String>
}
| 4 | null | 8 | 97 | 9e221948d4484b98f8216f0d3977513c26c96e49 | 980 | stove | Apache License 2.0 |
servers/graphql-kotlin-spring-server/src/main/kotlin/com/expediagroup/graphql/server/spring/GraphQLExecutionConfiguration.kt | ExpediaGroup | 148,706,161 | false | null | /*
* Copyright 2022 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.graphql.server.spring
import com.expediagroup.graphql.generator.execution.KotlinDataFetcherFactoryProvider
import com.expediagroup.graphql.dataloader.DataLoaderRegistryFactory
import com.expediagroup.graphql.dataloader.KotlinDataLoaderRegistryFactory
import com.expediagroup.graphql.dataloader.KotlinDataLoader
import com.expediagroup.graphql.server.spring.execution.SpringKotlinDataFetcherFactoryProvider
import graphql.execution.DataFetcherExceptionHandler
import graphql.execution.SimpleDataFetcherExceptionHandler
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import java.util.Optional
/**
* The root configuration class that other configurations can import to get the basic
* beans required to then create an executable GraphQL schema object.
*/
@Configuration
@EnableConfigurationProperties(GraphQLConfigurationProperties::class)
@Import(JacksonAutoConfiguration::class)
class GraphQLExecutionConfiguration {
@Bean
@ConditionalOnMissingBean
fun dataFetcherFactoryProvider(applicationContext: ApplicationContext): KotlinDataFetcherFactoryProvider =
SpringKotlinDataFetcherFactoryProvider(applicationContext)
@Bean
@ConditionalOnMissingBean
fun exceptionHandler(): DataFetcherExceptionHandler = SimpleDataFetcherExceptionHandler()
@Bean
@ConditionalOnMissingBean
fun dataLoaderRegistryFactory(dataLoaders: Optional<List<KotlinDataLoader<*, *>>>): DataLoaderRegistryFactory =
KotlinDataLoaderRegistryFactory(dataLoaders.orElse(emptyList()))
}
| 68 | null | 345 | 1,739 | d3ad96077fc6d02471f996ef34c67066145acb15 | 2,541 | graphql-kotlin | Apache License 2.0 |
app/src/main/java/com/pedrogomez/spacelensapp/models/api/Location.kt | makhnnar | 339,465,187 | false | null | package com.pedrogomez.spacelensapp.models.api
import kotlinx.serialization.Serializable
@Serializable
data class Location(
val latitude: Double,
val longitude: Double
) | 0 | Kotlin | 0 | 0 | 9ebee0a9bb0097c2453befd2377429860c33f401 | 179 | spaceLensAndImpl | MIT License |
src/test/kotlin/watch/craft/scrapers/JeffersonsScraperTest.kt | oliver-charlesworth | 273,553,100 | false | {"Kotlin": 289472, "TypeScript": 40268, "CSS": 9885, "HCL": 1516, "JavaScript": 964, "Shell": 440} | package watch.craft.scrapers
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import watch.craft.*
import watch.craft.Format.CAN
import watch.craft.Scraper.Node.ScrapedItem
import java.net.URI
class JeffersonsScraperTest {
companion object {
private val ITEMS = executeScraper(JeffersonsScraper(), dateString = "2020-08-02")
}
@Test
fun `finds all the beers`() {
assertEquals(4, ITEMS.size)
}
@Test
fun `extracts beer details`() {
assertEquals(
ScrapedItem(
name = "The Brightside",
summary = "Hazy Pale",
abv = 5.4,
offers = setOf(
Offer(totalPrice = 16.80, quantity = 6, sizeMl = 330, format = CAN)
),
available = true,
thumbnailUrl = URI("https://cdn.shopify.com/s/files/1/2172/2447/products/TheBrightside_Can_200x.jpg")
),
ITEMS.first { it.name == "The Brightside" && it.onlyOffer().quantity == 6 }.noDesc()
)
}
@Test
fun `extracts description`() {
assertNotNull(ITEMS.byName("The Brightside").desc)
}
}
| 4 | Kotlin | 1 | 0 | 9f4337f3da7223644ee389282e9a199d86336d8f | 1,132 | craft-watch | MIT License |
customerly-android-sdk/src/main/java/io/customerly/utils/ClyForegroundAppChecker.kt | Customerly | 77,624,700 | false | {"Kotlin": 494771, "Java": 66539} | package io.customerly.utils
/*
* Copyright (C) 2017 Customerly
*
* 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.
*/
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import io.customerly.utils.ggkext.weak
import java.lang.ref.WeakReference
/**
* Created by Gianni on 25/03/17.
*/
@Suppress("MemberVisibilityCanPrivate", "unused")
internal abstract class ForegroundAppChecker : Application.ActivityLifecycleCallbacks {
private var lastDisplayedActivity : WeakReference<Activity>? = null
private var pausedApplicationContext : WeakReference<Context>? = null
private var foreground = false
private val checkBackground = Runnable {
this.pausedApplicationContext?.get()?.let { applicationContext ->
if (this.foreground) {
this.foreground = false
this.doOnAppGoBackground(applicationContext = applicationContext)
}
}
}
internal val isInBackground : Boolean get() = !this.foreground
internal fun getLastDisplayedActivity() : Activity? = this.lastDisplayedActivity?.get()
final override fun onActivityResumed(activity: Activity) {
this.lastDisplayedActivity = activity.weak()
this.pausedApplicationContext = null
val wasBackground = !this.foreground
this.foreground = true
Handler(Looper.getMainLooper()).removeCallbacks(this.checkBackground)
this.doOnActivityResumed(activity, wasBackground)
}
final override fun onActivityPaused(activity: Activity) {
this.pausedApplicationContext = activity.applicationContext.weak()
val h = Handler(Looper.getMainLooper())
h.removeCallbacks(this.checkBackground)
h.postDelayed(this.checkBackground, 500)
this.doOnActivityPaused(activity)
}
final override fun onActivityDestroyed(activity: Activity) {
if(this.lastDisplayedActivity?.get() == activity) {
this.lastDisplayedActivity = null
}
this.doOnActivityDestroyed(activity = activity)
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
protected abstract fun doOnAppGoBackground(applicationContext : Context)
protected abstract fun doOnActivityResumed(activity: Activity, fromBackground: Boolean)
protected open fun doOnActivityDestroyed(activity: Activity) {}
protected open fun doOnActivityPaused(activity: Activity) {}
}
| 5 | Kotlin | 6 | 18 | 7289ef39ac94b4731822b61c783d9596b5ee995f | 3,247 | Android-SDK | Apache License 2.0 |
ok-profile-transport-mp/src/commonMain/kotlin/ok.profile.transport.main.mp/common/IMpDebug.kt | otuskotlin | 327,213,872 | false | null | package ok.profile.transport.main.mp.common
interface IMpDebug {
val mode: MpWorkModeDto?
}
| 1 | Kotlin | 0 | 0 | 61c642a939f73872586793c6dd1ac231eb22795f | 97 | otuskotlin-202012-profile-pd | MIT License |
feat-profile/src/main/java/com/mathroda/profile_screen/drawer/DrawerFooter.kt | MathRoda | 507,060,394 | false | {"Kotlin": 375433} | package com.mathroda.profile_screen.drawer
import androidx.compose.animation.ExperimentalAnimationApi
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.Spacer
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.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.mathroda.common.components.CustomDialogSignOut
import com.mathroda.common.components.CustomLoginButton
import com.mathroda.common.navigation.Destinations
import com.mathroda.common.theme.CustomRed
import com.mathroda.common.theme.DarkGray
import com.mathroda.common.theme.Gold
import com.mathroda.core.state.UserState
import com.mathroda.core.util.Constants
import com.mathroda.profile_screen.ProfileViewModel
import com.mathroda.profile_screen.R
@ExperimentalMaterialApi
@ExperimentalAnimationApi
@ExperimentalComposeUiApi
@Composable
fun DrawerFooter(
userState: UserState,
navController: NavController
) {
val uriHandler = LocalUriHandler.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Bottom,
modifier = Modifier
.fillMaxSize()
.padding(bottom = 60.dp)
) {
when(userState) {
is UserState.AuthedUser -> LogOut(navController)
is UserState.UnauthedUser -> Login(navController)
is UserState.PremiumUser -> LogOut(navController)
}
Spacer(modifier = Modifier.height(48.dp) )
Text(
text = "Contact Creator",
fontStyle = FontStyle.Italic,
fontWeight = FontWeight.SemiBold,
color = Gold
)
LazyRow {
item {
IconButton(onClick = { uriHandler.openUri(Constants.LINKEDIN) }) {
Icon(
painter = painterResource(id = R.drawable.ic_linkedin),
modifier = Modifier.size(18.dp),
contentDescription = "Linkedin"
)
}
Spacer(modifier = Modifier.size(12.dp))
IconButton(onClick = { uriHandler.openUri(Constants.GITHUB) }) {
Icon(
painter = painterResource(id = R.drawable.ic_github),
modifier = Modifier.size(18.dp),
contentDescription = "Github"
)
}
Spacer(modifier = Modifier.size(12.dp))
IconButton(onClick = { uriHandler.openUri(Constants.TWITTER) }) {
Icon(
painter = painterResource(id = R.drawable.ic_twitter),
modifier = Modifier.size(18.dp),
contentDescription = "Twitter"
)
}
}
}
}
}
@Composable
fun Login(navController: NavController) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
TopAppBar(title = { Text(text = "Profile") })
Spacer(modifier = Modifier.size(32.dp))
CustomLoginButton(
text = "LOGIN",
modifier = Modifier
.fillMaxWidth()
.background(DarkGray)
.padding(top = 24.dp),
) {
navController.navigate(Destinations.SignIn.route)
}
}
}
@ExperimentalComposeUiApi
@ExperimentalAnimationApi
@ExperimentalMaterialApi
@Composable
fun LogOut(
navController: NavController,
viewModel: ProfileViewModel = hiltViewModel()
) {
val openDialogCustom = remember { mutableStateOf(false) }
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
TopAppBar(title = { Text(text = "Profile") })
Spacer(modifier = Modifier.size(32.dp))
CustomLoginButton(
text = "LOGOUT",
modifier = Modifier
.fillMaxWidth()
.background(DarkGray)
.padding(top = 24.dp),
backgroundColor = CustomRed
) {
openDialogCustom.value = true
}
}
if (openDialogCustom.value) {
CustomDialogSignOut(openDialogCustom = openDialogCustom) {
viewModel.signOut()
navController.popBackStack()
navController.navigate(Destinations.CoinsScreen.route)
}
}
} | 0 | Kotlin | 40 | 275 | 33ef0b13d4873bb2b297b501dce8fda5e4982d42 | 5,595 | DashCoin | Apache License 2.0 |
src/test/kotlin/de/lancom/openapi/serialisation/AbstractSerialisationTest.kt | lancomsystems | 733,524,954 | false | {"Kotlin": 767613, "Mustache": 12233} | package de.lancom.openapi.serialisation
import de.lancom.openapi.assertYamlEquals
import de.lancom.openapi.entity.Entity
import de.lancom.openapi.tools.yamlMapper
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
abstract class AbstractSerialisationTest {
@ParameterizedTest
@MethodSource("testCases")
fun testDeserialisation(testCase: TestCase<Entity>) {
val actual = try {
yamlMapper.readValue(testCase.yamlForDeserialization, testCase.typeReference)
} catch (exception: Exception) {
println("failed to deserialize yaml:")
println(testCase.yamlForDeserialization)
throw RuntimeException(exception)
}
val expected = testCase.entityField.getOrError()
assertYamlEquals(expected, actual)
}
@ParameterizedTest
@MethodSource("testCases")
fun testSerialisation(testCase: TestCase<Entity>) {
val given = testCase.entityField.getOrError()
val actual = try {
yamlMapper.writeValueAsString(given)
} catch (exception: Exception) {
println("failed to serialize to yaml:")
println(testCase.entityField.getOrError())
throw RuntimeException(exception)
}
val expected = testCase.serializedYaml + "\n"
assertEquals(expected, actual)
}
}
| 1 | Kotlin | 0 | 1 | 702b35bb5d1c7d68164930483d0281ae7f3bf045 | 1,447 | openapi-parser | Apache License 2.0 |
android/src/main/java/com/thomasflad/covid19radar/android/MainActivityViewModel.kt | thomasflad | 440,110,344 | false | null | package com.thomasflad.covid19radar.android
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.thomasflad.covid19radar.domain.DataState
import com.thomasflad.covid19radar.domain.useCases.GetGermany
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted.Companion.WhileSubscribed
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.stateIn
class Inputs {
}
interface Outputs {
val weekIncidence: Flow<Double>
}
interface MainActivityViewModelType {
val inputs: Inputs
val outputs: Outputs
}
class MainActivityViewModel(
getGermanyUseCase: GetGermany
) : ViewModel(), MainActivityViewModelType, Outputs {
override val inputs: Inputs = Inputs()
override val outputs: Outputs = this
private val getGermany = getGermanyUseCase.dataFlow()
.stateIn(viewModelScope, WhileSubscribed(5000), DataState.initial())
override val weekIncidence = getGermany
.mapNotNull { it.data?.weekIncidence }
}
| 0 | Kotlin | 0 | 1 | 986b067cde3d6365cc58799f84474a69f8509e27 | 1,025 | Covid19Radar | Apache License 2.0 |
src/main/java/me/shadowalzazel/mcodyssey/enchantments/ranged/LuckyDraw.kt | ShadowAlzazel | 511,383,377 | false | {"Kotlin": 1003062} | package me.shadowalzazel.mcodyssey.enchantments.ranged
import me.shadowalzazel.mcodyssey.enchantments.base.OdysseyEnchantment
import net.kyori.adventure.text.Component
import org.bukkit.Material
import org.bukkit.enchantments.Enchantment
import org.bukkit.enchantments.Enchantment.ARROW_INFINITE
import org.bukkit.inventory.ItemStack
object LuckyDraw : OdysseyEnchantment("lucky_draw", "Lucky Draw", 3) {
override fun conflictsWith(other: Enchantment): Boolean {
return when (other) {
ARROW_INFINITE -> {
true
}
else -> {
false
}
}
}
override fun canEnchantItem(item: ItemStack): Boolean {
return when (item.type) {
Material.ENCHANTED_BOOK, Material.BOW -> {
true
}
else -> {
false
}
}
}
override fun getDescriptionToolTip(inputLevel: Int): List<Component> {
val amount1 = 7 + (10 * inputLevel)
val text1 = "$amount1=[7 + (level x 10)]% chance to not consume ammo."
return listOf(
getGrayComponentText(text1)
)
}
} | 0 | Kotlin | 0 | 3 | de66a1c653a98247254f7f70b2aaf9726d716a94 | 1,181 | MinecraftOdyssey | MIT License |
src/main/kotlin/info/dgjones/barnable/domain/general/CardinalDirection.kt | jonesd | 442,279,905 | false | {"Kotlin": 474251} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package info.dgjones.barnable.domain.general
import info.dgjones.barnable.concept.*
import info.dgjones.barnable.grammar.Preposition
import info.dgjones.barnable.grammar.PrepositionWord
import info.dgjones.barnable.parser.*
import info.dgjones.barnable.util.transformCamelCaseToHyphenSeparatedWords
/**
* Cardinal Direction model with cardinal directions of North/East/South/West, and intercardinal, and secondary
* intercardinal directions.
*
* https://en.wikipedia.org/wiki/Cardinal_direction
*/
enum class CardinalDirectionConcept {
CardinalDirection
}
fun buildGeneralCardinalDirectionLexicon(lexicon: Lexicon) {
buildCardinalDirectionWords(lexicon)
buildInCardinalDirection(lexicon)
}
// Support Rain in Northeast
fun buildInCardinalDirection(lexicon: Lexicon) {
lexicon.addMapping(PrepositionWord(Preposition.In, setOf(CardinalDirectionConcept.CardinalDirection.name)))
}
private fun buildCardinalDirectionWords(lexicon: Lexicon) {
CardinalDirection.values().forEach { cardinalDirection ->
cardinalDirection.lexiconNames().forEach { lexiconName ->
lexicon.addMapping(CardinalDirectionHandler(cardinalDirection, lexiconName))
}
}
}
enum class CardinalFields(override val fieldName: String): Fields {
Degrees("degrees"),
Direction("direction"),
}
private enum class CardinalCategory {
Cardinal,
Intercardinal,
SecondaryIntercardinal
}
enum class CardinalDirection(val degrees: Double, private val initials: String, private val category: CardinalCategory) {
North(0.0, "N", CardinalCategory.Cardinal),
NorthNorthEast(22.5, "NNE", CardinalCategory.SecondaryIntercardinal),
NorthEast(45.0, "NE", CardinalCategory.Intercardinal),
EastNorthEast(67.5, "ENE", CardinalCategory.SecondaryIntercardinal),
East(90.0, "E", CardinalCategory.Cardinal),
EastSouthEast(112.5, "ESE", CardinalCategory.SecondaryIntercardinal),
SouthEast(135.0, "SE", CardinalCategory.Intercardinal),
SouthSouthEast(157.5, "SSE", CardinalCategory.SecondaryIntercardinal),
South(180.0, "S", CardinalCategory.Cardinal),
SouthSouthWest(202.5, "SSW", CardinalCategory.SecondaryIntercardinal),
SouthWest(225.0, "SW", CardinalCategory.Intercardinal),
WestSouthWest(247.5, "WSW", CardinalCategory.SecondaryIntercardinal),
West(270.0, "W", CardinalCategory.Cardinal),
WestNorthWest(292.5, "WNW", CardinalCategory.SecondaryIntercardinal),
NorthWest(315.0, "NW", CardinalCategory.Intercardinal),
NorthNorthWest(337.5, "NNW", CardinalCategory.SecondaryIntercardinal);
fun lexiconNames(): List<String> {
return if (category == CardinalCategory.Cardinal) {
listOf(name)
} else {
listOf(name, initials, transformCamelCaseToHyphenSeparatedWords(name))
}
}
}
class CardinalDirectionHandler(private val cardinalDirection: CardinalDirection, word: String): WordHandler(EntryWord(word)) {
override fun build(wordContext: WordContext): List<Demon> =
lexicalConcept(wordContext, CardinalDirectionConcept.CardinalDirection.name) {
slot(CoreFields.Name, cardinalDirection.name)
slot(CardinalFields.Degrees, cardinalDirection.degrees.toString())
}.demons
}
| 1 | Kotlin | 0 | 0 | b5b7453e2fe0b2ae7b21533db1b2b437b294c63f | 3,850 | barnable | Apache License 2.0 |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Wiper.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.Wiper: ImageVector
get() {
if (_wiper != null) {
return _wiper!!
}
_wiper = Builder(name = "Wiper", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 18.0f)
moveToRelative(-1.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 9.0f)
lineToRelative(5.5f, 5.5f)
arcToRelative(5.0f, 5.0f, 0.0f, false, true, 7.0f, 0.0f)
lineToRelative(5.5f, -5.5f)
arcToRelative(12.0f, 12.0f, 0.0f, false, false, -18.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 18.0f)
lineToRelative(-2.2f, -12.8f)
}
}
.build()
return _wiper!!
}
private var _wiper: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,538 | compose-icon-collections | MIT License |
buildSrc/src/main/kotlin/org.sourcegrade.fopbot.script/FOPBotPublishPlugin.kt | Elynvalur | 563,050,862 | true | {"Gradle Kotlin DSL": 3, "Shell": 1, "EditorConfig": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Java": 15, "JSON": 1, "YAML": 1, "Kotlin": 1, "TOML": 1, "INI": 1} | package org.sourcegrade.fopbot.script
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaBasePlugin
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getByType
import org.gradle.plugins.signing.SigningExtension
import org.gradle.plugins.signing.SigningPlugin
import java.net.URI
class FOPBotPublishPlugin : Plugin<Project> {
override fun apply(target: Project) = target.afterEvaluate { configure() }
private fun Project.configure() {
apply<JavaBasePlugin>()
apply<MavenPublishPlugin>()
apply<SigningPlugin>()
extensions.configure<JavaPluginExtension> {
withJavadocJar()
withSourcesJar()
}
extensions.configure<PublishingExtension> {
repositories {
maven {
credentials {
username = project.findProperty("sonatypeUsername") as? String
password = project.findProperty("sonatypePassword") as? String
}
val releasesRepoUrl = "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/"
val snapshotsRepoUrl = "https://s01.oss.sonatype.org/content/repositories/snapshots"
url = URI(if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl)
}
}
publications {
create<MavenPublication>("maven") {
from(components["java"])
pom {
artifactId = "fopbot"
name.set("FOPBot")
description.set("A small environment with robot agents used for teaching programming basics")
url.set("https://www.sourcegrade.org")
scm {
url.set("https://github.com/FOP-2022/FOPBot")
connection.set("scm:git:https://github.com/FOP-2022/FOPBot.git")
developerConnection.set("scm:git:https://github.com/FOP-2022/FOPBot.git")
}
licenses {
license {
name.set("The MIT License")
url.set("https://opensource.org/licenses/MIT")
distribution.set("repo")
}
}
developers {
developer {
id.set("lr32")
}
developer {
id.set("alexstaeding")
name.set("<NAME>")
}
}
}
}
}
}
extensions.configure<SigningExtension> {
sign(extensions.getByType<PublishingExtension>().publications)
}
}
}
| 0 | Java | 0 | 0 | fc458e818cb95acb70c27ca28f078f9592fd46aa | 2,807 | fopbot | MIT License |
android/src/main/java/com/transfirampreactnativesdk/events/TopMessageEvent.kt | Trans-Fi | 581,432,327 | false | {"JSON with Comments": 1, "JSON": 10, "JavaScript": 9, "Markdown": 3, "Text": 1, "Ignore List": 1, "Git Attributes": 1, "EditorConfig": 1, "YAML": 3, "Ruby": 3, "XML": 10, "INI": 4, "Gradle": 4, "Shell": 2, "Batchfile": 2, "Java": 11, "Kotlin": 8, "Java Properties": 1, "Starlark": 1, "C++": 7, "CMake": 1, "Dotenv": 1, "C": 1, "Swift": 1, "OpenStep Property List": 3, "Objective-C": 9, "Objective-C++": 1} | package com.transfirampreactnativesdk.events
import com.facebook.react.bridge.WritableMap
import com.facebook.react.uimanager.events.Event
import com.facebook.react.uimanager.events.RCTEventEmitter
class TopMessageEvent(viewId: Int, private val mEventData: WritableMap) : Event<TopMessageEvent>(viewId) {
companion object {
const val EVENT_NAME = "topMessage"
}
override fun getEventName(): String = EVENT_NAME
override fun canCoalesce(): Boolean = false
override fun getCoalescingKey(): Short = 0
override fun dispatch(rctEventEmitter: RCTEventEmitter) {
rctEventEmitter.receiveEvent(viewTag, EVENT_NAME, mEventData)
}
}
| 1 | Java | 1 | 0 | c861bfd48eaa32c96173f7855a89f40206744558 | 650 | transfi-ramp-react-native-sdk | MIT License |
domain/src/main/java/com/yapp/buddycon/domain/repository/ChangeCouponRepository.kt | YAPP-Github | 561,172,522 | false | null | package com.yapp.buddycon.domain.repository
import com.yapp.buddycon.domain.model.ChangeCouponResult
import kotlinx.coroutines.flow.Flow
interface ChangeCouponRepository {
fun updateCoupon(
id: Int,
expireDate: String,
isMoneyCoupon: Boolean,
leftMoney: Int,
memo: String,
name: String,
storeName: String
): Flow<ChangeCouponResult>
fun updateCustomCoupon(
id: Int,
name: String,
expireDate: String,
storeName: String,
sentMemberName: String,
memo: String
): Flow<ChangeCouponResult>
fun changeCoupon(
id: Int,
state: String
): Flow<ChangeCouponResult>
fun deleteCoupon(
id: Int
): Flow<ChangeCouponResult>
} | 33 | Kotlin | 0 | 8 | dcd6324f1c313a2af05b328ea21673b096caca51 | 773 | 21st-Android-Team-1-Android | Apache License 2.0 |
card-monopoly/src/main/java/com/kotlin/android/card/monopoly/provider/CardMonopolyProviderExt.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.card.monopoly.provider
import android.app.Activity
import android.view.View
import com.kotlin.android.app.data.annotation.CARD_MONOPOLY_UNKNOWN
import com.kotlin.android.app.data.entity.monopoly.UserInfo
import com.kotlin.android.ktx.ext.core.getActivity
import com.kotlin.android.app.router.path.RouterProviderPath
import com.kotlin.android.app.router.provider.card_monopoly.ICardMonopolyProvider
import com.kotlin.android.router.ext.getProvider
/**
*
* Created on 2020/11/18.
*
* @author o.s
*/
fun View?.startCardMainActivity(userInfo: UserInfo?, tab: Int = CARD_MONOPOLY_UNKNOWN) {
this?.apply {
getProvider(ICardMonopolyProvider::class.java)?.apply {
getActivity()?.apply {
startCardMainActivity(
context = this,
userId = userInfo?.userId,
tab = tab
)
}
}
}
}
fun Activity?.startCardMainActivity(userInfo: UserInfo?, tab: Int = CARD_MONOPOLY_UNKNOWN) {
this?.apply {
getProvider(ICardMonopolyProvider::class.java)?.apply {
startCardMainActivity(
context = this@startCardMainActivity,
userId = userInfo?.userId,
tab = tab
)
}
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 1,330 | Mtime | Apache License 2.0 |
LearnBook/PhotoGallery/src/main/java/com/by5388/learn/v4/kotlin/photogallery/QueryPreferences.kt | sby5388 | 373,231,323 | false | null | package com.by5388.learn.v4.kotlin.photogallery
import android.content.Context
import android.preference.PreferenceManager
import androidx.core.content.edit
private const val PREF_SEARCH_QUERY = "searchQuery"
private const val PREF_LAST_RESULT_ID = "lastResultId"
private const val PREF_IS_POLLING = "isPolling"
private const val PREF_IS_CHROME_TAB = "useChromeCustomTab"
/**
* 保存最近一次搜索的关键字
* object:单例模式
*/
object QueryPreferences {
fun getStoredQuery(context: Context): String {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getString(PREF_SEARCH_QUERY, "")!!
}
fun setStoredQuery(context: Context, query: String) {
PreferenceManager.getDefaultSharedPreferences(context)
//TODO 26.5 use android KTX
// 扩展函数edit :会自动调用apply();使用 edit(true){}则会调用 commit()
.edit {
putString(PREF_SEARCH_QUERY, query)
}
}
fun getLastResultId(context: Context): String {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getString(PREF_LAST_RESULT_ID, "")!!
}
fun setLastResultId(context: Context, lastResultId: String) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit {
putString(PREF_LAST_RESULT_ID, lastResultId)
}
}
fun isPolling(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getBoolean(PREF_IS_POLLING, false)
}
fun setPolling(context: Context, isOn: Boolean) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit {
putBoolean(PREF_IS_POLLING, isOn)
}
}
fun isUseChromeCustomTab(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getBoolean(PREF_IS_CHROME_TAB, false)
}
fun setUseChromeCustomTab(context: Context, isOn: Boolean) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit {
putBoolean(PREF_IS_CHROME_TAB, isOn)
}
}
} | 0 | Kotlin | 3 | 8 | b0fc2c08e17e5333a50e4d57e1d47634e4db562c | 2,188 | AndroidBianChengQuanWeiZhiNanV4-kotlin | Apache License 2.0 |
demo/src/main/java/io/ecosed/plugin_example/FWDemo.kt | ecosed | 675,794,358 | false | null | package io.ecosed.plugin_example
import android.widget.Toast
import io.ecosed.plugin.EcosedExtension
import io.ecosed.plugin.PluginBinding
import io.ecosed.plugin.PluginChannel
class FWDemo : EcosedExtension {
private lateinit var pluginChannel: PluginChannel
override fun onEcosedAdded(binding: PluginBinding) {
pluginChannel = PluginChannel(binding, channel)
pluginChannel.setMethodCallHandler(this)
}
override fun onEcosedRemoved(binding: PluginBinding) {
pluginChannel.setMethodCallHandler(null)
}
override val getPluginChannel: PluginChannel
get() = pluginChannel
override fun onEcosedMethodCall(call: PluginChannel.MethodCall, result: PluginChannel.Result) {
when (call.method){
"" -> result.success("")
else -> result.notImplemented()
}
}
companion object {
const val channel: String = "FWDemo"
}
} | 0 | Kotlin | 0 | 1 | 2e9b84990d87dc6f46715607e04c71f7a0674f5d | 933 | plugin | Apache License 2.0 |
stream-chat-android-compose/src/main/java/io/getstream/chat/android/compose/ui/components/messages/GiphyMessageContent.kt | GetStream | 177,873,527 | false | {"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229} | /*
* Copyright (c) 2014-2022 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getstream.chat.android.compose.ui.components.messages
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
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.getstream.chat.android.compose.R
import io.getstream.chat.android.compose.ui.attachments.content.MessageAttachmentsContent
import io.getstream.chat.android.compose.ui.theme.ChatTheme
import io.getstream.chat.android.models.Message
import io.getstream.chat.android.previewdata.PreviewMessageData
import io.getstream.chat.android.ui.common.state.messages.list.CancelGiphy
import io.getstream.chat.android.ui.common.state.messages.list.GiphyAction
import io.getstream.chat.android.ui.common.state.messages.list.SendGiphy
import io.getstream.chat.android.ui.common.state.messages.list.ShuffleGiphy
/**
* Represents the content of an ephemeral giphy message.
*
* @param message The ephemeral giphy message.
* @param modifier Modifier for styling.
* @param onGiphyActionClick Handler when the user clicks on action button.
*/
@Composable
public fun GiphyMessageContent(
message: Message,
modifier: Modifier = Modifier,
onGiphyActionClick: (GiphyAction) -> Unit = {},
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Image(
modifier = Modifier.size(24.dp),
painter = painterResource(id = R.drawable.stream_compose_ic_giphy),
contentDescription = null,
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = stringResource(id = R.string.stream_compose_message_list_giphy_title),
style = ChatTheme.typography.bodyBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = ChatTheme.colors.textHighEmphasis,
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = message.text,
style = ChatTheme.typography.body,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = ChatTheme.colors.textLowEmphasis,
)
}
MessageAttachmentsContent(
message = message,
onLongItemClick = {},
onMediaGalleryPreviewResult = {},
)
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(1.dp)
.background(color = ChatTheme.colors.borders),
)
Row(
modifier = Modifier
.height(48.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
GiphyButton(
modifier = Modifier
.fillMaxHeight()
.weight(1f),
text = stringResource(id = R.string.stream_compose_message_list_giphy_cancel),
textColor = ChatTheme.colors.textLowEmphasis,
onClick = { onGiphyActionClick(CancelGiphy(message)) },
)
Spacer(
modifier = Modifier
.fillMaxHeight()
.width(1.dp)
.background(color = ChatTheme.colors.borders),
)
GiphyButton(
modifier = Modifier
.fillMaxHeight()
.weight(1f),
text = stringResource(id = R.string.stream_compose_message_list_giphy_shuffle),
textColor = ChatTheme.colors.textLowEmphasis,
onClick = { onGiphyActionClick(ShuffleGiphy(message)) },
)
Spacer(
modifier = Modifier
.fillMaxHeight()
.width(1.dp)
.background(color = ChatTheme.colors.borders),
)
GiphyButton(
modifier = Modifier
.fillMaxHeight()
.weight(1f),
text = stringResource(id = R.string.stream_compose_message_list_giphy_send),
textColor = ChatTheme.colors.primaryAccent,
onClick = { onGiphyActionClick(SendGiphy(message)) },
)
}
}
}
/**
* Represents an action button in the ephemeral giphy message.
*
* @param text The text displayed on the button.
* @param textColor The color applied to the text.
* @param onClick Handler when the user clicks on action button.
* @param modifier Modifier for styling.
*/
@Composable
internal fun GiphyButton(
text: String,
textColor: Color,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Box(
modifier = modifier
.clickable(
onClick = onClick,
indication = rememberRipple(),
interactionSource = remember { MutableInteractionSource() },
),
) {
Text(
modifier = Modifier.align(Alignment.Center),
text = text,
style = ChatTheme.typography.bodyBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = textColor,
textAlign = TextAlign.Center,
)
}
}
@Preview
@Composable
private fun GiphyMessageContentPreview() {
ChatTheme {
GiphyMessageContent(
modifier = Modifier.size(600.dp),
message = PreviewMessageData.message1,
onGiphyActionClick = {},
)
}
}
| 37 | Kotlin | 273 | 1,451 | 8e46f46a68810d8086c48a88f0fff29faa2629eb | 7,506 | stream-chat-android | FSF All Permissive License |
app/src/main/java/com/diegoalvis/dualcalculator/MainActivity.kt | diegoalvis | 781,627,761 | false | {"Kotlin": 18784} | package com.diegoalvis.dualcalculator
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.commit
import com.diegoalvis.dualcalculator.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var _binding: ActivityMainBinding
private val viewModel: MainViewModel by viewModels { MainViewModel.Factory }
companion object {
const val FIRST_FRAGMENT_POS = 0
const val SECOND_FRAGMENT_POS = 1
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
enableEdgeToEdge()
_binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(_binding.root)
val isLandscape = _binding.fragmentContainerB != null // other way: use Configuration.ORIENTATION_LANDSCAPE
viewModel.updateConfig(isLandscape)
supportFragmentManager.commit {
replace(R.id.fragment_container, CalculatorFragment.newInstance(FIRST_FRAGMENT_POS), "$FIRST_FRAGMENT_POS")
if (isLandscape) {
replace(R.id.fragment_container_b, CalculatorFragment.newInstance(SECOND_FRAGMENT_POS), "$SECOND_FRAGMENT_POS")
}
setReorderingAllowed(true)
}
_binding.switchLeft?.setOnClickListener {
viewModel.onEvent(UiEvents.SendToNextScreen(direction = CommandDirection.LEFT))
}
_binding.switchRight?.setOnClickListener {
viewModel.onEvent(UiEvents.SendToNextScreen(direction = CommandDirection.RIGHT))
}
}
} | 0 | Kotlin | 0 | 0 | 30ae83a76be9f93ab802e5ab5e44803186966094 | 1,807 | Dual-Calculator | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/calculatereleasedatesapi/repository/ComparisonRepository.kt | ministryofjustice | 387,841,000 | false | {"Kotlin": 1601679, "Shell": 7185, "Dockerfile": 1379} | package uk.gov.justice.digital.hmpps.calculatereleasedatesapi.repository
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.entity.Comparison
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.enumerations.ComparisonType
@Repository
interface ComparisonRepository : JpaRepository<Comparison, Long> {
fun findAllByComparisonTypeIsIn(types: Collection<ComparisonType>): List<Comparison>
fun findAllByComparisonTypeIsInAndPrisonIsIn(types: Collection<ComparisonType>, includedPrisons: List<String>): List<Comparison>
fun findByComparisonShortReference(shortReference: String): Comparison?
}
| 4 | Kotlin | 0 | 5 | 7bb046c5f311455df7beb626f5c1f9751a805502 | 729 | calculate-release-dates-api | MIT License |
src/main/kotlin/MainForm.kt | masanori840816 | 63,615,062 | false | null | /**
* Created by masanori on 2016/07/16.
*/
import javafx.application.Application
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.ComboBox
import javafx.scene.control.TextField
import javafx.scene.layout.StackPane
import javafx.stage.FileChooser
import javafx.stage.Stage
import java.io.File
import java.io.IOException
class MainForm : Application(){
lateinit private var spreadsheetAccesser: SpreadsheetAccesser
lateinit private var jsonFileCreator: JsonFileCreater
lateinit private var loadFilePathField: TextField
lateinit private var sheetNameCombobox: ComboBox<String>
lateinit private var createButton: Button
private var sheetNameList: ObservableList<String>? = null
private var selectedFile: File? = null
@Throws(IOException::class)
override fun start(primaryStage: Stage) {
spreadsheetAccesser = SpreadsheetAccesser()
jsonFileCreator = JsonFileCreater()
val findFileButton = Button()
findFileButton.text = "参照"
findFileButton.translateX = 250.0
findFileButton.translateY = -150.0
findFileButton.setOnAction { event -> run {
val fileChooser = FileChooser()
fileChooser.title = "ファイルを選択"
fileChooser.extensionFilters.add(FileChooser.ExtensionFilter("Spreadsheet", "*.xlsx", "*.ods"))
selectedFile = fileChooser.showOpenDialog(primaryStage)
loadFilePathField.text = selectedFile.toString()
setSheetNames()
}
}
loadFilePathField = TextField()
loadFilePathField.translateX = -35.0
loadFilePathField.translateY = -150.0
loadFilePathField.scaleX = 0.8
loadFilePathField.setOnAction { event -> run{
setSheetNames()
} }
sheetNameList = sheetNameList?: FXCollections.observableArrayList("")
sheetNameCombobox = ComboBox()
sheetNameCombobox.translateX = -200.0
sheetNameCombobox.translateY = -70.0
sheetNameCombobox.prefWidth = 160.0
if(sheetNameList != null){
sheetNameCombobox.items = sheetNameList
}
createButton = Button()
createButton.text = "作成"
createButton.translateX = 230.0
createButton.translateY = 150.0
createButton.setOnAction { event -> run{
if(! loadFilePathField.text.isNullOrEmpty()
&& ! sheetNameCombobox.selectionModel.selectedItem.isNullOrEmpty()
&& ! selectedFile?.name.isNullOrEmpty()) {
spreadsheetAccesser.loadFile(loadFilePathField.text, sheetNameCombobox.selectionModel.selectedItem)
jsonFileCreator.createFile(spreadsheetAccesser.ToiletInfoList, selectedFile!!.name)
}
} }
val stackPane = StackPane()
stackPane.children.addAll(findFileButton
, loadFilePathField
, sheetNameCombobox
, createButton)
val primaryScene = Scene(stackPane, 600.0, 400.0)
primaryStage.setScene(primaryScene)
primaryStage.show()
}
private fun setSheetNames(){
if(!loadFilePathField.text.isNullOrEmpty()){
sheetNameCombobox.items = null
val gotItems = spreadsheetAccesser.getSheetNames(loadFilePathField.text)
if(gotItems != null
&& gotItems.size > 0){
sheetNameCombobox.items = gotItems
sheetNameCombobox.selectionModel.select(0)
}
}
}
} | 0 | Kotlin | 0 | 1 | 88dfff71e98342a4d858ffdc899117488c078850 | 3,670 | KtCreateJson | Apache License 2.0 |
modules/economy/src/main/kotlin/ru/astrainteractive/aspekt/module/economy/database/dao/impl/EconomyDaoImpl.kt | Astra-Interactive | 588,890,842 | false | {"Kotlin": 317987} | package ru.astrainteractive.aspekt.module.economy.database.dao.impl
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.JoinType
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.SortOrder
import org.jetbrains.exposed.sql.SqlExpressionBuilder.inList
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.andWhere
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.update
import ru.astrainteractive.aspekt.module.economy.database.dao.EconomyDao
import ru.astrainteractive.aspekt.module.economy.database.table.CurrencyTable
import ru.astrainteractive.aspekt.module.economy.database.table.PlayerCurrencyTable
import ru.astrainteractive.aspekt.module.economy.model.CurrencyModel
import ru.astrainteractive.aspekt.module.economy.model.PlayerCurrency
import ru.astrainteractive.aspekt.module.economy.model.PlayerModel
import ru.astrainteractive.astralibs.logging.JUtiltLogger
import ru.astrainteractive.astralibs.logging.Logger
@Suppress("TooManyFunctions")
internal class EconomyDaoImpl(
private val databaseFlow: Flow<Database>
) : EconomyDao,
Logger by JUtiltLogger("EconomyDao") {
private val mutex = Mutex()
private suspend fun <T> withMutex(block: suspend () -> T): T {
return mutex.withLock { block.invoke() }
}
private suspend fun currentDatabase(): Database {
return databaseFlow.first()
}
private fun ResultRow.toCurrency() = CurrencyModel(
id = this[CurrencyTable.id].value,
name = this[CurrencyTable.name],
priority = this[CurrencyTable.priority],
)
private fun ResultRow.toPlayerCurrency() = PlayerCurrency(
playerModel = PlayerModel(
name = this[PlayerCurrencyTable.lastUsername],
uuid = this[PlayerCurrencyTable.uuid],
),
balance = this[PlayerCurrencyTable.amount],
currencyModel = CurrencyModel(
id = this[CurrencyTable.id].value,
name = this[CurrencyTable.name],
priority = this[CurrencyTable.priority],
)
)
override suspend fun getAllCurrencies(): List<CurrencyModel> {
return newSuspendedTransaction(db = currentDatabase()) {
CurrencyTable.selectAll()
.map { it.toCurrency() }
}
}
override suspend fun updateCurrencies(currencies: List<CurrencyModel>) = withMutex {
val existingCurrencies = getAllCurrencies()
val nonExistingCurrencies = existingCurrencies
.map(CurrencyModel::id)
.toSet()
.minus(currencies.map(CurrencyModel::id).toSet())
if (currencies.isEmpty()) {
error { "#updateCurrencies you didn't setup any currencies! Economy may break!" }
}
if (nonExistingCurrencies.isNotEmpty()) {
newSuspendedTransaction(db = currentDatabase()) {
CurrencyTable.deleteWhere { CurrencyTable.id inList nonExistingCurrencies }
PlayerCurrencyTable.deleteWhere { PlayerCurrencyTable.currencyId inList nonExistingCurrencies }
}
}
newSuspendedTransaction(db = currentDatabase()) {
currencies.forEach { currency ->
if (existingCurrencies.find { currency.id == it.id } != null) {
CurrencyTable.update(where = { CurrencyTable.id eq currency.id }) {
it[CurrencyTable.name] = currency.name
it[CurrencyTable.priority] = currency.priority
}
} else {
CurrencyTable.insert {
it[CurrencyTable.id] = currency.id
it[CurrencyTable.name] = currency.name
it[CurrencyTable.priority] = currency.priority
}
}
}
}
}
override suspend fun findCurrency(id: String): CurrencyModel? {
return newSuspendedTransaction(db = currentDatabase()) {
CurrencyTable.selectAll()
.where { CurrencyTable.id eq id }
.map { it.toCurrency() }
.firstOrNull()
}
}
override suspend fun findPlayerCurrency(playerUuid: String, currencyId: String): PlayerCurrency? {
return newSuspendedTransaction(db = currentDatabase()) {
CurrencyTable.join(
otherTable = PlayerCurrencyTable,
joinType = JoinType.LEFT,
onColumn = CurrencyTable.id,
otherColumn = PlayerCurrencyTable.currencyId
)
.selectAll()
.where { PlayerCurrencyTable.uuid eq playerUuid }
.andWhere { PlayerCurrencyTable.currencyId eq currencyId }
.map { it.toPlayerCurrency() }
.firstOrNull()
}
}
override suspend fun playerCurrencies(playerUuid: String): List<PlayerCurrency> {
return newSuspendedTransaction(db = currentDatabase()) {
CurrencyTable.join(
otherTable = PlayerCurrencyTable,
joinType = JoinType.LEFT,
onColumn = CurrencyTable.id,
otherColumn = PlayerCurrencyTable.currencyId
)
.selectAll()
.where { PlayerCurrencyTable.uuid eq playerUuid }
.map { it.toPlayerCurrency() }
}
}
override suspend fun topCurrency(id: String, page: Int, size: Int): List<PlayerCurrency> {
return newSuspendedTransaction(db = currentDatabase()) {
CurrencyTable.join(
otherTable = PlayerCurrencyTable,
joinType = JoinType.INNER,
onColumn = CurrencyTable.id,
otherColumn = PlayerCurrencyTable.currencyId
)
.selectAll()
.orderBy(PlayerCurrencyTable.amount to SortOrder.DESC)
.where { CurrencyTable.id eq id }
.limit(n = size, offset = (page * size).toLong())
.map { it.toPlayerCurrency() }
}
}
private suspend fun updatePlayerCurrencyWithoutTransaction(currency: PlayerCurrency) {
val isPlayerCurrencyExists = PlayerCurrencyTable.selectAll()
.where { PlayerCurrencyTable.currencyId eq currency.currencyModel.id }
.andWhere { PlayerCurrencyTable.uuid eq currency.playerModel.uuid }
.firstOrNull()
if (isPlayerCurrencyExists == null) {
PlayerCurrencyTable.insert {
it[PlayerCurrencyTable.amount] = currency.balance
it[PlayerCurrencyTable.lastUsername] = currency.playerModel.name
it[PlayerCurrencyTable.uuid] = currency.playerModel.uuid
it[PlayerCurrencyTable.currencyId] = currency.currencyModel.id
}
} else {
PlayerCurrencyTable.update(
where = {
PlayerCurrencyTable.currencyId.eq(currency.currencyModel.id).and {
PlayerCurrencyTable.uuid.eq(currency.playerModel.uuid)
}
},
body = {
it[PlayerCurrencyTable.amount] = currency.balance
it[PlayerCurrencyTable.lastUsername] = currency.playerModel.name
}
)
}
}
override suspend fun transfer(
from: PlayerModel,
to: PlayerModel,
amount: Double,
currencyId: String
): Boolean = withMutex {
newSuspendedTransaction(db = currentDatabase()) {
val fromPlayerCurrency =
findPlayerCurrency(from.uuid, currencyId) ?: return@newSuspendedTransaction false
if (fromPlayerCurrency.balance - amount < 0) return@newSuspendedTransaction false
val toPlayerCurrency = PlayerCurrency(
playerModel = PlayerModel(
name = to.name,
uuid = to.uuid,
),
balance = amount,
currencyModel = fromPlayerCurrency.currencyModel
)
updatePlayerCurrencyWithoutTransaction(
fromPlayerCurrency.copy(balance = fromPlayerCurrency.balance - amount)
)
updatePlayerCurrencyWithoutTransaction(toPlayerCurrency)
true
}
}
override suspend fun updatePlayerCurrency(currency: PlayerCurrency) = withMutex {
newSuspendedTransaction(db = currentDatabase()) {
updatePlayerCurrencyWithoutTransaction(currency)
}
}
}
| 2 | Kotlin | 0 | 0 | 2c7339a88a7438a75d7f304cdeda811130aa9c6c | 8,926 | AspeKt | MIT License |
Library/src/main/java/com/xfhy/library/service/InitIntentService.kt | xfhy | 258,978,567 | false | null | package com.xfhy.library.service
import android.app.IntentService
import android.content.Intent
import com.xfhy.library.data.net.OkHttpUtils
/**
* 2018年10月29日15:13:21
* @author xfhy
* 初始化一些第三方库
*
* 在Application中start
*/
class InitIntentService : IntentService("InitIntentService") {
override fun onHandleIntent(intent: Intent?) {
OkHttpUtils.initOkHttp(applicationContext)
//ARouter
/*if (BuildConfig.DEBUG) { // 这两行必须写在init之前,否则这些配置在init过程中将无效
ARouter.openLog() // 打印日志
ARouter.openDebug() // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
}
ARouter.init(application) // 尽可能早,推荐在Application中初始化*/
}
}
| 1 | Kotlin | 5 | 6 | 294cd16f0549f97d13304d659e76c776189e44ff | 699 | AllInOne | Apache License 2.0 |
shared/src/commonMain/kotlin/ui/compose/Main/MainDrawer.kt | west2-online | 840,273,230 | false | {"Kotlin": 742964, "Swift": 592, "Shell": 228} | package ui.compose.Main
import androidVersion.AndroidVersion
import androidVersion.Version
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.liftric.kvault.KVault
import config.CurrentZone
import dev.icerock.moko.resources.compose.painterResource
import dev.icerock.moko.resources.compose.stringResource
import di.SystemAction
import getVersionFileName
import io.kamel.image.KamelImage
import io.kamel.image.asyncPainterResource
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import kotlinx.datetime.Clock
import kotlinx.datetime.toLocalDateTime
import kotlinx.serialization.json.Json
import org.example.library.MR
import org.koin.compose.koinInject
import ui.root.getRootAction
/**
* 获取今年过去的比例
*
* @return Float
*/
fun getPassedRange(): Float {
// 获取当前日期
val currentDate = Clock.System.now().toLocalDateTime(CurrentZone).date.dayOfYear
// 获取今年总天数
val daysInYear = 365 // 注意:这里假设每年都是 365 天
// 计算已经过去的天数比例
return (currentDate.toFloat() / daysInYear)
}
/**
* 侧边栏
*
* @param modifier Modifier
*/
@Composable
fun MainDrawer(modifier: Modifier = Modifier) {
LazyColumn(modifier = modifier, verticalArrangement = Arrangement.spacedBy(10.dp)) {
item {
val angle = Animatable(270f)
LaunchedEffect(Unit) { angle.animateTo(getPassedRange() * 360f * (-1.0f)) }
Row(
modifier =
Modifier.statusBarsPadding()
.fillMaxWidth()
.height(100.dp)
.clip(RoundedCornerShape(10.dp))
.background(MaterialTheme.colors.primary)
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Canvas(
modifier = Modifier.fillMaxHeight().aspectRatio(1f).clip(RoundedCornerShape(10.dp))
) {
drawArc(
brush = Brush.linearGradient(colors = listOf(Color.Green, Color.Blue, Color.Red)),
startAngle = 270f,
sweepAngle = angle.value,
useCenter = false,
size = Size(size.height - size.height / 3, size.height - size.height / 3),
style = Stroke(30f, cap = StrokeCap.Round),
topLeft = Offset(size.height / 6, size.height / 6),
)
}
Text("今年已过 ${(getPassedRange()*100).toInt()}%,继续加油!\uD83E\uDD17")
}
}
item {
val client = koinInject<HttpClient>()
val latest = remember { mutableStateOf<Version?>(null) }
LaunchedEffect(Unit) {
try {
val result = client.get("/static/config/${getVersionFileName()}").bodyAsText()
val data: AndroidVersion = Json.decodeFromString(result)
latest.value =
data.version
.filter { it.canUse }
.filter { it.version.split("-")[1] == "Release" }
.sortedBy {
val list = it.version.split("-")[0].split(".")
return@sortedBy list[0].toInt() * 100 + list[1].toInt() * 10 + list[2].toInt() * 1
}
.lastOrNull()
} catch (e: Exception) {
println(e.message.toString())
}
}
Column(
modifier =
Modifier.fillMaxWidth()
.wrapContentHeight()
.clip(RoundedCornerShape(10.dp))
.background(MaterialTheme.colors.primary)
.padding(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Text("当前版本:" + stringResource(MR.strings.version))
Divider(modifier = Modifier.fillMaxWidth().height(1.dp))
latest.value?.let { Text("最新版本:" + latest.value?.version) }
}
}
item {
Functions(
modifier = Modifier.wrapContentHeight().fillMaxWidth().clip(RoundedCornerShape(10.dp))
)
}
}
}
@Composable
fun PersonalInformation(modifier: Modifier = Modifier) {
Column(modifier = modifier) {
KamelImage(
resource =
asyncPainterResource("https://pic1.zhimg.com/v2-fddbd21f1206bcf7817ddec207ad2340_b.jpg"),
null,
modifier = Modifier.height(50.dp).aspectRatio(1f).clip(CircleShape),
contentScale = ContentScale.FillBounds,
)
Text(
text = "theonenull",
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 10.dp),
)
Text(text = "[email protected]", fontSize = 10.sp)
}
}
/**
* 侧边栏的功能集合
*
* @param modifier Modifier
* @param kVault KVault
*/
@Composable
fun Functions(modifier: Modifier = Modifier, kVault: KVault = koinInject()) {
val rootAction = getRootAction()
Column(modifier = modifier) {
Divider(modifier = Modifier.fillMaxWidth().padding(10.dp))
FunctionsItem(
painterResource(MR.images.feedback),
{ rootAction.navigateFromActionToFeedback() },
"反馈",
)
FunctionsItem(
painterResource(MR.images.qrcode),
{ rootAction.navigateFromActionToQRCodeScreen() },
"二维码生成",
)
// FunctionsItem(
// painterResource(MR.images.eye),
// {
// rootAction.navigateToNewTarget(rootTarget = RootTarget.Person(null))
// },
// "个人资料"
// )
// FunctionsItem(
// painterResource(MR.images.eye),
// {
//// routeState.navigateWithoutPop(Route.Test())
// rootAction.navigateToNewTarget(rootTarget = RootTarget.Person(null))
// },
// "测试"
// )
val systemAction = koinInject<SystemAction>()
FunctionsItem(Icons.Filled.ExitToApp, { systemAction.onFinish.invoke() }, "退出程序")
FunctionsItem(
painterResource(MR.images.loginOut),
onclick = {
kVault.clear()
rootAction.reLogin()
},
"退出登录",
modifier =
Modifier.padding(bottom = 10.dp)
.height(50.dp)
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.background(Color(231, 64, 50))
.padding(start = 10.dp),
)
}
}
/**
* 侧边栏的item显示 用painter 为icon
*
* @param painter Painter
* @param onclick Function0<Unit>
* @param text String
* @param modifier Modifier
*/
@Composable
fun FunctionsItem(
painter: Painter,
onclick: () -> Unit = {},
text: String,
modifier: Modifier =
Modifier.padding(bottom = 10.dp)
.height(50.dp)
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.clickable { onclick.invoke() }
.padding(start = 10.dp),
) {
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
Icon(painter = painter, "", modifier = Modifier.fillMaxHeight(0.4f).aspectRatio(1f))
Text(
text,
modifier = Modifier.weight(1f).padding(horizontal = 10.dp),
fontWeight = FontWeight.Bold,
maxLines = 1,
softWrap = false,
)
}
}
/**
* 侧边栏的item显示 imageVector 为icon
*
* @param imageVector Painter
* @param onclick Function0<Unit>
* @param text String
* @param modifier Modifier
*/
@Composable
fun FunctionsItem(
imageVector: ImageVector,
onclick: () -> Unit = {},
text: String,
modifier: Modifier =
Modifier.padding(bottom = 10.dp)
.height(50.dp)
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.clickable { onclick.invoke() }
.padding(start = 10.dp),
) {
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
Icon(imageVector = imageVector, "", modifier = Modifier.fillMaxHeight(0.4f).aspectRatio(1f))
Text(
text,
modifier = Modifier.weight(1f).padding(horizontal = 10.dp),
fontWeight = FontWeight.Bold,
maxLines = 1,
softWrap = false,
)
}
}
| 6 | Kotlin | 2 | 0 | 484b699b372e6ff5c43ae725372b28c6de4eaa73 | 9,596 | fzuhelper-KMP | Apache License 2.0 |
app/src/main/java/ar/edu/unlam/mobile/scaffold/ui/screens/heroduel/HeroDuelScreen.kt | unlam-tec-movil | 691,293,842 | false | {"Kotlin": 348767} | package ar.edu.unlam.mobile.scaffold.ui.screens.heroduel
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
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.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import ar.edu.unlam.mobile.scaffold.R
import ar.edu.unlam.mobile.scaffold.domain.cardgame.Stat
import ar.edu.unlam.mobile.scaffold.domain.cardgame.Winner
import ar.edu.unlam.mobile.scaffold.domain.model.HeroModel
import ar.edu.unlam.mobile.scaffold.ui.components.ActionMenu
import ar.edu.unlam.mobile.scaffold.ui.components.AnimatedHeroCard
import ar.edu.unlam.mobile.scaffold.ui.components.CustomButton
import ar.edu.unlam.mobile.scaffold.ui.components.CustomTitle
import ar.edu.unlam.mobile.scaffold.ui.components.GameScore
import ar.edu.unlam.mobile.scaffold.ui.components.PlayerDeck
import ar.edu.unlam.mobile.scaffold.ui.components.hero.adversaryCardColor
@Preview(showBackground = true)
@Composable
fun FinishedDuelUi(
modifier: Modifier = Modifier,
winner: Winner = Winner.PLAYER,
playerScore: Int = 0,
adversaryScore: Int = 0,
onPlayerWinner: () -> Unit = { }
) {
Box(
modifier = modifier.clickable {
if (winner == Winner.PLAYER) {
onPlayerWinner()
}
}
) {
Image(
painter = painterResource(id = R.drawable.fondo_pantalla_pelea),
contentDescription = "FinishedDuelUi background",
contentScale = ContentScale.FillBounds,
modifier = Modifier.fillMaxSize()
)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
modifier = Modifier
.padding(16.dp)
.testTag("FinishedDuelUi result text"),
text = { "El ganador es " + if (winner == Winner.PLAYER) "el jugador!" else "el adversario." }
)
GameScore(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
.testTag("FinishedDuelUi final score"),
playerScore = playerScore,
adversaryScore = adversaryScore
)
}
}
}
@Composable
fun HeroDuelScreen(
modifier: Modifier = Modifier,
viewModel: HeroDuelViewModelv2 = hiltViewModel()
) {
val isLoading by viewModel.isLoading.collectAsStateWithLifecycle()
if (isLoading) {
Box(modifier = modifier) {
Image(
painter = painterResource(id = R.drawable.fondo_pantalla_pelea),
contentDescription = "Fondo loading",
contentScale = ContentScale.FillBounds,
modifier = Modifier.fillMaxSize()
)
CircularProgressIndicator(modifier = Modifier.fillMaxSize())
}
} else {
val playerDeck by viewModel.currentPlayerDeck.collectAsStateWithLifecycle()
val onPlayCardClick = viewModel::playCard
val onPlayerCardClick = viewModel::selectPlayerCard
val currentPlayerCard by viewModel.currentPlayerCard.collectAsStateWithLifecycle()
val currentAdversaryCard by viewModel.currentAdversaryCard.collectAsStateWithLifecycle()
val playerScore by viewModel.playerScore.collectAsStateWithLifecycle()
val adversaryScore by viewModel.adversaryScore.collectAsStateWithLifecycle()
val onClickSelectedStat = viewModel::selectStat
val useMultiplierX2 = viewModel::useMultiplierX2
val onFightClick = viewModel::fight
val winner by viewModel.winner.collectAsStateWithLifecycle()
val canMultix2BeUsed by viewModel.isMultiplierAvailable.collectAsStateWithLifecycle()
val currentScreen by viewModel.currentScreen.collectAsStateWithLifecycle()
val wonHero by viewModel.wonHero.collectAsStateWithLifecycle()
val checkIfPlayerWonHero = viewModel::checkIfPlayerWonHero
val animationDuration = 500
AnimatedContent(
targetState = currentScreen,
label = "",
transitionSpec = {
if (targetState == DuelScreen.SELECT_CARD_UI) {
slideInHorizontally(
animationSpec = tween(
durationMillis = animationDuration
),
initialOffsetX = { fullWidth -> -fullWidth }
) togetherWith (
slideOutHorizontally(
animationSpec = tween(
durationMillis = animationDuration
),
targetOffsetX = { fullWidth -> fullWidth }
)
)
} else {
slideInHorizontally(
animationSpec = tween(
durationMillis = animationDuration
),
initialOffsetX = { fullWidth -> fullWidth }
) togetherWith (
slideOutHorizontally(
animationSpec = tween(
durationMillis = animationDuration
),
targetOffsetX = { fullWidth -> -fullWidth }
)
)
}
}
) { screen ->
when (screen) {
DuelScreen.DUEL_UI -> DuelUi(
modifier = modifier,
currentPlayerCard = currentPlayerCard,
currentAdversaryCard = currentAdversaryCard,
playerScore = playerScore,
adversaryScore = adversaryScore,
onClickSelectedStat = onClickSelectedStat,
useMultiplier = useMultiplierX2,
onFightClick = onFightClick,
canMultix2BeUsed = canMultix2BeUsed
)
DuelScreen.SELECT_CARD_UI -> SelectCardUi(
modifier = modifier,
playerDeck = playerDeck,
onPlayCardClick = onPlayCardClick,
onPlayerCardClick = onPlayerCardClick
)
DuelScreen.FINISHED_DUEL_UI -> FinishedDuelUi(
modifier = modifier,
winner = winner,
playerScore = playerScore,
adversaryScore = adversaryScore,
onPlayerWinner = checkIfPlayerWonHero
)
DuelScreen.WIN_CARD_UI -> WinCardUi(modifier = modifier, hero = wonHero)
}
}
}
}
@Preview
@Composable
fun WinCardUi(
modifier: Modifier = Modifier,
hero: HeroModel = HeroModel()
) {
Box(modifier = modifier) {
Image(
painter = painterResource(id = R.drawable.fondo_coleccion),
contentDescription = "WinCardUi background",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds
)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(space = 25.dp, alignment = Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = { "Ganaste la siguiente carta!" }
)
AnimatedHeroCard(
hero = hero
)
}
}
}
@Preview(showBackground = true)
@Composable
fun DuelUi(
modifier: Modifier = Modifier,
currentPlayerCard: HeroModel = HeroModel(),
currentAdversaryCard: HeroModel = HeroModel(),
playerScore: Int = 0,
adversaryScore: Int = 0,
onClickSelectedStat: (Stat) -> Unit = {},
canMultix2BeUsed: Boolean = true,
useMultiplier: (Boolean) -> Unit = {},
onFightClick: () -> Unit = {}
) {
Box(modifier = modifier) {
Image(
painter = painterResource(id = R.drawable.fondo_pantalla_pelea),
contentDescription = "DuelUi background",
contentScale = ContentScale.FillBounds,
modifier = Modifier.fillMaxSize()
)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceBetween,
horizontalAlignment = Alignment.CenterHorizontally
) {
GameScore(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.testTag("DuelUi game score"),
playerScore = playerScore,
adversaryScore = adversaryScore
)
val cardModifier = Modifier
.padding(7.dp)
AnimatedHeroCard(
modifier = cardModifier.testTag("DuelUi adversary card"),
hero = currentAdversaryCard,
cardColors = adversaryCardColor()
)
ActionMenu(
modifier = Modifier
.fillMaxWidth()
.background(color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f))
.testTag("DuelUi action menu"),
onClickSelectedStat = onClickSelectedStat,
useMultiplier = useMultiplier,
onFightClick = onFightClick,
isMultiplierEnabled = canMultix2BeUsed,
heroStats = currentPlayerCard.stats
)
AnimatedHeroCard(
modifier = cardModifier.testTag("DuelUi player card"),
hero = currentPlayerCard
)
}
}
}
@Preview(showBackground = true)
@Composable
fun SelectCardUi(
modifier: Modifier = Modifier,
playerDeck: List<HeroModel> = listOf(
HeroModel(id = 1, name = "test 1"),
HeroModel(id = 2, name = "test 2")
),
onPlayCardClick: () -> Unit = {},
onPlayerCardClick: (Int) -> Unit = {},
) {
var selectedCard by remember { mutableStateOf(playerDeck[0]) }
Box(modifier = modifier) {
Image(
painter = painterResource(id = R.drawable.fondo_pantalla_pelea),
contentDescription = "SelectCardUi background",
contentScale = ContentScale.FillBounds,
modifier = Modifier.fillMaxSize()
)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(space = 5.dp, alignment = Alignment.Top),
horizontalAlignment = Alignment.CenterHorizontally
) {
AnimatedHeroCard(
modifier = Modifier
.padding(8.dp)
.testTag("SelectCardUi player card"),
hero = selectedCard
)
CustomButton(
modifier = Modifier.testTag("SelectCardUi play card button"),
label = { "Jugar carta!" },
onClick = onPlayCardClick
)
PlayerDeck(
modifier = Modifier
.weight(1f)
.testTag("SelectCardUi player deck"),
playerDeck = playerDeck,
onCardClick = { index ->
selectedCard = playerDeck[index]
onPlayerCardClick(index)
}
)
}
}
}
| 3 | Kotlin | 0 | 0 | 62f24b5a8117891e1656c23a6b6bd6289d54f198 | 12,786 | A3-2023-H2-Cartas-Super | MIT License |
src/main/kotlin/com/piashcse/route/UserProfileRoute.kt | piashcse | 410,331,425 | false | null | package com.piashcse.route
import com.piashcse.controller.userProfileController
import com.piashcse.models.user.body.UserProfileBody
import com.piashcse.plugins.RoleManagement
import com.piashcse.utils.ApiResponse
import com.piashcse.utils.AppConstants
import com.piashcse.utils.extension.apiResponse
import com.piashcse.utils.extension.fileExtension
import com.piashcse.utils.extension.getCurrentUser
import io.github.smiley4.ktorswaggerui.dsl.routing.get
import io.github.smiley4.ktorswaggerui.dsl.routing.post
import io.github.smiley4.ktorswaggerui.dsl.routing.put
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.util.*
fun Route.userProfileRoute(profileController: userProfileController) {
authenticate(RoleManagement.ADMIN.role, RoleManagement.SELLER.role, RoleManagement.CUSTOMER.role) {
route("user") {
get({
tags("User")
apiResponse()
}) {
call.respond(
ApiResponse.success(
profileController.getProfile(getCurrentUser().userId), HttpStatusCode.OK
)
)
}
put({
tags("User")
request {
body<UserProfileBody>()
}
apiResponse()
}) {
val requestBody = call.receive<UserProfileBody>()
call.respond(
ApiResponse.success(
profileController.updateProfile(getCurrentUser().userId, requestBody), HttpStatusCode.OK
)
)
}
post("photo-upload",{
tags("User")
request {
multipartBody {
mediaTypes = setOf(ContentType.MultiPart.FormData)
part<File>("image") {
mediaTypes = setOf(
ContentType.Image.PNG, ContentType.Image.JPEG, ContentType.Image.SVG
)
}
}
}
apiResponse()
}) {
val multipartData = call.receiveMultipart()
multipartData.forEachPart { part ->
when (part) {
is PartData.FormItem -> {
val fileDescription = part.value
}
is PartData.FileItem -> {
UUID.randomUUID()?.let { imageId ->
val fileName = part.originalFileName as String
val fileLocation = fileName.let {
"${AppConstants.ImageFolder.PROFILE_IMAGE_LOCATION}$imageId${it.fileExtension()}"
}
fileLocation.let {
File(it).writeBytes(withContext(Dispatchers.IO) {
part.streamProvider().readBytes()
})
}
val fileNameInServer = imageId.toString().plus(fileLocation.fileExtension())
profileController.updateProfileImage(getCurrentUser().userId, fileNameInServer)?.let {
call.respond(
ApiResponse.success(fileNameInServer, HttpStatusCode.OK)
)
}
}
}
else -> {}
}
part.dispose()
}
}
}
}
} | 5 | null | 19 | 96 | 7093a687fb0fa35e4714847b13663603aeeb6db5 | 4,066 | ktor-E-Commerce | curl License |
app/src/main/java/com/example/szyfry0/CMorseActivity.kt | dominikk787 | 305,617,080 | false | null | package com.example.szyfry0
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.preference.PreferenceManager
import kotlinx.android.synthetic.main.activity_c_morse.*
class CMorseActivity : AppCompatActivity() {
private var copyUnicode = false
private fun updateMorse() {
outTextC.setText(Morse.encode(inTextC.text.toString()).replace(".", "\u2022").replace("-", "\u2212"))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_c_morse)
val preferences = PreferenceManager.getDefaultSharedPreferences(this)
copyUnicode = preferences.getBoolean("morse_copy_unicode", false)
inTextC.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable?) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
updateMorse()
}
})
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_copy, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.menuCopyS) {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
var text = outTextC.text.toString()
if(!copyUnicode) {
text = text.replace('\u2022', '.').replace('\u2212', '-')
}
clipboard.setPrimaryClip(ClipData.newPlainText("Morse", text))
Toast.makeText(this, R.string.copy_toast, Toast.LENGTH_SHORT).show()
} else if(item.itemId == R.id.menuPasteS) {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val text = clipboard.primaryClip?.getItemAt(0)?.text?.toString()
if(text != null && text.isNotEmpty()) {
inTextC.setText(text)
updateMorse()
}
}
return super.onOptionsItemSelected(item)
}
} | 0 | Kotlin | 0 | 0 | 46a5599f655078d9c70a2836f8364b8cc691ba6f | 2,479 | Szyfry0_android | MIT License |
service_chat/src/main/kotlin/org/thechance/service_chat/data/collection/mappers/TicketMapper.kt | TheChance101 | 671,967,732 | false | null | package org.thechance.service_chat.data.collection.mappers
import org.thechance.service_chat.data.collection.TicketCollection
import org.thechance.service_chat.domain.entity.Ticket
fun Ticket.toCollection(): TicketCollection {
return TicketCollection(
ticketId = id,
userId = userId,
supportId = supportId,
time = time,
isOpen = isOpen
)
}
fun TicketCollection.toEntity(): Ticket {
return Ticket(
id = ticketId,
userId = userId,
supportId = supportId,
time = time,
messages = messages.toEntity(),
isOpen = isOpen
)
} | 4 | null | 55 | 572 | 1d2e72ba7def605529213ac771cd85cbab832241 | 624 | beep-beep | Apache License 2.0 |
core/src/commonMain/kotlin/com/maxkeppeker/sheets/core/icons/twotone/EmojiObjects.kt | maxkeppeler | 523,345,776 | false | {"Kotlin": 1337179, "Python": 4978, "Shell": 645} | package com.maxkeppeker.sheets.core.icons.twotone
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.ui.graphics.vector.ImageVector
public val EmojiObjects: ImageVector
get() {
if (_emojiObjects != null) {
return _emojiObjects!!
}
_emojiObjects = materialIcon(name = "TwoTone.EmojiObjects") {
materialPath(fillAlpha = 0.3f, strokeAlpha = 0.3f) {
moveTo(10.0f, 18.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-4.0f)
close()
}
materialPath(fillAlpha = 0.3f, strokeAlpha = 0.3f) {
moveTo(10.0f, 16.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-4.0f)
close()
}
materialPath {
moveTo(12.0f, 3.0f)
curveToRelative(-0.46f, 0.0f, -0.93f, 0.04f, -1.4f, 0.14f)
curveTo(7.84f, 3.67f, 5.64f, 5.9f, 5.12f, 8.66f)
curveToRelative(-0.48f, 2.61f, 0.48f, 5.01f, 2.22f, 6.56f)
curveTo(7.77f, 15.6f, 8.0f, 16.13f, 8.0f, 16.69f)
verticalLineTo(19.0f)
curveToRelative(0.0f, 1.1f, 0.9f, 2.0f, 2.0f, 2.0f)
horizontalLineToRelative(0.28f)
curveToRelative(0.35f, 0.6f, 0.98f, 1.0f, 1.72f, 1.0f)
reflectiveCurveToRelative(1.38f, -0.4f, 1.72f, -1.0f)
horizontalLineTo(14.0f)
curveToRelative(1.1f, 0.0f, 2.0f, -0.9f, 2.0f, -2.0f)
verticalLineToRelative(-2.31f)
curveToRelative(0.0f, -0.55f, 0.22f, -1.09f, 0.64f, -1.46f)
curveTo(18.09f, 13.95f, 19.0f, 12.08f, 19.0f, 10.0f)
curveTo(19.0f, 6.13f, 15.87f, 3.0f, 12.0f, 3.0f)
close()
moveTo(14.0f, 19.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(-1.0f)
horizontalLineToRelative(4.0f)
verticalLineTo(19.0f)
close()
moveTo(14.0f, 17.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(-1.0f)
horizontalLineToRelative(4.0f)
verticalLineTo(17.0f)
close()
moveTo(15.31f, 13.74f)
curveToRelative(-0.09f, 0.08f, -0.16f, 0.18f, -0.24f, 0.26f)
horizontalLineTo(8.92f)
curveToRelative(-0.08f, -0.09f, -0.15f, -0.19f, -0.24f, -0.27f)
curveToRelative(-1.32f, -1.18f, -1.91f, -2.94f, -1.59f, -4.7f)
curveToRelative(0.36f, -1.94f, 1.96f, -3.55f, 3.89f, -3.93f)
curveTo(11.32f, 5.03f, 11.66f, 5.0f, 12.0f, 5.0f)
curveToRelative(2.76f, 0.0f, 5.0f, 2.24f, 5.0f, 5.0f)
curveTo(17.0f, 11.43f, 16.39f, 12.79f, 15.31f, 13.74f)
close()
}
materialPath {
moveTo(11.5f, 11.0f)
horizontalLineToRelative(1.0f)
verticalLineToRelative(3.0f)
horizontalLineToRelative(-1.0f)
close()
}
materialPath {
moveTo(9.672f, 9.581f)
lineToRelative(0.707f, -0.707f)
lineToRelative(2.121f, 2.121f)
lineToRelative(-0.707f, 0.707f)
close()
}
materialPath {
moveTo(12.208f, 11.712f)
lineToRelative(-0.707f, -0.707f)
lineToRelative(2.121f, -2.121f)
lineToRelative(0.707f, 0.707f)
close()
}
}
return _emojiObjects!!
}
private var _emojiObjects: ImageVector? = null
| 14 | Kotlin | 38 | 816 | 2af41f317228e982e261522717b6ef5838cd8b58 | 3,953 | sheets-compose-dialogs | Apache License 2.0 |
shared/src/commonMain/kotlin/by/game/binumbers/main/domain/MainInteractor.kt | alexander-kulikovskii | 565,271,232 | false | {"Kotlin": 454229, "Swift": 3274, "Ruby": 2480, "Shell": 622} | package by.game.binumbers.main.domain
import by.game.binumbers.base.BinumbersNavigation
import by.game.binumbers.base.extension.emitNavigation
import by.game.binumbers.base.navigation.Screen
import by.game.binumbers.base.navigation.fromScreen
import by.game.binumbers.base.navigation.toScreen
import by.game.binumbers.main.domain.generated.MainState
import by.game.binumbers.main.domain.generated.MainStore
import by.game.binumbers.main.domain.model.MainAction
import by.game.binumbers.main.domain.model.MainSideEffect
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class MainInteractor(
private val interactorDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : MainStore, CoroutineScope by CoroutineScope(interactorDispatcher) {
private val state = MutableStateFlow(MainState.initial)
private val sideEffect = MutableSharedFlow<MainSideEffect>()
private val navigation = MutableSharedFlow<BinumbersNavigation>()
override fun observeState(): StateFlow<MainState> = state
override fun observeSideEffect(): Flow<MainSideEffect> = sideEffect
override fun observeNavigation(): Flow<BinumbersNavigation> = navigation
override fun dispatch(action: MainAction) {
when (action) {
MainAction.Load -> {}
MainAction.OnClickStatistics -> openStatistics()
MainAction.OnClickLevels -> openLevels()
MainAction.OnClickSettings -> openSettings()
MainAction.Pause -> {}
MainAction.Resume -> {}
}
}
private fun openStatistics() {
launch {
navigation.emitNavigation(
from = Screen.Main.fromScreen(),
to = Screen.WinOrLose.toScreen(),
inclusiveScreen = true,
)
}
}
private fun openLevels() {
launch {
navigation.emitNavigation(
from = Screen.Main.fromScreen(),
to = Screen.Levels.toScreen(),
)
}
}
private fun openSettings() {
launch {
navigation.emitNavigation(
from = Screen.Main.fromScreen(),
to = Screen.Settings.toScreen(),
)
}
}
}
| 0 | Kotlin | 0 | 10 | 66b1678b47a96a52ebef467111d1d4854a37486a | 2,496 | 2048-kmm | Apache License 2.0 |
src/main/kotlin/output/dictionary/templates/foreign/Title.kt | Jackson-S | 443,654,833 | false | null | package output.dictionary.templates.foreign
import kotlinx.html.BODY
import kotlinx.html.h1
import kotlinx.html.header
internal object Title {
fun BODY.title(word: String) {
header { h1 { +word } }
}
}
| 0 | Kotlin | 0 | 0 | 3ce7765887d55a2701c2dbdcdd3fe82f97093fdc | 220 | JapaneseDictionaryRewrite | MIT License |
ndarray/ndarray-core/src/commonMain/kotlin/io/kinference/ndarray/extensions/activations/elu/EluPrimitive.kt | JetBrains-Research | 244,400,016 | false | null | @file:GeneratePrimitives(
DataType.DOUBLE,
DataType.FLOAT
)
package io.kinference.ndarray.extensions.activations.elu
import io.kinference.ndarray.arrays.MutablePrimitiveNDArray
import io.kinference.ndarray.arrays.PrimitiveNDArray
import io.kinference.ndarray.extensions.constants.PrimitiveConstants
import io.kinference.ndarray.math.FastMath
import io.kinference.ndarray.math.exp
import io.kinference.ndarray.parallelizeByBlocks
import io.kinference.primitives.annotations.GeneratePrimitives
import io.kinference.primitives.annotations.MakePublic
import io.kinference.primitives.types.DataType
import io.kinference.primitives.types.toPrimitive
@MakePublic
internal suspend fun PrimitiveNDArray.elu(alpha: Float = 1f): PrimitiveNDArray {
val actualAlpha = alpha.toPrimitive()
val output = MutablePrimitiveNDArray(strides)
val inputBlocks = this.array.blocks
val outputBlocks = output.array.blocks
val blocksNum = this.array.blocksNum
val blockSize = this.array.blockSize
parallelizeByBlocks(blockSize, blocksNum, 2048) { blockStart, blockEnd ->
for (blockIdx in blockStart until blockEnd) {
val inputBlock = inputBlocks[blockIdx]
val outputBlock = outputBlocks[blockIdx]
for (idx in outputBlock.indices) {
val x = inputBlock[idx]
if (x >= PrimitiveConstants.ZERO) {
outputBlock[idx] = x
} else {
outputBlock[idx] = (FastMath.exp(x) - PrimitiveConstants.ONE) * actualAlpha
}
}
}
}
return output
}
| 7 | null | 6 | 95 | e47129b6f1e2a60bf12404d8126701ce7ef4db3a | 1,615 | kinference | Apache License 2.0 |
shared/src/main/kotlin/com/egm/stellio/shared/web/ExceptionHandler.kt | vraybaud | 274,435,648 | true | {"Kotlin": 555843, "Shell": 4974, "TSQL": 1381, "Dockerfile": 844, "PLSQL": 61} | package com.egm.stellio.shared.web
import com.egm.stellio.shared.model.AccessDeniedException
import com.egm.stellio.shared.model.AccessDeniedResponse
import com.egm.stellio.shared.model.AlreadyExistsException
import com.egm.stellio.shared.model.AlreadyExistsResponse
import com.egm.stellio.shared.model.BadRequestDataException
import com.egm.stellio.shared.model.BadRequestDataResponse
import com.egm.stellio.shared.model.InternalErrorResponse
import com.egm.stellio.shared.model.JsonLdErrorResponse
import com.egm.stellio.shared.model.JsonParseErrorResponse
import com.egm.stellio.shared.model.ResourceNotFoundException
import com.egm.stellio.shared.model.ResourceNotFoundResponse
import com.egm.stellio.shared.util.ApiUtils
import com.fasterxml.jackson.core.JsonParseException
import com.github.jsonldjava.core.JsonLdError
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
@RestControllerAdvice
class ExceptionHandler {
@ExceptionHandler
fun transformErrorResponse(throwable: Throwable): ResponseEntity<String> =
when (val cause = throwable.cause ?: throwable) {
is AlreadyExistsException -> generateErrorResponse(
HttpStatus.CONFLICT,
AlreadyExistsResponse(cause.message)
)
is ResourceNotFoundException -> generateErrorResponse(
HttpStatus.NOT_FOUND,
ResourceNotFoundResponse(cause.message)
)
is BadRequestDataException -> generateErrorResponse(
HttpStatus.BAD_REQUEST,
BadRequestDataResponse(cause.message)
)
is JsonLdError -> generateErrorResponse(
HttpStatus.BAD_REQUEST,
JsonLdErrorResponse(cause.type.toString(), cause.message.orEmpty())
)
is JsonParseException -> generateErrorResponse(
HttpStatus.BAD_REQUEST,
JsonParseErrorResponse(cause.message ?: "There has been a problem during JSON parsing")
)
is AccessDeniedException -> generateErrorResponse(
HttpStatus.FORBIDDEN,
AccessDeniedResponse(cause.message)
)
else -> generateErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR,
InternalErrorResponse(cause.message ?: "There has been an error during the operation execution")
)
}
private fun generateErrorResponse(status: HttpStatus, exception: Any) =
ResponseEntity.status(status)
.contentType(MediaType.APPLICATION_JSON)
.body(ApiUtils.serializeObject(exception))
}
| 0 | null | 0 | 0 | e2c9ee575eaf3397f6262618c98356fe0dbd6d6a | 2,845 | stellio-context-broker | Apache License 2.0 |
analytics-impl/src/main/java/com/grappim/hateitorrateit/analyticsimpl/HomeScreenAnalyticsImpl.kt | Grigoriym | 704,244,986 | false | {"Kotlin": 383936} | package com.grappim.hateitorrateit.analyticsimpl
import com.grappim.hateitorrateit.analyticsapi.AnalyticsController
import com.grappim.hateitorrateit.analyticsapi.HomeScreenAnalytics
import javax.inject.Inject
import javax.inject.Singleton
internal const val HOME_SCREEN_START = "home_screen_start"
internal const val HOME_PRODUCT_CLICKED = "home_product_clicked"
@Singleton
class HomeScreenAnalyticsImpl @Inject constructor(
private val analyticsController: AnalyticsController
) : HomeScreenAnalytics {
override fun trackHomeScreenStart() {
analyticsController.trackEvent(HOME_SCREEN_START)
}
override fun trackProductClicked() {
analyticsController.trackEvent(HOME_PRODUCT_CLICKED)
}
}
| 2 | Kotlin | 0 | 0 | be87578c63ab5d535617df1676bc65c661ab3ccc | 729 | HateItOrRateIt | Apache License 2.0 |
src/main/kotlin/com/fiap/healthmed/adapter/controller/DoctorController.kt | FIAP-3SOAT-G15 | 831,891,205 | false | {"Kotlin": 89410, "HCL": 17775, "Gherkin": 367, "Makefile": 356, "Dockerfile": 286} | package com.fiap.healthmed.adapter.controller
import com.fiap.healthmed.adapter.gateway.DoctorGateway
import com.fiap.healthmed.domain.Doctor
import com.fiap.healthmed.driver.web.DoctorApi
import com.fiap.healthmed.driver.web.request.AvailableTimesRequest
import com.fiap.healthmed.driver.web.request.DoctorRequest
import com.fiap.healthmed.driver.web.request.toDomain
import com.fiap.healthmed.usecases.CreateDoctorUseCase
import com.fiap.healthmed.usecases.SearchDoctorUseCase
import com.fiap.healthmed.usecases.UpdateAvailableTimeDoctorUseCase
import com.fiap.healthmed.usecases.UpdateDoctorUseCase
import com.fiap.healthmed.usecases.service.DoctorService
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RestController
@RestController
class DoctorController(
doctorGateway: DoctorGateway,
) : DoctorApi {
private val service = DoctorService(doctorGateway)
private val createDoctorUseCase: CreateDoctorUseCase = service
private val updateDoctorUseCase: UpdateDoctorUseCase = service
private val updateAvailableTimeDoctorUseCase: UpdateAvailableTimeDoctorUseCase = service
private val searchDoctorUseCase: SearchDoctorUseCase = service
override fun create(request: DoctorRequest): ResponseEntity<Doctor> {
return ResponseEntity.ok(createDoctorUseCase.create(request.toDomain()))
}
override fun update(crm: String, request: DoctorRequest): ResponseEntity<Doctor> {
return ResponseEntity.ok(updateDoctorUseCase.update(request.toDomain()))
}
override fun updateAvailableTimes(crm: String, request: AvailableTimesRequest): ResponseEntity<Doctor> {
return ResponseEntity.ok(updateAvailableTimeDoctorUseCase.updateAvailableTime(crm, request.toDomain()))
}
override fun search(query: Map<String, String>): ResponseEntity<List<Doctor>> {
return ResponseEntity.ok(searchDoctorUseCase.search(query))
}
override fun get(crm: String): ResponseEntity<Doctor> {
return ResponseEntity.ok(searchDoctorUseCase.get(crm))
}
}
| 0 | Kotlin | 0 | 1 | be624d424916c8c4bed90d0cfde725482ab4bc97 | 2,068 | healthmed-app | MIT License |
sdk/push/src/main/java/com/klaviyo/push/KlaviyoPushService.kt | klaviyo | 282,284,680 | false | null | package com.klaviyo.push
import com.google.firebase.messaging.FirebaseMessagingService
import com.klaviyo.coresdk.Klaviyo
import com.klaviyo.coresdk.networking.KlaviyoCustomerProperties
import com.klaviyo.coresdk.utils.KlaviyoPreferenceUtils
/**
* Implementation of the FCM messaging service that runs when the parent application is started
* This service handles all the interaction with FCM service that the SDK needs
*
* If the parent application has their own FCM messaging service defined they need to ensure
* that the implementation details of this service are carried over into their own
*/
class KlaviyoPushService: FirebaseMessagingService() {
companion object {
internal const val PUSH_TOKEN_PREFERENCE_KEY = "PUSH_TOKEN"
internal const val REQUEST_PUSH_KEY = "\$android_tokens"
/**
* Returns the current push token that we have stored on this device
*
* @return The push token we read from the shared preferences
*/
fun getCurrentPushToken(): String {
return KlaviyoPreferenceUtils.readStringPreference(PUSH_TOKEN_PREFERENCE_KEY) ?: ""
}
}
/**
* FCM service calls this function whenever a token is generated
* This can be whenever a token is created anew, or whenever it has expired and regenerated itself
*
* We append this new token to a property map and queue it into an identify request to send to
* the Klaviyo asynchronous APIs.
* We then write it into the shared preferences so that we can fetch the token for this device
* as needed
*
* @param newToken The newly generated token returned from the FCM service
*/
override fun onNewToken(newToken: String) {
super.onNewToken(newToken)
val properties = KlaviyoCustomerProperties()
properties.addAppendProperty(REQUEST_PUSH_KEY, newToken)
Klaviyo.identify(properties)
KlaviyoPreferenceUtils.writeStringPreference(PUSH_TOKEN_PREFERENCE_KEY, newToken)
}
} | 0 | Kotlin | 1 | 1 | 72b3df42c1c0e31a9e464d0f6102a57b544165f3 | 2,030 | klaviyo-android-sdk | MIT License |
annotation/annotation/src/commonMain/kotlin/androidx/annotation/ProductionVisibility.kt | androidx | 256,589,781 | false | null | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.annotation
/**
* Typedef for the [VisibleForTesting.otherwise] attribute.
*
*/
@IntDef(
VisibleForTesting.PRIVATE,
VisibleForTesting.PACKAGE_PRIVATE,
VisibleForTesting.PROTECTED,
VisibleForTesting.NONE
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@Retention(AnnotationRetention.SOURCE)
internal annotation class ProductionVisibility
| 29 | null | 778 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 985 | androidx | Apache License 2.0 |
app/src/main/java/com/example/music_player_mvvm/ui/settingview/adapter/SettingSongListAdapter.kt | KevinMartinezC | 625,009,498 | false | null | package com.example.music_player_mvvm.ui.settingview.adapter
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.music_player_mvvm.databinding.SongListItemBinding
import com.example.music_player_mvvm.model.Song
@Suppress("DEPRECATION")
class SettingSongListAdapter(
private val songs: MutableList<Song>,
private val onSongClickListener: (Int) -> Unit,
private val onDeleteClickListener: (Int) -> Unit
) : RecyclerView.Adapter<SettingSongListAdapter.SettingSongViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingSongViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = SongListItemBinding.inflate(inflater, parent, false)
return SettingSongViewHolder(binding)
}
override fun onBindViewHolder(holder: SettingSongViewHolder, position: Int) {
holder.bind(songs[position], onSongClickListener, onDeleteClickListener)
}
override fun getItemCount(): Int {
return songs.size
}
inner class SettingSongViewHolder(private val binding: SongListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(
song: Song,
onSongClickListener: (Int) -> Unit,
onDeleteClickListener: (Int) -> Unit
) {
binding.songTitleTextView.text = song.title
// Update the item UI based on the song's selected state
binding.root.setBackgroundColor(
if (song.selected) Color.parseColor("#E0E0E0")
else Color.TRANSPARENT
)
// Load album art into the ImageView
Glide.with(binding.albumArtImageView.context)
.load(song.albumArtUri)
.into(binding.albumArtImageView)
// Set click listener for the whole item
itemView.setOnClickListener {
onSongClickListener(adapterPosition)
}
// Set click listener for the delete button
binding.deleteButton.setOnClickListener {
onDeleteClickListener(adapterPosition)
}
}
}
}
| 1 | Kotlin | 0 | 0 | cb0fce3c7b21da47fe3769ef92fcff20a837d915 | 2,285 | Music-player-mvvm | MIT License |
app/src/main/java/com/example/rabbitapp/ui/vaccines/VaccinationsListAdapter.kt | AgnieszkaKlobus12 | 604,315,829 | false | {"Kotlin": 188198} | package com.example.rabbitapp.ui.vaccines
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.rabbitapp.R
import com.example.rabbitapp.model.entities.relations.Vaccinated
import com.example.rabbitapp.ui.mainTab.MainListViewModel
import com.example.rabbitapp.utils.RabbitDetails
class VaccinationsListAdapter(
private val viewModel: MainListViewModel,
private val values: List<Vaccinated>,
private val onSelectedItem: OnSelectedVaccination
) :
RecyclerView.Adapter<VaccinationsListAdapter.VaccinationsListItemView>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VaccinationsListItemView {
val itemView =
LayoutInflater.from(parent.context)
.inflate(R.layout.vaccination_list_item, parent, false)
return VaccinationsListItemView(itemView)
}
override fun onBindViewHolder(holder: VaccinationsListItemView, position: Int) {
val item = values[position]
holder.name.text = viewModel.getVaccine(item.fkVaccine)?.name
holder.date.text = RabbitDetails.getDateString(item.date)
if (item.nextDoseDate != null) {
holder.nextDate.text = item.nextDoseDate.let { RabbitDetails.getDateString(it) }
} else {
holder.nextDate.visibility = View.GONE
}
holder.doseNumber.text = item.doseNumber.toString()
holder.itemView.setOnClickListener { onSelectedItem.onItemClick(item) }
}
override fun getItemCount(): Int = values.size
inner class VaccinationsListItemView(iv: View) : RecyclerView.ViewHolder(iv) {
val name: TextView = iv.findViewById(R.id.vaccination_list_item_vaccine_name)
val date: TextView = iv.findViewById(R.id.vaccination_list_item_vaccination_date)
val nextDate: TextView = iv.findViewById(R.id.vaccination_list_item_date_next)
val doseNumber: TextView = iv.findViewById(R.id.vaccination_list_item_dose_number)
}
} | 0 | Kotlin | 0 | 1 | b545611b9b44b9a84ed502368cbb80f470388737 | 2,086 | RabbitApp | MIT License |
block-tlb/src/AddrNone.kt | ton-community | 448,983,229 | false | {"Kotlin": 1194581} | package org.ton.block
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.ton.cell.CellBuilder
import org.ton.cell.CellSlice
import org.ton.tlb.TlbConstructor
import org.ton.tlb.TlbPrettyPrinter
import org.ton.tlb.providers.TlbConstructorProvider
@SerialName("addr_none")
@Serializable
public object AddrNone : MsgAddressExt, TlbConstructorProvider<AddrNone> by AddrNoneTlbConstructor {
override fun toString(): String = print().toString()
override fun print(tlbPrettyPrinter: TlbPrettyPrinter): TlbPrettyPrinter = tlbPrettyPrinter {
type("addr_none")
}
}
private object AddrNoneTlbConstructor : TlbConstructor<AddrNone>(
schema = "addr_none\$00 = MsgAddressExt;"
) {
override fun storeTlb(
cellBuilder: CellBuilder,
value: AddrNone
) {
}
override fun loadTlb(cellSlice: CellSlice): AddrNone {
return AddrNone
}
}
| 21 | Kotlin | 24 | 80 | 7eb82e9b04a2e518182ebfc56c165fbfcc916be9 | 928 | ton-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/hotm/world/HotMPortalGenPositions.kt | Heart-of-the-Machine | 271,669,718 | false | null | package com.github.hotm.world
import com.github.hotm.util.BiomeUtils
import net.minecraft.block.Blocks
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.ChunkPos
import net.minecraft.world.Heightmap
import net.minecraft.world.RegistryWorldView
import net.minecraft.world.StructureWorldAccess
import java.util.*
object HotMPortalGenPositions {
private const val WORLD_SEED_OFFSET = 0xDEADBEEFL
private const val MIN_ROOF_HEIGHT = 32
/**
* Gets a consistent random for use in portal placement.
*/
private fun getPortalPlacementRandom(world: StructureWorldAccess, portalX: Int, portalZ: Int): Random =
Random(world.seed + (portalX * 31 + portalZ) * 31 + WORLD_SEED_OFFSET)
/**
* Gets the location of the portal spawner block entity within a chunk.
*/
fun getPortalSpawnerPos(pos: ChunkPos): BlockPos = BlockPos(pos.startX, 1, pos.startZ)
/**
* Scans the world at the given x and z coordinates for valid biomes and surfaces.
*/
private fun findPortalPoses(world: RegistryWorldView, portalX: Int, portalZ: Int): FindContext {
val surfaces = mutableListOf<Int>()
val validBiomes = mutableListOf<Int>()
val pos = BlockPos.Mutable(portalX, 0, portalZ)
var prevAir = world.isAir(pos)
var roof = -1
for (y in world.bottomY..world.topY) {
pos.y = y
if (world.getBlockState(pos).block == Blocks.BEDROCK && y > MIN_ROOF_HEIGHT) {
roof = y
break
}
if (BiomeUtils.checkNonNectereBiome(world, pos)) {
validBiomes.add(y)
}
val air = world.isAir(pos)
if (!prevAir && air) {
surfaces.add(y)
}
prevAir = air
}
surfaces.removeAll((roof - 4)..roof)
validBiomes.removeAll((roof - 4)..roof)
return FindContext(roof, surfaces, validBiomes)
}
/**
* Finds a portal position with the given x and z coordinates.
*
* This does not do any biome checking for world-gen.
*/
fun findPortalPos(world: StructureWorldAccess, portalX: Int, portalZ: Int): BlockPos {
val random = getPortalPlacementRandom(world, portalX, portalZ)
val find = findPortalPoses(world, portalX, portalZ)
val surfaces = find.surfaces
val roof = find.roof
val structureY = when {
surfaces.isEmpty() -> random.nextInt(
if (roof > MIN_ROOF_HEIGHT) {
roof - 8
} else {
124
}
) + 4
roof > MIN_ROOF_HEIGHT -> surfaces[random.nextInt(surfaces.size)]
else -> world.getTopY(Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, portalX, portalZ)
}
return BlockPos(portalX, HotMPortalOffsets.structure2PortalY(structureY), portalZ)
}
/**
* Find a valid non-nectere side portal position with the given x and z coordinates.
*
* This checks non-nectere side biomes for validity and returns null if no positions could be found in valid
* non-nectere biomes.
*/
fun findValidNonNecterePortalPos(world: StructureWorldAccess, portalX: Int, portalZ: Int): BlockPos? {
val random = getPortalPlacementRandom(world, portalX, portalZ)
val find = findPortalPoses(world, portalX, portalZ)
val validBiomes = find.validBiomes
if (validBiomes.isEmpty()) {
return null
}
val validSurfaces = find.surfaces.intersect(validBiomes).toList()
val topY = world.getTopY(Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, portalX, portalZ)
val structureY = when {
validSurfaces.isEmpty() -> validBiomes[random.nextInt(validBiomes.size)]
find.roof > MIN_ROOF_HEIGHT -> validSurfaces[random.nextInt(validSurfaces.size)]
validBiomes.contains(topY) -> topY
else -> validSurfaces[random.nextInt(validSurfaces.size)]
}
return BlockPos(portalX, HotMPortalOffsets.structure2PortalY(structureY), portalZ)
}
/**
* Find a possibly valid non-nectere side portal position with the given x and z coordinates.
*
* This checks non-nectere side biomes for validity. If no positions in valid biomes could be found a position in
* invalid biome is selected instead.
*/
fun findMaybeValidNonNecterePortalPos(world: StructureWorldAccess, portalX: Int, portalZ: Int): BlockPos {
val random = getPortalPlacementRandom(world, portalX, portalZ)
val find = findPortalPoses(world, portalX, portalZ)
val validBiomes = find.validBiomes
val surfaces = find.surfaces
val roof = find.roof
val validSurfaces = find.surfaces.intersect(validBiomes).toList()
val topY = world.getTopY(Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, portalX, portalZ)
val structureY = if (validBiomes.isEmpty()) {
when {
surfaces.isEmpty() -> random.nextInt(
if (roof > MIN_ROOF_HEIGHT) {
roof - 8
} else {
124
}
) + 4
roof > MIN_ROOF_HEIGHT -> surfaces[random.nextInt(surfaces.size)]
else -> world.getTopY(Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, portalX, portalZ)
}
} else {
when {
validSurfaces.isEmpty() -> validBiomes[random.nextInt(validBiomes.size)]
roof > MIN_ROOF_HEIGHT -> validSurfaces[random.nextInt(validSurfaces.size)]
validBiomes.contains(topY) -> topY
else -> validSurfaces[random.nextInt(validSurfaces.size)]
}
}
return BlockPos(portalX, HotMPortalOffsets.structure2PortalY(structureY), portalZ)
}
/**
* Gets the x position of a portal structure feature from the portal's chunk x.
*/
fun chunk2StructureX(chunkX: Int): Int {
return chunkX.shl(4)
}
/**
* Gets the x position of the portal in a portal structure feature from the portal's chunk x.
*/
fun chunk2PortalX(chunkX: Int): Int {
return HotMPortalOffsets.structure2PortalX(chunk2StructureX(chunkX))
}
/**
* Gets the z position of a portal structure feature from the portal's chunk z.
*/
fun chunk2StructureZ(chunkZ: Int): Int {
return chunkZ.shl(4)
}
/**
* Gets the z position of the portal in a portal structure feature from the portal's chunk z.
*/
fun chunk2PortalZ(chunkZ: Int): Int {
return HotMPortalOffsets.structure2PortalZ(chunk2StructureZ(chunkZ))
}
private data class FindContext(val roof: Int, val surfaces: List<Int>, val validBiomes: List<Int>)
} | 7 | Kotlin | 0 | 5 | de148c50f9c8ea1d1a3bd4f4dfb035c4614d70a1 | 6,866 | heart-of-the-machine | MIT License |
src/main/kotlin/net/piratjsk/rby/fish/Specie.kt | cobrex1 | 156,452,973 | true | {"Java": 98765, "Kotlin": 4033} | package net.piratjsk.rby.fish
import org.bukkit.inventory.ItemStack
open class Specie (
val name : String,
val catchConditions: Collection<CatchCondition>,
val effects: Collection<FishEffect>,
val chance: Float = 0f,
val minLength: Float = 0f,
val maxLength: Float = 0f,
val icon: ItemStack? = null
) {
val eatEffects : Collection<CatchCondition>
get() = this.catchConditions.filter { it is CatchCondition }.toList()
} | 0 | Java | 0 | 0 | 49248d8b8930922142e4f9cb284db980fb90aa00 | 498 | Rby | MIT License |
network-ktor/src/main/java/ru/shafran/network/services/KtorServicesRepository.kt | SuLG-ik | 384,238,863 | false | null | package ru.shafran.network.services
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import ru.shafran.network.services.data.CreateConfigurationRequest
import ru.shafran.network.services.data.CreateConfigurationResponse
import ru.shafran.network.services.data.CreateServiceRequest
import ru.shafran.network.services.data.CreateServiceResponse
import ru.shafran.network.services.data.DeactivateServiceConfigurationRequest
import ru.shafran.network.services.data.DeactivateServiceConfigurationResponse
import ru.shafran.network.services.data.EditServiceRequest
import ru.shafran.network.services.data.EditServiceResponse
import ru.shafran.network.services.data.GetAllServicesRequest
import ru.shafran.network.services.data.GetAllServicesResponse
import ru.shafran.network.services.data.GetServiceByIdRequest
import ru.shafran.network.services.data.GetServiceByIdResponse
internal class KtorServicesRepository(
private val httpClient: HttpClient,
) : ServicesRepository {
override suspend fun editService(request: EditServiceRequest): EditServiceResponse {
return httpClient.patch("services/editService",) {
setBody(request)
}.body()
}
override suspend fun getAllServices(request: GetAllServicesRequest): GetAllServicesResponse {
return httpClient.get("services/getAllServices",) {
setBody(request)
}.body()
}
override suspend fun createService(request: CreateServiceRequest): CreateServiceResponse {
return httpClient.post("services/createService",) {
setBody(request)
}.body()
}
override suspend fun getServiceById(request: GetServiceByIdRequest): GetServiceByIdResponse {
return httpClient.get("services/getServiceById",) {
setBody(request)
}.body()
}
override suspend fun createConfiguration(request: CreateConfigurationRequest): CreateConfigurationResponse {
return httpClient.put("services/createConfiguration",) {
setBody(request)
}.body()
}
override suspend fun deactivateConfiguration(request: DeactivateServiceConfigurationRequest): DeactivateServiceConfigurationResponse {
return httpClient.delete("services/deactivateConfiguration",) {
setBody(request)
}.body()
}
} | 0 | Kotlin | 0 | 1 | aef4a3083c87e2bd2de1eaff2b9925a5dc226fe2 | 2,340 | ShafranCards | Apache License 2.0 |
app/src/main/java/com/example/resume/ui/certificates/CertificatesViewModel.kt | Kavertx | 620,306,183 | false | null | package com.example.resume.ui.certificates
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class CertificatesViewModel : ViewModel() {
val androidKotlin2022 = Certificate("Android Development with Kotlin",
"https://softuni.bg/Certificates/Details/148201/bcf6ba8e")
val QAbasics = Certificate("QA Basics",
"https://softuni.bg/certificates/details/154752/77aba62a")
val certificatesArray = arrayOf<Certificate>(androidKotlin2022, QAbasics)
}
class Certificate(val name: String, val URL: String) | 1 | Kotlin | 0 | 0 | 57851b9d87c5ee42a5a3ff3b9fd3605876e9189c | 591 | ResumeApp | MIT License |
shared/src/commonMain/kotlin/core/auth/data/remote/AuthService.kt | adelsaramii | 731,513,657 | false | {"Kotlin": 83513, "Swift": 580, "Shell": 228} | package core.auth.data.remote
import arrow.core.Either
import data.remote.Failure
interface AuthService {
suspend fun loginPassword(username: String, password: String): Either<Failure.NetworkFailure, LoginDto>
suspend fun loginNumber(number: String): Either<Failure.NetworkFailure, LoginDto>
} | 0 | Kotlin | 0 | 0 | a45bfbcf3819d4d680ddf09b47bb7daa4c5be717 | 303 | Health | Apache License 2.0 |
app/src/main/java/com/alwaysondisplay/analogclock/digital/nightclock/neon/NeonActivity.kt | HammadAhmed-AndroidDeveloper | 732,705,344 | false | {"Kotlin": 86972} | package com.alwaysondisplay.analogclock.digital.nightclock.neon
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.alwaysondisplay.analogclock.digital.nightclock.databinding.ActivityNeonBinding
import com.alwaysondisplay.analogclock.digital.nightclock.service.Preferences
import com.leondzn.simpleanalogclock.SimpleAnalogClock
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class NeonActivity : AppCompatActivity() {
private lateinit var neon1: SimpleAnalogClock
private lateinit var neon2: SimpleAnalogClock
private lateinit var neon3: SimpleAnalogClock
private lateinit var neon4: SimpleAnalogClock
private lateinit var neon5: SimpleAnalogClock
private lateinit var neon6: SimpleAnalogClock
private lateinit var neon7: SimpleAnalogClock
private lateinit var neon8: SimpleAnalogClock
private lateinit var neon9: SimpleAnalogClock
private lateinit var neon10: SimpleAnalogClock
private var neon: String? = null
private lateinit var batteryLevelTv: TextView
private lateinit var timeLayout: LinearLayout
private lateinit var batteryLayout: LinearLayout
private lateinit var abstractLayout: LinearLayout
private var preferences: Preferences? = null
private lateinit var binding: ActivityNeonBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityNeonBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.hide()
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON)
preferences = Preferences(this)
neon1 = binding.neon1
neon2 = binding.neon2
neon3 = binding.neon3
neon4 = binding.neon4
neon5 = binding.neon5
neon6 = binding.neon6
neon7 = binding.neon7
neon8 = binding.neon8
neon9 = binding.neon9
neon10 = binding.neon10
timeLayout = binding.timeLayout
batteryLayout = binding.batteryLayout
abstractLayout = binding.abstractLayout
batteryLevelTv = binding.batteryLevelTv
val iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
registerReceiver(mBroadcastReceiver, iFilter)
neon = preferences?.getNeonApply()
when (neon) {
"neon1" -> setClocksVisibility(neon1, neon2, neon3, neon4, neon5, neon6, neon7, neon8, neon9, neon10)
"neon2" -> setClocksVisibility(neon2, neon1, neon3, neon4, neon5, neon6, neon7, neon8, neon9, neon10)
"neon3" -> setClocksVisibility(neon3, neon2, neon1, neon4, neon5, neon6, neon7, neon8, neon9, neon10)
"neon4" -> setClocksVisibility(neon4, neon2, neon3, neon1, neon5, neon6, neon7, neon8, neon9, neon10)
"neon5" -> setClocksVisibility(neon5, neon2, neon3, neon4, neon1, neon6, neon7, neon8, neon9, neon10)
"neon6" -> setClocksVisibility(neon6, neon2, neon3, neon4, neon5, neon1, neon7, neon8, neon9, neon10)
"neon7" -> setClocksVisibility(neon7, neon2, neon3, neon4, neon5, neon6, neon1, neon8, neon9, neon10)
"neon8" -> setClocksVisibility(neon8, neon2, neon3, neon4, neon5, neon6, neon7, neon1, neon9, neon10)
"neon9" -> setClocksVisibility(neon9, neon2, neon3, neon4, neon5, neon6, neon7, neon8, neon1, neon10)
"neon10" -> setClocksVisibility(neon10, neon2, neon3, neon4, neon5, neon6, neon7, neon8, neon9, neon1)
}
val mHandler = Handler(Looper.getMainLooper())
Thread {
while (true) {
try {
Thread.sleep(1000)
mHandler.post {
val hour = SimpleDateFormat("HH", Locale.getDefault()).format(Date())
val minute = SimpleDateFormat("mm", Locale.getDefault()).format(Date())
val second = SimpleDateFormat("ss", Locale.getDefault()).format(Date())
val h = hour.toInt()
val m = minute.toInt()
val s = second.toInt()
neon1.setTime(h, m, s)
neon2.setTime(h, m, s)
neon3.setTime(h, m, s)
neon4.setTime(h, m, s)
neon5.setTime(h, m, s)
neon6.setTime(h, m, s)
neon7.setTime(h, m, s)
neon8.setTime(h, m, s)
neon9.setTime(h, m, s)
neon10.setTime(h, m, s)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}.start()
}
private fun setClocksVisibility(
mainClock: SimpleAnalogClock, vararg otherClocks: SimpleAnalogClock
) {
mainClock.visibility = View.VISIBLE
for (clock in otherClocks) {
clock.visibility = View.GONE
}
}
private val mBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
@SuppressLint("SetTextI18n")
override fun onReceive(context: Context, intent: Intent) {
var chargingStatus = ""
when (intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)) {
BatteryManager.BATTERY_STATUS_CHARGING -> chargingStatus = "Charging"
BatteryManager.BATTERY_STATUS_DISCHARGING -> chargingStatus = "Not Charging"
BatteryManager.BATTERY_STATUS_FULL -> chargingStatus = "Battery Full"
BatteryManager.BATTERY_STATUS_UNKNOWN -> chargingStatus = "Unknown"
BatteryManager.BATTERY_STATUS_NOT_CHARGING -> chargingStatus = "Not Charging"
}
batteryLevelTv.text = "$chargingStatus ${intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)} %"
}
}
} | 0 | Kotlin | 0 | 0 | 51461323b9a062da20dfb3fc50f7ce2c4545446f | 6,462 | AlwaysOnDisplay | MIT License |
app/src/main/java/com/example/earthimagesapp/di/AppModule.kt | mateico | 637,574,482 | false | null | package com.example.earthimagesapp.di
import android.app.Application
import androidx.room.Room
import com.example.earthimagesapp.data.local.Converters
import com.example.earthimagesapp.data.local.EarthImagesDatabase
import com.example.earthimagesapp.data.local.GsonParser
import com.example.earthimagesapp.data.remote.EarthImagesApi
import com.example.earthimagesapp.data.repository.DayDataRepositoryImpl
import com.example.earthimagesapp.data.repository.DayRepositoryImpl
import com.example.earthimagesapp.domain.DayDataRepository
import com.example.earthimagesapp.domain.DayRepository
import com.example.earthimagesapplication.BuildConfig
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.create
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideDayRepository(
db: EarthImagesDatabase,
api: EarthImagesApi
): DayRepository{
return DayRepositoryImpl(db, api)
}
@Provides
@Singleton
fun provideDayDataRepository(
db: EarthImagesDatabase,
api: EarthImagesApi
): DayDataRepository {
return DayDataRepositoryImpl(db, api)
}
@Provides
@Singleton
fun provideEarthImagesApi(): EarthImagesApi {
val okHttpClientBuilder = OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
if (BuildConfig.DEBUG) {
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
okHttpClientBuilder.addInterceptor(logging)
}
return Retrofit.Builder()
.baseUrl(EarthImagesApi.BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.client(okHttpClientBuilder.build())
.build()
.create()
}
@Provides
@Singleton
fun provideEarthImagesDatabase(app: Application): EarthImagesDatabase {
return Room.databaseBuilder(
app,
EarthImagesDatabase::class.java,
"earthimagesdb.db"
)
.addTypeConverter(Converters(GsonParser(Gson())))
.fallbackToDestructiveMigration()
.build()
}
} | 1 | Kotlin | 0 | 1 | 03bf5b5034cf8bede35d846333e88438023910b9 | 2,573 | earth_image_app | MIT License |
app/src/main/java/fi/kroon/vadret/data/radar/cache/RadarDiskCache.kt | marvinmosa | 241,497,201 | true | {"Kotlin": 871560} | package fi.kroon.vadret.data.radar.cache
import fi.kroon.vadret.data.common.BaseCache
import fi.kroon.vadret.data.failure.Failure
import fi.kroon.vadret.data.radar.model.Radar
import fi.kroon.vadret.presentation.radar.di.RadarFeatureScope
import fi.kroon.vadret.util.extension.asLeft
import fi.kroon.vadret.util.extension.asRight
import io.github.sphrak.either.Either
import io.reactivex.Single
import javax.inject.Inject
import okhttp3.internal.cache.DiskLruCache
import okio.buffer
import timber.log.Timber
@RadarFeatureScope
class RadarDiskCache @Inject constructor(
private val cache: DiskLruCache
) : BaseCache() {
init {
cache.initialize()
}
private companion object {
const val KEY = "radar"
const val INDEX = 0
}
fun put(radar: Radar): Single<Either<Failure, Radar>> =
Single.fromCallable {
val editor = cache.edit(KEY)
val sink = editor?.newSink(INDEX)
val bufferedSink = sink?.buffer()
val byteArray = serializerObject(radar)
bufferedSink.use { _ ->
bufferedSink?.write(byteArray)
}
editor?.commit()
radar.asRight() as Either<Failure, Radar>
}.doOnError {
Timber.e("Disk cache insert failed: $it")
}.onErrorReturn {
Failure
.DiskCacheLruWriteFailure
.asLeft()
}
fun read(): Single<Either<Failure, Radar>> = Single.fromCallable {
val snapshot: DiskLruCache.Snapshot = cache.get(KEY)!!
val byteArray: ByteArray
byteArray = snapshot.getSource(INDEX)
.buffer()
.readByteArray()
deserializeBytes<Radar>(byteArray)
.asRight() as Either<Failure, Radar>
}.onErrorReturn {
Failure
.DiskCacheLruReadFailure
.asLeft()
}
fun remove(): Single<Either<Failure, Boolean>> = Single.fromCallable {
cache.remove(KEY).asRight() as Either<Failure, Boolean>
}.onErrorReturn {
Failure
.DiskCacheEvictionFailure
.asLeft()
}
} | 0 | null | 0 | 0 | f8149920c34bb3bc5e3148785ce217e37e596fbe | 2,133 | android | Apache License 2.0 |
analysis/analysis-api/testData/components/compileTimeConstantProvider/evaluate/annotationInAnnotation_collectionLiteral.kt | JetBrains | 3,432,266 | false | null | annotation class Annotation(vararg val strings: String)
annotation class AnnotationInner(val value: Annotation)
@AnnotationInner(<expr>Annotation(strings = ["v1", "v2"])</expr>)
class C
| 125 | Kotlin | 4813 | 39,375 | 83d2d2cfcfc3d9903c902ca348f331f89bed1076 | 188 | kotlin | Apache License 2.0 |
src/commonMain/kotlin/your/game/systems/CoinSystem.kt | dwursteisen | 427,936,086 | false | {"Kotlin": 30276, "HTML": 308} | package your.game.systems
import com.github.dwursteisen.minigdx.Seconds
import com.github.dwursteisen.minigdx.ecs.components.ModelComponent
import com.github.dwursteisen.minigdx.ecs.components.SpriteComponent
import com.github.dwursteisen.minigdx.ecs.entities.Entity
import com.github.dwursteisen.minigdx.ecs.entities.position
import com.github.dwursteisen.minigdx.ecs.events.Event
import com.github.dwursteisen.minigdx.ecs.systems.EntityQuery
import com.github.dwursteisen.minigdx.ecs.systems.System
import com.github.dwursteisen.minigdx.math.Interpolations
import your.game.Coin
import your.game.CoinRotation
import your.game.NextQuestionEvent
import your.game.TouchCoinEvent
class CoinRotationSystem : System(EntityQuery.Companion.of(CoinRotation::class)) {
override fun onEntityAdded(entity: Entity) {
entity.get(SpriteComponent::class).switchToAnimation("coin")
}
private val duration = 2f
override fun update(delta: Seconds, entity: Entity) {
val coin = entity.get(CoinRotation::class)
coin.t += delta
if (coin.t > duration) {
coin.t -= duration
}
entity.position.setLocalRotation(
x = 0f,
y = Interpolations.linear.interpolate(0f, 360f, coin.t / duration),
z = 0f
)
}
}
class CoinSystem : System(EntityQuery.of(Coin::class)) {
override fun update(delta: Seconds, entity: Entity) = Unit
override fun onEvent(event: Event, entityQuery: EntityQuery?) {
if (event is TouchCoinEvent) {
entities.forEach {
it.get(ModelComponent::class).hidden = true
}
} else if (event is NextQuestionEvent) {
entities.forEach {
it.get(ModelComponent::class).hidden = false
}
}
}
}
| 0 | Kotlin | 0 | 0 | d03efa79f546169a50082eb3a956b8f5d4623be7 | 1,817 | poc-android-tv | MIT License |
src/main/kotlin/fr/spacefox/calvinandbot/repository/LuceneWriteRepository.kt | SpaceFox | 405,756,166 | false | {"Kotlin": 54454} | package fr.spacefox.calvinandbot.repository
import fr.spacefox.calvinandbot.model.Strip
import fr.spacefox.calvinandbot.model.StripToLuceneDocMapper
import fr.spacefox.calvinandbot.util.LoggerDelegate
import org.apache.lucene.index.IndexWriter
import org.apache.lucene.index.IndexWriterConfig
import org.slf4j.Logger
class LuceneWriteRepository : AutoCloseable {
companion object {
val log: Logger by LoggerDelegate()
}
private val repository = LuceneRepository()
private val config: IndexWriterConfig = IndexWriterConfig(repository.analyzer)
private val writer: IndexWriter = IndexWriter(repository.directory, config)
override fun close() {
writer.close()
repository.close()
}
fun save(strip: Strip): Strip {
val doc = StripToLuceneDocMapper.toDoc(strip)
if (log.isDebugEnabled) {
log.debug("Save to Lucene : $doc")
}
writer.addDocument(doc)
return strip
}
fun commit() {
writer.flush()
writer.commit()
}
fun clearAll() {
writer.deleteAll()
commit()
writer.deleteUnusedFiles()
}
}
| 0 | Kotlin | 0 | 0 | 963d639bd3c2d68d36094d0d19a13494e9af6504 | 1,157 | calvinandbot | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.