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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
graphics/src/main/kotlin/dev/brella/kornea/fx/graphics/ConfigurableExtensions.kt | UnderMybrella | 527,415,026 | false | null | package dev.brella.kornea.fx.graphics
import dev.brella.kornea.fx.base.Configurable
import javafx.scene.Node
import javafx.scene.layout.BorderPane
public inline fun <T : Node> BorderPane.center(configurable: Configurable<T>, block: T.() -> Unit) {
center = configurable(block)
} | 0 | Kotlin | 0 | 0 | a5d6a4cff7e8dee3fb48a39e24670179f4aeb91c | 284 | kornea-fx | MIT License |
app/src/test/java/com/github/takahirom/hiltsample/PlayerFragmentTest.kt | takahirom | 302,200,470 | false | null | package com.github.takahirom.hiltsample
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import androidx.annotation.StyleRes
import androidx.core.util.Preconditions
import androidx.fragment.app.Fragment
import androidx.fragment.app.testing.FragmentScenario
import androidx.room.Room
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import dagger.hilt.android.testing.UninstallModules
import dagger.hilt.components.SingletonComponent
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@HiltAndroidTest
@UninstallModules(DataModule::class)
@RunWith(RobolectricTestRunner::class)
class PlayerFragmentTest {
@InstallIn(SingletonComponent::class)
@Module
class TestDataModule {
@Provides
fun provideVideoDatabase(): VideoDatabase {
return Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
VideoDatabase::class.java
).build()
}
}
@get:Rule
var hiltAndroidRule = HiltAndroidRule(this)
@Before
fun setup() {
hiltAndroidRule.inject()
}
@Test
fun play() {
launchFragmentInHiltContainerInInstrumentation<PlayerFragment> {
onView(withText("playing")).check(matches(isDisplayed()))
}
}
}
inline fun <reified T : Fragment> launchFragmentInHiltContainerInInstrumentation(
fragmentArgs: Bundle? = null,
@StyleRes themeResId: Int = R.style.AppTheme,
crossinline action: Fragment.() -> Unit = {}
) {
val startActivityIntent = Intent.makeMainActivity(
ComponentName(
ApplicationProvider.getApplicationContext(),
HiltTestActivity::class.java
)
).putExtra(FragmentScenario.EmptyFragmentActivity.THEME_EXTRAS_BUNDLE_KEY, themeResId)
ActivityScenario.launch<HiltTestActivity>(startActivityIntent).onActivity { activity ->
val fragment: Fragment = activity.supportFragmentManager.fragmentFactory.instantiate(
Preconditions.checkNotNull(T::class.java.classLoader),
T::class.java.name
)
fragment.arguments = fragmentArgs
activity.supportFragmentManager
.beginTransaction()
.add(android.R.id.content, fragment, "")
.commitNow()
fragment.action()
}
} | 0 | Kotlin | 1 | 7 | f54e58d72057e8d81921fa0d4e3bcfe809e9c5b9 | 2,879 | hilt-sample-app | Apache License 2.0 |
command-line/src/test/kotlin/MainTest.kt | waveduke | 709,454,938 | false | {"Kotlin": 54407, "TypeScript": 7810} | import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import testing.*
import java.io.File
class MainTest {
@TempDir
lateinit var tempDir: File
@Tag(TestTags.END_TO_END)
@Test
fun main() {
val inputFileContent = getResourceContent("Input.ts")
val testPaths = TestPaths.createTestPaths(tempDir)
testPaths.setupDirectories(inputFileContent = inputFileContent)
val expectedOutputFileContent = getResourceContent("Output.kt")
val arguments = testPaths.getCommandLineArguments()
main(arguments)
val actualOutputFileContent = getFileContent(filePath = testPaths.outputDirectory)
assertEquals(expectedOutputFileContent, actualOutputFileContent)
}
} | 0 | Kotlin | 0 | 0 | e82a163718b01ed78ad937912d3c7a2458e7b08f | 840 | ttk | Apache License 2.0 |
app/src/main/java/com/semisonfire/cloudgallery/utils/FileUtils.kt | Semyon100116907 | 132,183,724 | false | null | package com.semisonfire.cloudgallery.utils
import android.app.Application
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
object FileUtils {
lateinit var application: Application
lateinit var fileProvider: ExternalFileProvider
/**
* Create temp file to share.
*/
fun createShareFile(bitmap: Bitmap): Uri {
val uri = getLocalFileUri("share_image_" + System.currentTimeMillis())
saveFile(uri, bitmap)
return uri
}
fun savePublicFile(bitmap: Bitmap, fileName: String): String {
val publicDirectory = File(
fileProvider.publicDirectory,
"CloudGallery"
)
if (!publicDirectory.exists()) {
publicDirectory.mkdir()
}
val index = fileName.lastIndexOf('.')
val name = fileName.substring(0, index)
val extension = fileName.substring(index)
val file = createPublicFile(publicDirectory, name, extension, 0)
saveFile(file, bitmap)
return file.absolutePath
}
/**
* Create file in public external directory.
*/
private fun createPublicFile(
directory: File,
name: String,
extension: String,
counter: Int
): File {
val newName: String = if (counter != 0) "$name($counter)" else name
val file = File(directory, newName + extension)
if (file.exists()) {
return createPublicFile(directory, name, extension, counter + 1)
}
try {
file.createNewFile()
} catch (e: IOException) {
e.printStackTrace()
}
return file
}
fun saveFile(uri: Uri, bitmap: Bitmap) {
saveFile(getFile(uri), bitmap)
}
fun saveFile(file: File, bitmap: Bitmap) {
var fileOutputStream: FileOutputStream? = null
try {
fileOutputStream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
} catch (e: FileNotFoundException) {
e.printStackTrace()
} finally {
try {
fileOutputStream?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
/**
* Get local file
*/
fun getFile(uri: Uri): File {
return fileProvider.getFile(uri)
}
/**
* Get local file uri with today`s date name
*/
val localFileUri: Uri
get() {
val time = "IMG_" + DateUtils.currentDate
return getLocalFileUri(time)
}
/**
* Get local file uri
*/
private fun getLocalFileUri(name: String): Uri {
val mediaStorageDir = fileProvider.privateDirectory
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdir()
}
val mediaFile = File(
mediaStorageDir.path + File.separator
+ if (name.endsWith(".png")) name else "$name.png"
)
return if (Build.VERSION.SDK_INT >= 24) {
fileProvider.getUri(application, mediaFile)
} else {
Uri.fromFile(mediaFile)
}
}
} | 0 | Kotlin | 0 | 1 | 59f8b94fdeaf8db0557deef84f1b25224ab768e4 | 3,296 | CloudGallery | MIT License |
mpchart/src/main/java/com/angcyo/chart/ScatterChartConfig.kt | angcyo | 229,037,684 | false | {"Kotlin": 3416972, "JavaScript": 5542, "HTML": 1598} | package com.angcyo.chart
import com.angcyo.library.L
import com.github.mikephil.charting.charts.Chart
import com.github.mikephil.charting.charts.ScatterChart
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.ScatterData
import com.github.mikephil.charting.data.ScatterDataSet
/**
* 分散/散列 图表配置
* Email:[email protected]
* @author angcyo
* @date 2020/04/10
* Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved.
*/
open class ScatterChartConfig : BaseChartConfig<Entry, ScatterDataSet>() {
override fun addDataSet(label: String?, action: ScatterDataSet.() -> Unit) {
if (entryList.isEmpty()) {
L.w("Entry为空, 请检查是否先调用了[addEntry].")
}
ScatterDataSet(entryList, label).apply {
configDataSet(this)
action()
addDataSet(this)
}
}
override fun addEntry(action: Entry.() -> Unit) {
entryList.add(Entry().apply(action))
}
var scatterDataConfig: (ScatterData) -> Unit = {}
override fun onSetChartData(chart: Chart<*>, dataSetList: List<ScatterDataSet>) {
chart.data = ScatterData(dataSetList).apply {
scatterDataConfig(this)
}
}
}
fun dslScatterChart(chart: Chart<*>?, action: ScatterChartConfig.() -> Unit = {}): ScatterChart? {
chart?.apply {
ScatterChartConfig().also {
it.action()
it.doIt(chart)
}
}
return chart as? ScatterChart?
} | 0 | Kotlin | 4 | 4 | 7c9000a117a0b405c17d19a067874413c52042ba | 1,475 | UICoreEx | MIT License |
v2-model-enumeration/src/commonMain/kotlin/com/bselzer/gw2/v2/model/enumeration/ArmorWeight.kt | Woody230 | 388,820,096 | false | {"Kotlin": 750899} | package com.bselzer.gw2.v2.model.enumeration
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class ArmorWeight {
@SerialName("Heavy")
HEAVY,
@SerialName("Medium")
MEDIUM,
@SerialName("Light")
LIGHT,
@SerialName("Clothing")
CLOTHING
} | 2 | Kotlin | 0 | 2 | 7bd43646f94d1e8de9c20dffcc2753707f6e455b | 323 | GW2Wrapper | Apache License 2.0 |
src/test/kotlin/no/nav/tms/varseltekst/monitor/coalesce/rules/UtvidetSykepengerRuleTest.kt | navikt | 552,751,202 | false | {"Kotlin": 98858, "Dockerfile": 259} | package no.nav.tms.varseltekst.monitor.coalesce.rules
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import org.junit.jupiter.api.Test
class UtvidetSykepengerRuleTest {
@Test
fun `Matcher passende tekst`() {
val tekst = "<NAME> har søkt om utvidet støtte fra NAV angående sykepenger til deg."
UtvidetSykepengerRule.ruleApplies(tekst) shouldBe true
}
@Test
fun `Matcher ikke annen tekst`() {
val tekst = "Du har fått et brev som du må lese: Brev om trekt 18 års søknad. Les brevet i dokumentarkivet. Hvis du ikke åpner og leser dokumentet, vil vi sende det til deg i posten."
UtvidetSykepengerRule.ruleApplies(tekst) shouldBe false
}
@Test
fun `Bytter ut passende tekst`() {
val tekst = "<NAME> har søkt om utvidet støtte fra NAV angående sykepenger til deg."
val expected = "<arbeidssted> har søkt om utvidet støtte fra NAV angående sykepenger til deg."
val coalescedTekst = UtvidetSykepengerRule.applyRule(tekst)
coalescedTekst shouldNotBe tekst
coalescedTekst shouldBe expected
}
@Test
fun `Bytter ikke ut annen tekst`() {
val tekst = "Vi minner om at du har et videomøte"
UtvidetSykepengerRule.applyRule(tekst) shouldBe tekst
}
}
| 0 | Kotlin | 0 | 0 | 084e95a585758df48ddb14e262052b40d812a5df | 1,307 | tms-varseltekst-monitor | MIT License |
DailyMovie/app/src/main/java/com/example/dailymovie/models/MovieOfTheDay.kt | jesus33lcc | 794,693,138 | false | {"Kotlin": 55973, "Java": 5856} | package com.example.dailymovie.models
data class MovieOfTheDay(
val title: String,
val rating: Double,
val review: String,
val date: String,
val author: String,
val posterPath: String
)
| 0 | Kotlin | 0 | 0 | 135bcf1bf35433c827ab1b0bcd09150bb8c3dc58 | 211 | DailyMovie | MIT License |
desktop/app/src/main/kotlin/com/abdownloadmanager/desktop/pages/home/HomeWindow.kt | amir1376 | 825,187,044 | false | {"Kotlin": 967280, "Shell": 3811} | package com.abdownloadmanager.desktop.pages.home
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.window.WindowPlacement
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.rememberWindowState
import com.abdownloadmanager.desktop.actions.LocalShortCutManager
import com.abdownloadmanager.desktop.actions.handle
import com.abdownloadmanager.desktop.ui.customwindow.CustomWindow
import com.abdownloadmanager.desktop.ui.customwindow.rememberWindowController
import com.abdownloadmanager.desktop.ui.icon.MyIcons
import com.abdownloadmanager.desktop.utils.mvi.HandleEffects
import java.awt.Dimension
@Composable
fun HomeWindow(
homeComponent: HomeComponent,
onCLoseRequest: () -> Unit,
) {
val size by homeComponent.windowSize.collectAsState()
val windowState = rememberWindowState(
size = size,
position = WindowPosition.Aligned(Alignment.Center)
)
val onCloseRequest = onCLoseRequest
val windowTitle = "AB Download Manager"
val windowIcon = MyIcons.appIcon
val windowController = rememberWindowController(
windowTitle,
windowIcon.rememberPainter(),
)
CompositionLocalProvider(
LocalShortCutManager provides homeComponent.shortcutManager
) {
CustomWindow(
state = windowState,
onCloseRequest = onCloseRequest,
windowController = windowController,
onKeyEvent = {
homeComponent.shortcutManager.handle(it)
}
) {
LaunchedEffect(windowState.size) {
if (!windowState.isMinimized && windowState.placement == WindowPlacement.Floating) {
homeComponent.setWindowSize(windowState.size)
}
}
window.minimumSize = Dimension(
400, 400
)
HandleEffects(homeComponent) {
when (it) {
HomeEffects.BringToFront -> {
windowState.isMinimized = false
window.toFront()
}
else -> {}
}
}
BoxWithConstraints {
HomePage(homeComponent)
}
}
}
} | 31 | Kotlin | 16 | 721 | 34801da12e8ae1e0a7e4cec5b75a62c6d3b2d265 | 2,366 | ab-download-manager | Apache License 2.0 |
Dictionary/app/src/main/java/com/zsx/dictionary/ui/dictionary2/Dictionary2Fragment.kt | BennyZhang-Canviz | 255,919,665 | false | null | package com.zsx.dictionary.ui.dictionary2
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.zsx.dictionary.adapter.Dictionary2Adapter
import com.zsx.dictionary.databinding.FragmentDictionary2Binding
import com.zsx.dictionary.util.InjectorUtils
import com.zsx.dictionary.util.SoftInputHelper
import com.zsx.dictionary.viewmodel.Dictionary2ViewModel
import kotlinx.android.synthetic.main.fragment_dictionary2.*
class Dictionary2Fragment : Fragment() {
private val dictionary2ViewModel: Dictionary2ViewModel by viewModels {
InjectorUtils.provideDictionary2ViewModelFactory()
}
private lateinit var dictionary2Adapter: Dictionary2Adapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
var binding = FragmentDictionary2Binding.inflate(inflater,container,false)
dictionary2Adapter = Dictionary2Adapter()
binding.tvDictionary1.adapter = dictionary2Adapter
dictionary2ViewModel.dictionary2Entity.observe(viewLifecycleOwner, Observer {
dictionary2Adapter.submitList(it)
})
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button_search.setOnClickListener{
var keyword = et_search_keyword.text.toString()
if(keyword.isNotEmpty()){
dictionary2ViewModel.getDictionary2(keyword)
}
SoftInputHelper.hideSoftInput(requireContext(),it)
}
}
}
| 0 | Kotlin | 0 | 0 | 55ae049d5c880b67251e40cf658c4535d52cd017 | 1,804 | Android | Apache License 2.0 |
src/main/kotlin/model/Book.kt | okaryo | 390,533,957 | false | null | package model
import kotlinx.serialization.Serializable
@Serializable
data class Book(
val title: String,
val author: Author,
val page: Int,
val url: String?,
)
| 2 | Kotlin | 0 | 1 | 554619ac394d184abcee6ec10ea4365c50962330 | 179 | BookMeterRecordScraping | MIT License |
client/src/main/kotlin/builder/PermaLink.kt | attrib | 113,712,441 | false | null | package builder
import index.LZString
import kotlinx.serialization.stringFromUtf8Bytes
import kotlinx.serialization.toUtf8Bytes
import ltd2.Build
import ltd2.PermaLinkV1
object PermaLinkV1JS {
fun toPermaLinkCode(build: Build): String {
val str = PermaLinkV1.toPermaLinkCode(build).map { it.toChar() }.joinToString("")
return LZString.compressToBase64("1_$str")
}
fun fromPermaLinkCode(code: String) : Build {
val str = LZString.decompressFromBase64(code)
val codeId = str[0]
if( codeId!='1') {
throw IllegalArgumentException("Illegal code id $codeId")
}
return PermaLinkV1.fromPermaLinkCode(str.substring(2).map { it.toByte() }.toByteArray())
}
} | 7 | Kotlin | 0 | 1 | eeaaad013235b0aebebb9fa47c2c5c1c7f5459cb | 733 | legion2-builder | FSF All Permissive License |
app/src/main/java/com/nik/mycar/viewmodels/CarViewModelFactory.kt | brav3t | 295,171,778 | false | null | package com.nik.mycar.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.nik.mycar.data.CarDao
import java.lang.IllegalArgumentException
class CarViewModelFactory(
private val carDao: CarDao
) :ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if(modelClass.isAssignableFrom(CarViewModel::class.java)) {
return CarViewModel(carDao) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
} | 0 | Kotlin | 0 | 0 | 98428d92539de3303983ad61c93ae15500c8aa0d | 576 | myCar | MIT License |
musicPlay/src/main/java/com/tobery/musicplay/PlayConfig.kt | Tobeyr1 | 508,699,099 | false | null | package com.tobery.musicplay
import android.os.Bundle
import com.lzx.starrysky.notification.INotification
import com.tobery.musicplay.notification.MusicNotificationManager.Companion.CUSTOM_NOTIFICATION_FACTORY
import com.tobery.musicplay.notification.MusicNotificationConfig
import com.tobery.musicplay.notification.MusicNotificationManager
import com.tobery.musicplay.util.GlideImageLoader
import com.tobery.musicplay.util.printLog
data class PlayConfig(
var defaultNotificationSwitch: Boolean = true, //通知栏开关
var notificationType: Int = INotification.CUSTOM_NOTIFICATION, //通知栏类型 1系统 2 自定义
var isOpenCache: Boolean = true, // 开启cache
var cacheFilePath: String = "musicStarrySkyCache",
var cacheByteNum: Long = 1024 * 1024 * 1024,
var isAutoManagerFocus: Boolean = false, //是否自动处理焦点
var defaultImageLoader: GlideImageLoader = GlideImageLoader(), //默认glide框架
var defaultPermissionIntercept: PermissionInterceptor = PermissionInterceptor(),
var notificationClass: String = "com.tobery.app.MainActivity",
var factory: MusicNotificationManager.NotificationFactory = CUSTOM_NOTIFICATION_FACTORY,
var defaultNotificationConfig: MusicNotificationConfig = MusicNotificationConfig.create {
targetClass { "com.tobery.musicplay.NotificationReceiver" }
targetClassBundle {
val bundle = Bundle()
bundle.putString("title", "我是点击通知栏转跳带的参数")
"当前切换是否成功$notificationClass".printLog()
bundle.putString("targetClass", notificationClass)
//参数自带当前音频播放信息,不用自己传
return@targetClassBundle bundle
}
smallIconRes {
-1
}
pendingIntentMode { MusicNotificationConfig.MODE_BROADCAST }
}
)
| 0 | Kotlin | 0 | 0 | c15665880e3d2cc261b838b9b8400802e243b803 | 1,741 | MusicPlayManager | Apache License 2.0 |
app/src/main/java/io/marlon/cleanarchitecture/ui/mvp/login/LoginContract.kt | marloncarvalho | 110,142,579 | false | null | package io.marlon.cleanarchitecture.ui.mvp.login
import io.marlon.cleanarchitecture.ui.mvp.ErrorView
import io.marlon.cleanarchitecture.ui.mvp.LoadingView
interface LoginContract {
interface Presenter : io.marlon.cleanarchitecture.ui.mvp.Presenter<View> {
fun login(username: String, password: String)
}
interface View : io.marlon.cleanarchitecture.ui.mvp.View, ErrorView, LoadingView {
}
} | 0 | Kotlin | 0 | 0 | 613153498ffb28813652526a5a829ed64f71a1fa | 420 | android-clean-architecture | MIT License |
src/main/kotlin/com/yumeal/algorithm/UserProfile.kt | AlexandreMELIN | 865,574,461 | false | {"Kotlin": 16176} | package com.yumeal.algorithm
import com.yumeal.food.PositiveQuantity
data class UserProfile(val targetBodyweightInKilogram: PositiveQuantity, val targetCalories: PositiveQuantity, val proteinPerBodyweightKilogram: PositiveQuantity, val carbsPerBodyweightKilogram: PositiveQuantity, val fatPerBodyweightKilogram: PositiveQuantity){
val targetProtein = targetBodyweightInKilogram * proteinPerBodyweightKilogram
val targetCarbs = targetBodyweightInKilogram * carbsPerBodyweightKilogram
}
| 0 | Kotlin | 0 | 0 | dd42c0aea73ff69d7afd1ab9e76067753ee49102 | 496 | Yumeal | Apache License 2.0 |
domain/src/main/java/com/comit/domain/usecase/holiday/FetchHolidaysUseCase.kt | Team-ComIT | 511,156,689 | false | null | package com.comit.domain.usecase.holiday
import com.comit.domain.repository.HolidayRepository
import javax.inject.Inject
class FetchHolidaysUseCase @Inject constructor(
private val repository: HolidayRepository,
) {
suspend operator fun invoke(
startAt: String,
endAt: String,
status: String,
) = kotlin.runCatching {
repository.fetchHolidays(
startAt = startAt,
endAt = endAt,
status = status,
)
}
}
| 2 | Kotlin | 0 | 31 | 48293d51264908cc2f1ece572bf42c8c2f93880d | 496 | SimTong-Android | Apache License 2.0 |
src/main/kotlin/me/stylite/predator/Config.kt | melmsie | 258,000,181 | false | null | package me.stylite.predator
import java.io.FileInputStream
import java.util.Properties
object Config {
private val conf = Properties().apply { load(FileInputStream("config.properties")) }
operator fun get(key: String) = conf.getProperty(key)?.takeIf { it.isNotEmpty() }
?: throw IllegalStateException("$key is missing or was empty in config.properties!")
val prefix = this["prefix"].split(", ")
val token = this["token"]
val apiKey = this["apiKey"]
//val dblKey = this["dblkey"]
}
| 1 | Kotlin | 1 | 4 | f7828ac759742094c0ab220235d9b4c76261577d | 517 | apexbot | MIT License |
app/src/main/java/com/adityakamble49/wordlist/di/scope/PerActivity.kt | adityakamble49 | 131,319,368 | false | null | package com.adityakamble49.wordlist.di.scope
import javax.inject.Scope
/**
* Dagger scope for per activity
*
* @author <NAME>
* @since 4/4/2018
*/
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class PerActivity
| 2 | Kotlin | 1 | 2 | ea1f7cf58574b4a87dbe689cbf9ce69610b1718d | 230 | word-list | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/AssistiveListeningSystems.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.AssistiveListeningSystems: ImageVector
get() {
if (_assistiveListeningSystems != null) {
return _assistiveListeningSystems!!
}
_assistiveListeningSystems = Builder(name = "AssistiveListeningSystems", defaultWidth =
512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight =
24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(3.0f, 22.5f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
close()
moveTo(8.5f, 14.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(1.439f, 17.561f)
lineToRelative(5.0f, 5.0f)
lineToRelative(2.121f, -2.121f)
lineTo(3.561f, 15.439f)
lineToRelative(-2.121f, 2.121f)
close()
moveTo(19.099f, 0.125f)
lineToRelative(-1.197f, 2.75f)
curveToRelative(1.438f, 0.626f, 2.577f, 1.762f, 3.209f, 3.198f)
lineToRelative(2.746f, -1.207f)
curveToRelative(-0.936f, -2.13f, -2.625f, -3.813f, -4.758f, -4.741f)
close()
moveTo(15.237f, 12.999f)
curveToRelative(0.492f, -0.551f, 0.763f, -1.261f, 0.763f, -1.999f)
curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f)
reflectiveCurveToRelative(-3.0f, 1.346f, -3.0f, 3.0f)
horizontalLineToRelative(3.0f)
lineToRelative(2.237f, 1.999f)
close()
moveTo(12.882f, 3.001f)
curveToRelative(-4.42f, 0.064f, -7.882f, 3.578f, -7.882f, 7.999f)
horizontalLineToRelative(3.0f)
curveToRelative(0.0f, -2.764f, 2.164f, -4.959f, 4.925f, -4.999f)
curveToRelative(1.341f, -0.059f, 2.624f, 0.491f, 3.584f, 1.438f)
reflectiveCurveToRelative(1.49f, 2.212f, 1.49f, 3.561f)
curveToRelative(0.0f, 1.001f, -0.296f, 1.965f, -0.856f, 2.791f)
curveToRelative(-0.77f, 1.134f, -1.144f, 2.347f, -1.144f, 3.709f)
curveToRelative(0.0f, 2.298f, -2.012f, 3.5f, -4.0f, 3.5f)
verticalLineToRelative(3.0f)
curveToRelative(3.991f, 0.0f, 7.0f, -2.794f, 7.0f, -6.5f)
curveToRelative(0.0f, -0.763f, 0.193f, -1.387f, 0.625f, -2.024f)
curveToRelative(0.899f, -1.324f, 1.375f, -2.872f, 1.375f, -4.476f)
curveToRelative(0.0f, -2.158f, -0.847f, -4.182f, -2.384f, -5.697f)
reflectiveCurveToRelative(-3.593f, -2.302f, -5.734f, -2.302f)
close()
}
}
.build()
return _assistiveListeningSystems!!
}
private var _assistiveListeningSystems: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,093 | icons | MIT License |
src/test/kotlin/dev/bogwalk/batch6/Problem69Test.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch6
import kotlin.test.Test
import kotlin.test.assertEquals
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import dev.bogwalk.util.tests.Benchmark
import dev.bogwalk.util.tests.compareSpeed
import dev.bogwalk.util.tests.getSpeed
import kotlin.math.pow
internal class TotientMaximumTest {
private val tool = TotientMaximum()
@ParameterizedTest(name="N = {0}")
@CsvSource(
// lower constraints
"3, 2", "5, 2", "10, 6", "15, 6", "20, 6", "25, 6", "31, 30",
// mid constraints
"100, 30", "200, 30", "399, 210", "450, 210", "1000, 210", "6000, 2310", "100000, 30030"
)
fun `correct for lower & mid constraints`(n: Long, expected: Long) {
assertEquals(expected, tool.maxTotientRatio(n))
assertEquals(expected, tool.maxTotientRatioPrimorial(n))
}
@Test
fun `maxTotientRatio speed`() {
val n = 1_000_000L
val expected = 510_510L
val solutions = mapOf(
"Totient" to tool::maxTotientRatio, "Primorial" to tool::maxTotientRatioPrimorial
)
val speeds = mutableListOf<Pair<String, Benchmark>>()
for ((name, solution) in solutions) {
getSpeed(solution, n).run {
speeds.add(name to second)
assertEquals(expected, first)
}
}
compareSpeed(speeds)
}
@Test
fun `maxTotientRatioPrimorial correct when N is max n`() {
val n = 614_889_782_588_491_410 // max n less than N = 1e18
val expected = 13_082_761_331_670_030
assertEquals(expected, tool.maxTotientRatioPrimorial(n))
}
@Test
fun `correct for upper constraints`() {
val expected = listOf(
223_092_870, 200_560_490_130, 304_250_263_527_210, 614_889_782_588_491_410
)
for ((i, e) in (9..18 step 3).withIndex()) {
val n = (10.0).pow(e).toLong()
assertEquals(expected[i], tool.maxTotientRatioPrimorial(n))
}
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,056 | project-euler-kotlin | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Videovertical.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.bold
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.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup
public val BoldGroup.Videovertical: ImageVector
get() {
if (_videovertical != null) {
return _videovertical!!
}
_videovertical = Builder(name = "Videovertical", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(6.36f, 7.7813f)
horizontalLineTo(2.0f)
verticalLineTo(11.2512f)
horizontalLineTo(6.36f)
verticalLineTo(7.7813f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(6.3584f, 6.2889f)
verticalLineTo(2.1289f)
curveTo(4.0784f, 2.5489f, 2.5884f, 4.0189f, 2.1484f, 6.2789f)
horizontalLineTo(6.3284f)
curveTo(6.3384f, 6.2789f, 6.3484f, 6.2889f, 6.3584f, 6.2889f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(6.36f, 16.31f)
verticalLineTo(12.75f)
horizontalLineTo(2.0f)
verticalLineTo(16.28f)
horizontalLineTo(6.24f)
curveTo(6.28f, 16.28f, 6.32f, 16.3f, 6.36f, 16.31f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.8494f, 6.2797f)
curveTo(21.4194f, 4.0897f, 20.0194f, 2.6497f, 17.8594f, 2.1797f)
verticalLineTo(6.2797f)
horizontalLineTo(21.8494f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.3594f, 11.25f)
verticalLineTo(2.01f)
curveTo(16.3094f, 2.0f, 16.2494f, 2.0f, 16.1894f, 2.0f)
horizontalLineTo(7.8594f)
verticalLineTo(11.25f)
horizontalLineTo(16.3594f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.9994f, 12.75f)
horizontalLineTo(17.8594f)
verticalLineTo(16.28f)
horizontalLineTo(21.9994f)
verticalLineTo(12.75f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.8594f, 21.8212f)
curveTo(19.9994f, 21.3512f, 21.3994f, 19.9313f, 21.8394f, 17.7812f)
horizontalLineTo(17.8594f)
verticalLineTo(21.8212f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(6.2402f, 17.7817f)
horizontalLineTo(2.1602f)
curveTo(2.6202f, 20.0017f, 4.1002f, 21.4517f, 6.3602f, 21.8717f)
verticalLineTo(17.7617f)
curveTo(6.3202f, 17.7717f, 6.2802f, 17.7817f, 6.2402f, 17.7817f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.9994f, 7.7813f)
horizontalLineTo(17.8594f)
verticalLineTo(11.2512f)
horizontalLineTo(21.9994f)
verticalLineTo(7.7813f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.8594f, 12.75f)
verticalLineTo(22.0f)
horizontalLineTo(16.1894f)
curveTo(16.2494f, 22.0f, 16.3094f, 22.0f, 16.3594f, 21.99f)
verticalLineTo(12.75f)
horizontalLineTo(7.8594f)
close()
}
}
.build()
return _videovertical!!
}
private var _videovertical: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 6,256 | VuesaxIcons | MIT License |
src/main/kotlin/elan/tweaks/common/gui/component/TickingUIComponent.kt | Kiwi233 | 423,036,713 | true | {"Kotlin": 130451} | package elan.tweaks.common.gui.component
interface TickingUIComponent: UIComponent {
fun onTick(partialTicks: Float, context: UIContext)
}
| 0 | Kotlin | 0 | 0 | e8bf4694dc72a328fa11e36b51da7316ab3c933c | 144 | thaumcraft-research-tweaks | MIT License |
app/src/main/java/com/realform/macropaytestpokemon/presentation/ui/login/LoginViewModel.kt | IvanMedinaH | 809,257,969 | false | {"Kotlin": 211857} | package com.realform.macropaytestpokemon.presentation.ui.login
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseAuth
private const val LOGINVIEWMODEL = "VIEWMODEL"
class LoginViewModel(private val auth: FirebaseAuth) : ViewModel() {
private val _email = mutableStateOf("")
val email: State<String> get() = _email
private val _password = mutableStateOf("")
val password: State<String> get() = _password
private val _isLoginSuccess = mutableStateOf(false)
val isLoginSuccess: State<Boolean> get() = _isLoginSuccess
public fun ChallengeLogin(usr: String, psswrd: String) {
_email.value = usr
_password.value = <PASSWORD>
Log.d(TAG, _email.value + " " + _password.value)
Login()
}
fun Login(){
auth.signInWithEmailAndPassword(_email.value, _password.value)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val user = auth.currentUser
Log.d(TAG, "signInWithEmail:success {${user?.email}}")
_isLoginSuccess.value=true
} else {
Log.w(TAG, "signInWithEmail:failure", task.exception)
_isLoginSuccess.value=false
}
}
}
} | 0 | Kotlin | 0 | 0 | d6bdc416600f99f80af5264db420929796e109b2 | 1,419 | Pokedex | MIT License |
src/main/java/me/shadowalzazel/mcodyssey/tasks/dragon_tasks/LightningCloudTask.kt | ShadowAlzazel | 511,383,377 | false | {"Kotlin": 896208} | package me.shadowalzazel.mcodyssey.tasks.dragon_tasks
import org.bukkit.Particle
import org.bukkit.entity.AreaEffectCloud
import org.bukkit.entity.EnderDragon
import org.bukkit.entity.EntityType
import org.bukkit.entity.Player
import org.bukkit.scheduler.BukkitRunnable
class LightningCloudTask(private val dragon: EnderDragon, private val cloud: AreaEffectCloud) : BukkitRunnable() {
override fun run() {
if (cloud.isDead) {
this.cancel()
return
}
val ground = cloud.location.clone()
ground.getNearbyEntities(7.0, 6.0, 7.0).forEach {
if (it is Player) {
it.world.spawnEntity(it.location, EntityType.LIGHTNING_BOLT)
it.damage(5.0, dragon)
it.world.spawnParticle(Particle.EXPLOSION, it.location, 1, 0.0, 0.0, 0.0)
it.world.spawnParticle(Particle.ELECTRIC_SPARK, it.location, 25, 0.5, 0.2, 0.5)
}
}
}
} | 0 | Kotlin | 0 | 3 | 56937309af3317e768bfc220b3f7ee700a67ad73 | 964 | MinecraftOdyssey | MIT License |
app/src/main/kotlin/com/keygenqt/mylibrary/data/db/DbServiceOther.kt | keygenqt | 308,420,685 | false | null | /*
* Copyright 2020 Vitaliy Zarubin
*
* 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.keygenqt.mylibrary.data.db
import com.keygenqt.mylibrary.base.BaseSharedPreferences
import com.keygenqt.mylibrary.data.RoomDatabase
import com.keygenqt.mylibrary.data.dao.ModelRootDao
import com.keygenqt.mylibrary.data.dao.ModelUserDao
import com.keygenqt.mylibrary.data.models.ModelUser
import com.keygenqt.mylibrary.hal.*
import com.keygenqt.mylibrary.utils.API_VERSION
class DbServiceOther(
val db: RoomDatabase,
val preferences: BaseSharedPreferences,
) {
fun userId(): Long? {
return preferences.userId
}
fun uid(): String {
return preferences.uid
}
fun setBaseUserData(id: Long, token: String) {
preferences.userId = id
preferences.token = token
}
fun getModelUserDao(): ModelUserDao {
return db.getDao()
}
fun getModelRootDao(): ModelRootDao {
return db.getDao()
}
fun getUrlMessageToken(): Link {
return getModelRootDao().findModel(API_VERSION).getLink(API_KEY_MESSAGE_TOKEN)
}
fun getUrlUser(): Link {
return getModelRootDao().findModel(API_VERSION).getLink(ModelUser.API_KEY)
}
fun getUrlLogin(): Link {
return getModelRootDao().findModel(API_VERSION).getLink(API_KEY_LOGIN)
}
fun getUrlJoin(): Link {
return getModelRootDao().findModel(API_VERSION).getLink(API_KEY_JOIN)
}
fun getUrlPassword(): Link {
return getModelRootDao().findModel(API_VERSION).getLink(API_KEY_PASSWORD)
}
fun getUserMe(): ModelUser? {
db.getDao<ModelUserDao>().let { dao ->
preferences.userId?.let { userId ->
dao.findModel(userId).let { model ->
return model
}
}
}
return null
}
} | 0 | Kotlin | 0 | 0 | da819fdabbd3545a8be00ffbaf35520f64cc344a | 2,373 | MyLibrary-android | Apache License 2.0 |
app/src/main/java/com/linkjf/climita/di/DataModule.kt | linkjf | 683,250,481 | false | null | package com.linkjf.climita.di
import com.linkjf.climita.data.repository.ForecastRepositoryImp
import com.linkjf.climita.data.repository.LocationSearchRepositoryImp
import com.linkjf.climita.domain.repository.ForecastRepository
import com.linkjf.climita.domain.repository.LocationSearchRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DataModule {
@Provides
@Singleton
fun provideLocationSearchRepository(
locationSearchRepository: LocationSearchRepositoryImp
): LocationSearchRepository =
locationSearchRepository
@Provides
@Singleton
fun provideForecastRepository(
forecastRepository: ForecastRepositoryImp
): ForecastRepository =
forecastRepository
}
| 0 | Kotlin | 0 | 0 | 4106c139f9247639d2c3e870b8386f53eabf811b | 889 | climita | Apache License 2.0 |
app/src/main/java/com/looktabinc/feature/mypage/HistoryAdapter.kt | Looktab-naer | 568,419,392 | false | null | package com.looktabinc.feature.mypage
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.looktabinc.R
import com.looktabinc.databinding.ItemReviewBinding
import com.looktabinc.feature.model.ReviewHistory
class HistoryAdapter :
ListAdapter<ReviewHistory, HistoryAdapter.BrandViewHolder>(HistoryComparator) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BrandViewHolder {
return BrandViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_review, parent,
false)
)
}
override fun onBindViewHolder(holder: BrandViewHolder, position: Int) {
holder.bind(getItem(position))
}
inner class BrandViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val binding: ItemReviewBinding? =
androidx.databinding.DataBindingUtil.bind(itemView)
fun bind(item: ReviewHistory) {
binding?.item = item
//
// binding?.layout?.setOnClickListener {
// mListener?.onItemClick(item.id)
// }
}
}
interface OnItemClickListener {
fun onItemClick(id: Int)
}
private var mListener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener?) {
mListener = listener
}
}
object HistoryComparator : DiffUtil.ItemCallback<ReviewHistory>() {
override fun areItemsTheSame(
oldItem: ReviewHistory,
newItem: ReviewHistory
): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(
oldItem: ReviewHistory,
newItem: ReviewHistory
): Boolean {
return oldItem == newItem
}
} | 0 | Kotlin | 0 | 0 | 77c9d1672509fa52b680d742da1d698dc3665d10 | 1,927 | android | MIT License |
kotlin-mui-icons/src/main/generated/mui/icons/material/ChildFriendly.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ChildFriendly")
package mui.icons.material
@JsName("default")
external val ChildFriendly: SvgIconComponent
| 12 | Kotlin | 5 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 190 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/kssidll/arru/ui/component/dialog/FuzzySearchableListDialog.kt | KSSidll | 655,360,420 | false | {"Kotlin": 1021398} | package com.kssidll.arru.ui.component.dialog
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
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.Row
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.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ShapeDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import com.kssidll.arru.R
import com.kssidll.arru.data.data.ProductWithAltNames
import com.kssidll.arru.domain.data.Data
import com.kssidll.arru.domain.data.loadedData
import com.kssidll.arru.domain.data.loadedEmpty
import com.kssidll.arru.domain.data.searchSort
import com.kssidll.arru.ui.component.field.StyledOutlinedTextField
import com.kssidll.arru.ui.component.field.styledTextFieldColorDefaults
import com.kssidll.arru.ui.component.list.BaseClickableListItem
import com.kssidll.arru.ui.theme.ArrugarqTheme
import com.kssidll.arru.ui.theme.Typography
/**
* @param T: Type of the item, needs to implement FuzzySearchSource
* @param onDismissRequest: Function called when the user tries to dismiss the Dialog by clicking outside. This is also called when the Add/'+' button is clicked
* @param items: Items to be displayed in the list
* @param itemText: Transformation used to determine what to display on the item card
* @param onItemClick: Function called when an item is clicked
* @param showAddButton: Whether to show an Add/'+' button in the search field
* @param onAddButtonClick: Function called when the Add/'+' button is clicked. Provides searched for value at the time of the event as parameter
* @param addButtonDescription: Description for the Add/'+' button icon
* @param showDefaultValueItem: Whether to show a default, null value item under the search field
* @param defaultItemText: String to display on the default, null value item
* @param shape: Shape of the Dialog
* @param calculateScore function to use to calculate the score of an item which determines the order of the items
*/
@Composable
fun <T> SearchableListDialog(
onDismissRequest: () -> Unit,
items: Data<List<T>>,
itemText: (T) -> String,
onItemClick: ((T?) -> Unit)? = null,
onItemClickLabel: String? = null,
onItemLongClick: ((T) -> Unit)? = null,
onItemLongClickLabel: String? = null,
showAddButton: Boolean = true,
onAddButtonClick: ((query: String) -> Unit)? = null,
addButtonDescription: String? = null,
showDefaultValueItem: Boolean = false,
defaultItemText: String = String(),
shape: Shape = ShapeDefaults.ExtraLarge,
calculateScore: (item: T, query: String) -> Int
) {
var query: String by remember {
mutableStateOf(String())
}
var displayedItems: List<T> by remember {
mutableStateOf(listOf())
}
Dialog(onDismissRequest = onDismissRequest) {
Surface(
modifier = Modifier
.width(400.dp)
.height(600.dp),
shape = shape,
color = MaterialTheme.colorScheme.surface,
tonalElevation = 1.dp,
) {
AnimatedVisibility(
visible = items.loadedEmpty(),
enter = fadeIn(),
exit = fadeOut(),
) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 4.dp)
) {
Text(
text = stringResource(id = R.string.no_data_to_display_text),
textAlign = TextAlign.Center,
style = Typography.titleMedium,
)
}
}
AnimatedVisibility(
visible = items.loadedData(),
enter = fadeIn(),
exit = fadeOut(),
) {
if (items is Data.Loaded) {
LaunchedEffect(
items,
query
) {
displayedItems = if (query.isNotBlank()) items.data.searchSort {
calculateScore(
it,
query
)
} else items.data
}
Column {
LazyColumn(
modifier = Modifier.weight(1f),
reverseLayout = true,
) {
items(items = displayedItems) {
BaseClickableListItem(
text = itemText(it),
onClick = {
onItemClick?.invoke(it)
},
onClickLabel = onItemClickLabel,
onLongClick = {
onItemLongClick?.invoke(it)
},
onLongClickLabel = onItemLongClickLabel,
)
HorizontalDivider()
}
}
if (showDefaultValueItem) {
HorizontalDivider()
BaseClickableListItem(
onClick = {
onItemClick?.invoke(null)
},
onClickLabel = onItemClickLabel,
text = defaultItemText
)
}
Box(modifier = Modifier.background(MaterialTheme.colorScheme.surface)) {
StyledOutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(top = 6.dp),
singleLine = true,
value = query,
onValueChange = {
query = it
},
textStyle = TextStyle.Default.copy(
color = MaterialTheme.colorScheme.onSurface,
fontSize = 16.sp
),
label = {
Text(
text = stringResource(R.string.search),
fontSize = 16.sp,
)
},
colors = styledTextFieldColorDefaults(
focusedIndicator = Color.Transparent,
unfocusedIndicator = Color.Transparent,
),
trailingIcon = {
if (showAddButton) {
IconButton(
onClick = {
onDismissRequest()
onAddButtonClick?.invoke(query)
}
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = addButtonDescription,
modifier = Modifier.size(40.dp)
)
}
}
}
)
}
}
}
}
}
}
}
@PreviewLightDark
@Composable
private fun FuzzySearchableListDialogPreview() {
ArrugarqTheme {
Surface(modifier = Modifier.fillMaxSize()) {
SearchableListDialog(
onDismissRequest = {},
items = Data.Loaded(ProductWithAltNames.generateList()),
itemText = { "test" },
calculateScore = { _, _ -> 0 }
)
}
}
}
@PreviewLightDark
@Composable
private fun EmptyFuzzySearchableListDialogPreview() {
ArrugarqTheme {
Surface(modifier = Modifier.fillMaxSize()) {
SearchableListDialog(
onDismissRequest = {},
items = Data.Loaded(emptyList<ProductWithAltNames>()),
itemText = { "test" },
calculateScore = { _, _ -> 0 }
)
}
}
} | 3 | Kotlin | 1 | 38 | 19906cc3e517ec30849f6ab33be83315cd45918b | 10,666 | Arru | BSD 3-Clause Clear License |
examples/src/tl/telegram/stories/StoriesStories.kt | andreypfau | 719,064,910 | false | {"Kotlin": 62942} | // This file is generated by TLGenerator.kt
// Do not edit manually!
package tl.telegram.stories
import io.github.andreypfau.tl.serialization.TLCombinatorId
import kotlin.jvm.JvmName
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import tl.telegram.Chat
import tl.telegram.StoryItem
import tl.telegram.User
@Serializable
@SerialName("stories.stories")
@TLCombinatorId(0x5DD8C3C8)
public data class StoriesStories(
@get:JvmName("count")
public val count: Int,
@get:JvmName("stories")
public val stories: List<StoryItem>,
@get:JvmName("chats")
public val chats: List<Chat>,
@get:JvmName("users")
public val users: List<User>,
) {
public companion object
}
| 0 | Kotlin | 0 | 1 | 16de3f335d8005e35543cb7515a810fd9ac4236d | 727 | tl-kotlin | MIT License |
app/src/main/java/com/sayaradz/views/activities/ModelsActivity.kt | sayaradz | 170,285,633 | false | null | package com.sayaradz.views.activities
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.preference.PreferenceManager
import androidx.recyclerview.selection.SelectionPredicates
import androidx.recyclerview.selection.SelectionTracker
import androidx.recyclerview.selection.StorageStrategy
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
import com.sayaradz.R
import com.sayaradz.models.Model
import com.sayaradz.models.Version
import com.sayaradz.viewModels.*
import com.sayaradz.views.MyChosenModelLookup
import com.sayaradz.views.MyItemKeyProvider
import com.sayaradz.views.adapters.ModelChooseComposeCarAdapter
import com.sayaradz.views.adapters.ModelsRecyclerViewAdapter
import com.sayaradz.views.adapters.VersionChooseComposeCarAdapter
import com.sayaradz.views.fragments.dialog_fragments.ComposeModelDialogFragment
import com.sayaradz.views.fragments.dialog_fragments.ComposeVersionDialogFragment
import kotlinx.android.synthetic.main.activity_models.*
import kotlinx.android.synthetic.main.versions_models_view.*
class ModelsActivity : AppCompatActivity(), ModelsRecyclerViewAdapter.OnItemClickListener,
ComposeModelDialogFragment.ComposeDialogListener, ComposeVersionDialogFragment.ComposeDialogListener,
ModelChooseComposeCarAdapter.SelectModelListener, VersionChooseComposeCarAdapter.SelectVersionListener {
private lateinit var fAButton: ExtendedFloatingActionButton
private lateinit var titleTextView: TextView
private lateinit var mBrandViewModel: BrandViewModel
private lateinit var mAvailableModelsViewModel: AvailableModelsViewModel
private lateinit var mAvailableVersionsViewModel: AvailableVersionsViewModel
private lateinit var mFollowModelViewModel: FollowModelViewModel
private lateinit var mUnFollowModelViewModel: UnfollowModelViewModel
private lateinit var mIsModelFollowedViewModel: IsModelFollowedViewModel
// RecyclerView
private lateinit var modelsRecyclerView: RecyclerView
private lateinit var modelsRecyclerViewAdapter: ModelsRecyclerViewAdapter
private lateinit var noInternetTextView: TextView
private lateinit var contentNestedScrollView: NestedScrollView
private lateinit var progressBar: ProgressBar
private lateinit var brandLogo: String
private var versionList: List<Version>? = null
private lateinit var modelList: List<Model>
private lateinit var chosenModel: Model
private lateinit var chosenVersion: Version
private lateinit var recyclerPopulatedVersionsViewAdapter: VersionChooseComposeCarAdapter
private lateinit var tracker: SelectionTracker<Long>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_models)
val actionbar = supportActionBar
//set actionbar title
actionbar!!.title = this.intent.getStringExtra("brandName")
//set back button
actionbar.setDisplayHomeAsUpEnabled(true)
brandLogo = this.intent.getStringExtra("brandLogo")
modelsRecyclerView = models_recycler_view
titleTextView = models_text_view
fAButton = floatingActionButton
contentNestedScrollView = content_view
noInternetTextView = no_internet
progressBar = progress_bar
fAButton.visibility = View.GONE
}
override fun onResume() {
super.onResume()
mBrandViewModel = ViewModelProviders.of(
this,
viewModelFactory { BrandViewModel(this.intent.getStringExtra("brandId")) }
).get(BrandViewModel::class.java)
mBrandViewModel.loadingVisibility.observe(this, Observer { progressBar ->
progressBar?.let {
this.progressBar.visibility = it
}
})
mBrandViewModel.internetErrorVisibility.observe(this, Observer { internet ->
internet?.let {
noInternetTextView.visibility = it
}
})
mBrandViewModel.contentViewVisibility.observe(this, Observer { content ->
content?.let {
contentNestedScrollView.visibility = it
}
})
mBrandViewModel.modelLiveData.observe(this, Observer { brandsResponse ->
brandsResponse?.let {
modelsRecyclerViewAdapter = ModelsRecyclerViewAdapter(it.models)
modelsRecyclerView.adapter = modelsRecyclerViewAdapter
modelsRecyclerViewAdapter.setOnItemClickListener(this)
fAButton.visibility = View.VISIBLE
}
})
contentNestedScrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { v, _, scrollY, _, oldScrollY ->
if (scrollY > oldScrollY) {
//scroll down
fAButton.shrink(true)
}
if (scrollY < oldScrollY) {
//scroll up
if (!fAButton.isShown) fAButton.visibility = View.VISIBLE
else fAButton.extend(true)
}
if (scrollY == 0) {
//top scroll
fAButton.visibility = View.VISIBLE
}
if (scrollY == v.getChildAt(0).measuredHeight - v.measuredHeight) {
// end of the scroll view
fAButton.visibility = View.GONE
}
})
val mLayoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
modelsRecyclerView.layoutManager = mLayoutManager
modelsRecyclerView.itemAnimator = DefaultItemAnimator()
modelsRecyclerView.isNestedScrollingEnabled = false
fAButton.setOnClickListener {
val builder = ComposeModelDialogFragment()
builder.show(supportFragmentManager, "ComposeModelDialogFragment")
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onItemClick(view: View, obj: Model, position: Int) {
val intent = Intent(view.context, VersionsActivity::class.java)
intent.putExtra("model", obj)
intent.putExtra("brandLogo", brandLogo)
startActivity(intent)
}
override fun onFollowButtonClick(view: View, obj: Model, position: Int) {
val imageView = view as ImageView
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val id = prefs.getString("id", "")!!
if (imageView.drawable.constantState == getDrawable(R.drawable.ic_follow)!!.constantState) {
mFollowModelViewModel = ViewModelProviders.of(
this,
viewModelFactory { FollowModelViewModel() }
).get(FollowModelViewModel::class.java)
mFollowModelViewModel.getData(id, obj.id!!)
mFollowModelViewModel.fol.observe(this, Observer { brandsResponse ->
brandsResponse?.let {
imageView.setImageResource(R.drawable.ic_followed)
if (it) Toast.makeText(
this,
"Follow attribuer avec succés!",
Toast.LENGTH_SHORT
).show()
else {
Toast.makeText(this, "Follow echoué!! ", Toast.LENGTH_SHORT).show()
imageView.setImageResource(R.drawable.ic_follow)
}
}
})
} else {
mUnFollowModelViewModel = ViewModelProviders.of(
this,
viewModelFactory { UnfollowModelViewModel() }
).get(UnfollowModelViewModel::class.java)
mUnFollowModelViewModel.getData(id, obj.id!!)
Toast.makeText(
this,
"UnFollow attribuer avec succés!",
Toast.LENGTH_SHORT
).show()
imageView.setImageResource(R.drawable.ic_follow)
}
}
override fun isFollowed(id: String): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val userId = prefs.getString("id", "")!!
var boolea = false
mIsModelFollowedViewModel = ViewModelProviders.of(
this,
viewModelFactory { IsModelFollowedViewModel(userId, id) }
).get(IsModelFollowedViewModel::class.java)
mIsModelFollowedViewModel.brandLiveData.observe(this, Observer { brandsResponse ->
brandsResponse?.let {
boolea = it.following!!
}
})
return boolea
}
override fun onPopulateVersions(recyclerView: RecyclerView) {
val mLayoutManager =
LinearLayoutManager(recyclerView.context.applicationContext, LinearLayoutManager.HORIZONTAL, false)
recyclerView.layoutManager = mLayoutManager
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.isNestedScrollingEnabled = false
recyclerPopulatedVersionsViewAdapter = VersionChooseComposeCarAdapter(versionList)
recyclerView.adapter = recyclerPopulatedVersionsViewAdapter
val tracker = SelectionTracker.Builder(
"mySelection",
recyclerView,
MyItemKeyProvider(recyclerView),
MyChosenModelLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(
SelectionPredicates.createSelectSingleAnything()
).build()
recyclerPopulatedVersionsViewAdapter.tracker = tracker
recyclerPopulatedVersionsViewAdapter.setOnItemClickListener(this)
}
override fun onPopulateModels(
recyclerView: RecyclerView,
dialog: DialogFragment,
progressBar: ProgressBar,
noInternet: TextView,
content: ConstraintLayout
) {
progressBar.visibility = View.VISIBLE
content.visibility = View.INVISIBLE
mAvailableModelsViewModel = ViewModelProviders.of(
dialog,
viewModelFactory { AvailableModelsViewModel(this.intent.getStringExtra("brandId")) }
).get(AvailableModelsViewModel::class.java)
mAvailableModelsViewModel.loadingVisibility.observe(dialog, Observer { progress ->
progress?.let {
progressBar.visibility = it
}
})
mAvailableModelsViewModel.internetErrorVisibility.observe(dialog, Observer { internet ->
internet?.let {
noInternet.visibility = it
}
})
mAvailableModelsViewModel.contentViewVisibility.observe(dialog, Observer { internet ->
internet?.let {
content.visibility = it
}
})
mAvailableModelsViewModel.availableModelsLiveData.observe(dialog, Observer { brandsResponse ->
brandsResponse?.let {
modelList = it
val recyclerViewAdapter = ModelChooseComposeCarAdapter(modelList)
recyclerView.adapter = recyclerViewAdapter
(dialog as ComposeModelDialogFragment).adapter = recyclerViewAdapter
tracker = SelectionTracker.Builder(
"mySelection",
recyclerView,
MyItemKeyProvider(recyclerView),
MyChosenModelLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(
SelectionPredicates.createSelectSingleAnything()
).build()
recyclerViewAdapter.tracker = tracker
recyclerViewAdapter.setOnItemClickListener(this)
ComposeModelDialogFragment.invoke(recyclerViewAdapter, dialog as ComposeModelDialogFragment)
}
})
val mLayoutManager =
LinearLayoutManager(recyclerView.context.applicationContext, LinearLayoutManager.HORIZONTAL, false)
recyclerView.layoutManager = mLayoutManager
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.isNestedScrollingEnabled = false
}
override fun onSelectModel(modelPosition: Int) {
chosenModel = modelList[modelPosition]
}
override fun onSelectVersion(versionPosition: Int) {
chosenVersion = versionList!![versionPosition]
}
override fun onNextClick(
dialog: DialogFragment,
progressBar: ProgressBar,
noInternet: TextView,
content: ConstraintLayout
) {
mAvailableVersionsViewModel = ViewModelProviders.of(
dialog,
viewModelFactory { AvailableVersionsViewModel(chosenModel.id.toString()) }
).get(AvailableVersionsViewModel::class.java)
progressBar.visibility = View.VISIBLE
content.visibility = View.INVISIBLE
mAvailableVersionsViewModel.internetErrorVisibility.observe(dialog, Observer { internet ->
internet?.let {
noInternet.visibility = it
if (it == View.VISIBLE)
progressBar.visibility = View.INVISIBLE
}
})
mAvailableVersionsViewModel.availableVersionsLiveData.observe(dialog, Observer { brandsResponse ->
brandsResponse?.let {
versionList = it
val builder = ComposeVersionDialogFragment()
builder.show(supportFragmentManager, "ComposeVersionDialogFragment")
val timer = object : CountDownTimer(200, 100) {
override fun onTick(p0: Long) {
}
override fun onFinish() {
dialog.dismiss()
}
}
timer.start()
}
})
}
override fun onConfirmComposeClick(dialog: DialogFragment) {
val intent = Intent(this, CarComposingActivity::class.java)
intent.putExtra("model", chosenModel)
intent.putExtra("version", chosenVersion)
startActivity(intent)
}
private inline fun <VM : ViewModel> viewModelFactory(crossinline f: () -> VM) =
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(aClass: Class<T>): T = f() as T
}
}
| 0 | Kotlin | 1 | 2 | 15d54c6e9c959fafdd84703dbf63ae9245aa08ce | 14,994 | sayaradz_android | MIT License |
app/src/main/java/com/tans/tasciiartplayer/AppGlobalCoroutineScope.kt | Tans5 | 793,945,539 | false | {"Kotlin": 195703} | package com.tans.tasciiartplayer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
/**
* never cancel.
*/
val appGlobalCoroutineScope = CoroutineScope(Dispatchers.IO) | 0 | Kotlin | 0 | 2 | 921b492c2553a3b50c3142a2ba30743aace0750d | 199 | tAsciiArtPlayer | Apache License 2.0 |
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/arrows/ArrowDownDoubleLine.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.remix.remix.arrows
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.ArrowsGroup
public val ArrowsGroup.ArrowDownDoubleLine: ImageVector
get() {
if (_arrowDownDoubleLine != null) {
return _arrowDownDoubleLine!!
}
_arrowDownDoubleLine = Builder(name = "ArrowDownDoubleLine", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 19.164f)
lineTo(18.207f, 12.957f)
lineTo(16.793f, 11.543f)
lineTo(12.0f, 16.336f)
lineTo(7.207f, 11.543f)
lineTo(5.793f, 12.957f)
lineTo(12.0f, 19.164f)
close()
moveTo(12.0f, 13.514f)
lineTo(18.207f, 7.307f)
lineTo(16.793f, 5.893f)
lineTo(12.0f, 10.686f)
lineTo(7.207f, 5.893f)
lineTo(5.793f, 7.307f)
lineTo(12.0f, 13.514f)
close()
}
}
.build()
return _arrowDownDoubleLine!!
}
private var _arrowDownDoubleLine: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 1,938 | compose-icon-collections | MIT License |
Usability/Named Default Arguments/Exercise 3/src/Task.kt | marchdz | 633,862,396 | false | null | // NamedAndDefaultArgs/Task3.kt
package namedAndDefaultArgumentsExercise3
import atomictest.eq
fun joinComments(s: String): String =
s.trimMargin(marginPrefix = "// ").replace("\n", "; ")
fun main() {
val s = """
// First
// Second
// Third
"""
joinComments(s) eq "First; Second; Third"
} | 0 | Kotlin | 0 | 0 | 0246a342b54600ceb6ac38ecb4498d16a7e86e8e | 328 | atomic-kotlin-exercises | MIT License |
idea/testData/intentions/specifyTypeExplicitly/overrideNotNullFunction.kt | JakeWharton | 99,388,807 | false | null | // IGNORE_FIR
// CHOOSE_NULLABLE_TYPE_IF_EXISTS
// WITH_RUNTIME
interface Base {
fun notNullFun(): String
}
class Tesst : Base {
override fun notNullFun()<caret> = java.lang.String.valueOf("")
}
| 0 | null | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 204 | kotlin | Apache License 2.0 |
src/test/kotlin/dsl/wiremock/stubs/StubResponseTest.kt | valentin-goncharov | 447,352,842 | false | {"Kotlin": 208558} | package dsl.wiremock.stubs
import com.github.tomakehurst.wiremock.junit5.WireMockTest
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.client.statement.HttpResponse
import io.ktor.http.HttpStatusCode.Companion.Created
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
@WireMockTest(httpPort = 9090)
@ExperimentalCoroutinesApi
internal class StubResponseTest: BaseStubTest() {
@Test
fun `request body should be equal to string`() {
get {
url equalTo "/simple"
} returns {
status = 201
headers contain "ETag" equalTo "1234567890"
body string "OK"
}
runTest {
val response: HttpResponse = client.get<HttpStatement>("http://localhost:9090/simple").execute()
Assertions.assertThat(response.status).isEqualTo(Created)
Assertions.assertThat(response.headers.get("ETag")).isEqualTo("1234567890")
Assertions.assertThat(response.receive<String>()).isEqualTo("OK")
}
}
} | 2 | Kotlin | 0 | 0 | ad0aac9ce014a6f53c51c0e1aedb846414358b8d | 1,187 | wiremock-kotlin-dsl | Apache License 2.0 |
checker/src/test/kotlin/com/dickow/chortlin/checker/test/TraceEqualityTests.kt | Dickow | 138,721,545 | false | {"Kotlin": 142028, "Java": 2441} | package com.dickow.chortlin.checker.test
import com.dickow.chortlin.checker.choreography.participant.ObservableParticipant
import com.dickow.chortlin.checker.trace.Invocation
import com.dickow.chortlin.checker.trace.Return
import com.dickow.chortlin.checker.trace.TraceEvent
import com.dickow.chortlin.checker.trace.value.StringValue
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
class TraceEqualityTests {
@Test
fun `check equality of trace classes`() {
val p_m = ObservableParticipant("p", "m")
val strInputValue = StringValue("HELLO")
val invocation1 = Invocation(p_m, strInputValue)
val invocation2 = Invocation(p_m, strInputValue)
val return1 = Return(p_m, strInputValue, strInputValue)
val return2 = Return(p_m, strInputValue, strInputValue)
assertEquals(invocation1, invocation2)
assertNotEquals<TraceEvent>(invocation1, return1)
assertEquals(return1, return2)
assertEquals(return1.hashCode(), return2.hashCode())
assertEquals(invocation1.hashCode(), invocation2.hashCode())
}
} | 1 | Kotlin | 1 | 2 | e43986f3f84de8f7b565557f77e1c7d2676b5c76 | 1,134 | chortlin | MIT License |
app/src/main/java/moe/tlaster/openween/activity/MainActivity.kt | OpenWeen | 69,312,077 | false | null | package moe.tlaster.openween.activity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import com.benny.library.kbinding.bind.BindingDisposer
import com.benny.library.kbinding.viewmodel.ViewModel
import moe.tlaster.openween.R
import moe.tlaster.openween.view.MainPage
import moe.tlaster.openween.viewmodel.MainViewModel
import org.jetbrains.anko.linearLayout
import org.jetbrains.anko.recyclerview.v7.recyclerView
import com.benny.library.kbinding.view.setContentView
class MainActivity : BaseActivity() {
override val viewModel: ViewModel = MainViewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MainPage().setContentView(this).bindTo(viewModel)
}
}
| 3 | Kotlin | 1 | 11 | 9ace2dd55be92979561b6ec8f6c4fde8f3c045d3 | 784 | OpenWeen.Droid | MIT License |
src/test/kotlin/functional/IntegrationTests.kt | katielevy1 | 257,449,557 | true | {"Kotlin": 7120, "HTML": 5516, "Dockerfile": 226} | package functional
import functional.users.User
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToFlux
import reactor.test.test
class IntegrationTests {
private val application = Application(8181)
private val client = WebClient.create("http://localhost:8181")
@BeforeAll
fun beforeAll() {
application.start()
}
@Test
fun `Find all users on via users endpoint`() {
client.get().uri("/api/users")
.accept(APPLICATION_JSON)
.retrieve()
.bodyToFlux<User>()
.test()
.expectNextMatches { it.firstname == "carmine" && it.lastname == "d" }
.expectNextMatches { it.firstname == "eliana" && it.lastname == "g" }
.expectNextMatches { it.firstname == "laura" && it.lastname == "h" }
.verifyComplete()
}
@AfterAll
fun afterAll() {
application.stop()
}
} | 0 | null | 0 | 0 | 737592abedea5281e461e36fdb8e71d7a2168901 | 1,169 | kotlin-openapi-spring-functional-template | Apache License 2.0 |
modules/log/src/androidTest/kotlin/com/handtruth/kommon/AndroidLogTest.kt | handtruth | 258,808,258 | false | null | package com.handtruth.kommon
import kotlin.test.Test
import kotlin.test.assertTrue
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class AndroidLogTest {
data class SomeData(val name: String, val id: Int, val float: Double)
@Test
fun useLog() {
val datas = listOf(
SomeData("Popka", 32, 56.98),
SomeData("Kek", 34435, .0),
SomeData("Very Long Name", 23, 2.2)
)
val log = Log.default("Application", lvl = LogLevel.Debug)
log.info { "it is working!" }
log.debug(datas, SomeData::name, SomeData::id, SomeData::float) { "A table out" }
}
@Test
fun testMark() {
val builder = StringBuilder()
val log = AppendableLog(builder, "TAG")
log.info { "Hello World!".here }
assertTrue(
builder.toString().startsWith("TAG [info]: Hello World! at (AndroidLogTest.kt:"),
builder.toString()
)
}
}
| 0 | Kotlin | 0 | 0 | bd45aaa38b968e69674e7071418903f7e3f79d55 | 1,020 | kommon | MIT License |
goblin-core/src/main/java/org/goblinframework/core/config/MappingLocationScannerMXBean.kt | xiaohaiz | 206,246,434 | false | null | package org.goblinframework.core.config
import java.lang.management.PlatformManagedObject
interface MappingLocationScannerMXBean : PlatformManagedObject {
fun getConfigPath(): String?
} | 0 | null | 6 | 9 | b1db234912ceb23bdd81ac66a3bf61933b717d0b | 191 | goblinframework | Apache License 2.0 |
src/util/image/opencvMat/MatBitwiseUtil.kt | JBWills | 291,822,812 | false | null | package util.image.opencvMat
import coordinate.Point
import org.opencv.core.Core
import org.opencv.core.Mat
import org.opencv.core.Scalar
fun Mat.bitwiseOr(other: Mat): Mat = applyWithDest { src, dest ->
Core.bitwise_or(src, other, dest)
}
fun Mat.bitwiseAnd(other: Mat): Mat = applyWithDest { src, dest ->
Core.bitwise_and(src, other, dest)
}
fun Mat.bitwiseNot(other: Mat): Mat = applyWithDest { src, dest ->
Core.bitwise_not(src, other, dest)
}
fun Mat.subtract(other: Mat): Mat = applyWithDest { src, dest ->
Core.subtract(src, other, dest)
}
fun Mat.subtract(value: Double): Mat = applyWithDest { src, dest ->
Core.subtract(src, Scalar(value), dest)
}
fun Mat.bitwiseNot(): Mat = applyWithDest { src, dest ->
Core.bitwise_not(src, dest)
}
fun Mat.bitwiseXor(other: Mat): Mat = applyWithDest { src, dest ->
Core.bitwise_xor(src, other, dest)
}
fun Mat.copyTo(other: Mat, offset: Point): Mat {
val offset = offset.map { it.toInt() }
val newMat = other.clone()
val matToPasteBounds = bounds
val boundsOnNewMat = (matToPasteBounds + offset).boundsIntersection(newMat.bounds)
if (boundsOnNewMat == null || boundsOnNewMat.area == 0.0) return newMat
val clippedMatToPaste = submat(boundsOnNewMat - offset)
clippedMatToPaste.copyTo(newMat.submat(boundsOnNewMat))
return newMat
}
| 0 | Kotlin | 0 | 0 | df4d6efb8d463374fd1a9053db6a4bd089591a2a | 1,321 | processing-sketches | MIT License |
src/main/java/com/github/ai/kpdiff/entity/FieldEntity.kt | aivanovski | 607,687,384 | false | null | package com.github.ai.kpdiff.entity
import java.util.UUID
data class FieldEntity(
override val uuid: UUID,
val entryUid: UUID,
val name: String,
val value: String
) : DatabaseEntity | 0 | Kotlin | 0 | 0 | 0842084a5dc69b86b513b50ca8739263e0abe81e | 199 | kp-diff | Apache License 2.0 |
app/src/main/java/ac/uk/hope/osmviewerjetpack/data/network/musicbrainz/model/TagNetwork.kt | movedaccount-droid | 796,686,976 | false | {"Kotlin": 153945, "TeX": 15257} | package ac.uk.hope.osmviewerjetpack.data.network.musicbrainz.model
import kotlinx.serialization.Serializable
// this doesn't have a local model because tags don't have a central id of any kind,
// but we need to have a network object anyway to catch them before embedding them
// i miss serde...
@Serializable
data class TagNetwork(
val name: String,
val count: Int
)
fun List<TagNetwork>.toLocal() = associateBy({it.name}, {it.count}) | 0 | Kotlin | 0 | 0 | 74c785bdf9eb6b2b3e3be78fae1024469f16b8d9 | 447 | osmviewerjetpack2 | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/housq/sunnyweather/logic/dao/PlaceDao.kt | HousqLove | 262,533,921 | false | null | package com.housq.sunnyweather.logic.dao
import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import com.google.gson.Gson
import com.housq.sunnyweather.SunnyWeatherApplication
import com.housq.sunnyweather.logic.model.Place
object PlaceDao {
fun savePlace(place: Place) {
sharedPreferences().edit {
putString("place", Gson().toJson(place))
}
}
fun getSavedPlace(): Place {
val string = sharedPreferences().getString("place", "")
return Gson().fromJson(string, Place::class.java)
}
fun isSaved() = sharedPreferences().contains("place")
private fun sharedPreferences() =
SunnyWeatherApplication.context.getSharedPreferences("sunnt_weather", Context.MODE_PRIVATE)
} | 0 | Kotlin | 0 | 0 | 5c05b01f468727ebfb26320cf39ae4c7999f7339 | 797 | SunnyWeather | Apache License 2.0 |
plugin-build/plugin/src/main/java/com/github/hervian/gradle/plugins/SetApiVersionExtension.kt | Hervian | 654,717,020 | false | null | package com.github.hervian.gradle.plugins
import org.gradle.api.Project
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Optional
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
/*import org.gradle.internal.impldep.org.joda.time.Instant
import org.gradle.internal.impldep.org.joda.time.format.ISODateTimeFormat*/
import javax.inject.Inject
const val DEFAULT_OUTPUT_FILE = "version.txt"
const val DEFAULT_NEW_API_FILE = "openapi.json"
const val DEFAULT_OLD_API_FILE = "/old/openapi.json"
@Suppress("UnnecessaryAbstractClass")
abstract class SetApiVersionExtension @Inject constructor(project: Project) {
private val objects = project.objects
var acceptableDiffLevel: Property<SemVerDif> = objects.property(SemVerDif::class.java).convention(SemVerDif.MINOR)
var oldApi: RegularFileProperty = objects.fileProperty().convention(
project.layout.buildDirectory.file(DEFAULT_OLD_API_FILE),
)
var newApi: RegularFileProperty = objects.fileProperty().convention(
project.layout.buildDirectory.file(DEFAULT_NEW_API_FILE),
)
@Optional
var versionSuffix: Property<String> = objects.property(String::class.java).convention(
"+" + DateTimeFormatter.ofPattern("yyyyMMdd.HHmmss").withZone(ZoneId.systemDefault()).format(Instant.now()),
)
val versionFile: RegularFileProperty = objects.fileProperty().convention(
project.layout.buildDirectory.file(DEFAULT_OUTPUT_FILE),
)
}
| 0 | Kotlin | 0 | 0 | 79b003e61356ae92e99a79a06bfbc4e5968ec6ed | 1,551 | setversion-gradle-plugin | MIT License |
core/src/main/java/com/sagar/core/animation/Animator.kt | sagar-viradiya | 345,684,249 | false | null | package com.sagar.core.animation
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.os.Build
import androidx.annotation.RequiresApi
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
/**
* Await on animation start. It will take care of removing listener if coroutine gets cancelled.
*/
suspend fun Animator.awaitStart() = suspendCancellableCoroutine<Unit> { cont ->
val listener = getAnimatorListener(
onStart = {
cont.resume(Unit)
}
)
addListener(listener)
cont.invokeOnCancellation { removeListener(listener) }
}
/**
* Await on animation pause. It will take care of removing listener if coroutine gets cancelled
* or animation gets cancelled.
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
suspend fun Animator.awaitPause() = suspendCancellableCoroutine<Unit> { cont ->
val listener = getAnimatorListener(
onEnd = { isEndedSuccessfully ->
if (cont.isActive && !isEndedSuccessfully) {
cont.cancel()
}
},
onPause = {
cont.resume(Unit)
}
)
addListener(listener)
addPauseListener(listener)
cont.invokeOnCancellation { cancel() }
}
/**
* Await on animation resume. It will take care of removing listener if coroutine gets cancelled
* or animation gets cancelled.
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
suspend fun Animator.awaitResume() = suspendCancellableCoroutine<Unit> { cont ->
val listener = getAnimatorListener(
onEnd = { isEndedSuccessfully ->
if (cont.isActive && !isEndedSuccessfully) {
cont.cancel()
}
},
onResume = {
cont.resume(Unit)
}
)
addListener(listener)
addPauseListener(listener)
cont.invokeOnCancellation { cancel() }
}
/**
* Await on animation end. It will take care of removing listener if coroutine gets cancelled
* or animation gets cancelled.
*/
suspend fun Animator.awaitEnd() = suspendCancellableCoroutine<Unit> { cont ->
addListener(
getAnimatorListener(
onEnd = { isEndedSuccessfully ->
if (cont.isActive) {
if (isEndedSuccessfully) {
cont.resume(Unit)
} else {
cont.cancel()
}
}
}
)
)
cont.invokeOnCancellation { cancel() }
}
private inline fun getAnimatorListener(
crossinline onEnd: (isEndedSuccessfully: Boolean) -> Unit = {},
crossinline onStart: () -> Unit = {},
crossinline onPause: () -> Unit = {},
crossinline onResume: () -> Unit = {}
): AnimatorListenerAdapter {
return object : AnimatorListenerAdapter() {
var endedSuccessfully = true
override fun onAnimationEnd(animator: Animator) {
animator.removeListener(this)
onEnd(endedSuccessfully)
}
override fun onAnimationCancel(animator: Animator) {
endedSuccessfully = false
}
override fun onAnimationStart(animator: Animator) = onStart()
override fun onAnimationPause(animation: Animator) = onPause()
override fun onAnimationResume(animation: Animator) = onResume()
}
}
| 1 | Kotlin | 7 | 171 | b9b0f40001f8ef3d3b59713d4f616d6c49f32292 | 3,330 | callback-ktx | Apache License 2.0 |
api-gen-runtime/src/commonMain/kotlin/sh/christian/ozone/api/model/Blob.kt | christiandeange | 611,550,055 | false | {"Kotlin": 432991, "Shell": 1139} | package sh.christian.ozone.api.model
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.cbor.ByteString
@OptIn(ExperimentalSerializationApi::class)
@SerialName("blob")
@Serializable
data class Blob(
@ByteString val ref: BlobRef,
val mimeType: String,
val size: Long,
)
@Serializable
data class BlobRef(
@SerialName("\$link")
val link: String,
)
| 0 | Kotlin | 4 | 26 | e14b2bc4a5df5d9557399109bccaba41b3850192 | 476 | ozone | MIT License |
SixKeeper/app/src/main/java/com/example/sixkeeper/CreateNewAccountManageFragmentsClass.kt | rynrsts | 389,328,372 | false | null | package com.example.sixkeeper
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
open class CreateNewAccountManageFragmentsClass : AppCompatActivity() {
private val createNewAccP1 = "createNewAccP1"
// private val createNewAccP2 = "createNewAccP2"
private val createNewAccP3 = "createNewAccP3"
private val createNewAccP4 = "createNewAccP4"
private val fragmentManager: FragmentManager = supportFragmentManager
private val createNewAccountP1Fragment: Fragment = CreateNewAccountP1Fragment()
// private val createNewAccountP2Fragment: Fragment = CreateNewAccountP2Fragment()
private val createNewAccountP3Fragment: Fragment = CreateNewAccountP3Fragment()
private val createNewAccountP4Fragment: Fragment = CreateNewAccountP4Fragment()
private var fragmentNum = 0
fun getCreateNewAccP1(): String {
return createNewAccP1
}
// fun getCreateNewAccP2(): String {
// return createNewAccP2
// }
fun getCreateNewAccP3(): String {
return createNewAccP3
}
fun getCreateNewAccP4(): String {
return createNewAccP4
}
fun getFragmentNum(): Int {
return fragmentNum
}
fun manageCreateNewAccFragments(selectedFragment: String) {
when (selectedFragment) {
createNewAccP1 -> { // First fragment
fragmentManager.beginTransaction().apply {
if (fragmentNum == 3) {
setCustomAnimations(
R.anim.anim_enter_left_to_right_1,
R.anim.anim_exit_left_to_right_1
)
}
replace(R.id.clCreateNewAccContainer, createNewAccountP1Fragment)
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
commit()
}
fragmentNum = 1
}
// TODO: Second Fragment
// createNewAccP2 -> { // Second fragment
// fragmentManager.beginTransaction().apply {
// if (fragmentNum == 1) {
// setCustomAnimations(
// R.anim.anim_enter_right_to_left_1,
// R.anim.anim_exit_right_to_left_1
// )
// } else if (fragmentNum == 3) {
// setCustomAnimations(
// R.anim.anim_enter_left_to_right_1,
// R.anim.anim_exit_left_to_right_1
// )
// }
//
// replace(R.id.clCreateNewAccContainer, createNewAccountP2Fragment)
// setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
// commit()
// }
//
// fragmentNum = 2
// }
createNewAccP3 -> { // Third fragment
fragmentManager.beginTransaction().apply {
if (fragmentNum == 1) {
setCustomAnimations(
R.anim.anim_enter_right_to_left_1,
R.anim.anim_exit_right_to_left_1
)
} else if (fragmentNum == 4) {
setCustomAnimations(
R.anim.anim_enter_left_to_right_1,
R.anim.anim_exit_left_to_right_1
)
}
replace(R.id.clCreateNewAccContainer, createNewAccountP3Fragment)
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
commit()
}
fragmentNum = 3
}
createNewAccP4 -> { // Fourth fragment
fragmentManager.beginTransaction().apply {
if (fragmentNum == 3) {
setCustomAnimations(
R.anim.anim_enter_right_to_left_1,
R.anim.anim_exit_right_to_left_1
)
}
replace(R.id.clCreateNewAccContainer, createNewAccountP4Fragment)
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
commit()
}
fragmentNum = 4
}
}
}
} | 0 | Kotlin | 1 | 2 | 85878f57b99b89bd7a11ab5d3cf8c7ac0c37ba15 | 4,831 | 6Keeper | MIT License |
src/main/kotlin/com/pineypiney/game_engine/GameEngine.kt | PineyPiney | 491,900,499 | false | null | package com.pineypiney.game_engine
import com.pineypiney.game_engine.resources.ResourcesLoader
import glm_.c
import glm_.f
import org.lwjgl.glfw.GLFW
abstract class GameEngine<E: GameLogicI>(final override val resourcesLoader: ResourcesLoader): GameEngineI<E> {
override val timer: Timer = Timer()
private var nextUpdateTime: Double = Timer.getCurrentTime()
private var FPSCounter: Int = 0
private val FPSInterval: Float = 1f
override var FPS: Float = 0f
init {
// Load the resources for the game
resourcesLoader.loadResources()
}
override fun run() {
init()
gameLoop()
cleanUp()
}
override fun init(){
timer.init()
activeScreen.init()
window.setFrameBufferResizeCallback { activeScreen.updateAspectRatio(window) }
setInputCallbacks()
}
override fun gameLoop(){
var frameTime: Double
var accumulator = 0.0
val interval: Float = 1f / TARGET_UPS
while (!window.shouldClose) {
// elapsed time is the time since this function was last called
frameTime = timer.tickFrame()
// accumulator adds up elapsed time
accumulator += frameTime
// Once the accumulator exceeds the interval, the game is updated
// and the accumulator reduces by interval amount.
// Advantage of doing it this way is that if there is lag, then the game will catch up with itself
while (accumulator >= interval) {
update(interval)
accumulator -= interval
}
input()
// Render screen regardless of the accumulator
render(accumulator / interval)
FPSCounter++
if(Timer.frameTime > nextUpdateTime){
updateFPS()
}
if (!window.vSync) {
// sync means that the game only runs game loops at the intended FPS
sync()
}
}
}
override fun setInputCallbacks(){
input.mouseMoveCallback = { screenPos, cursorOffset ->
activeScreen.onCursorMove(screenPos, cursorOffset)
}
input.mouseScrollCallback = { scrollOffset ->
activeScreen.onScroll(scrollOffset)
}
input.keyPressCallback = { bind, action ->
activeScreen.onInput(bind, action)
}
input.keyboardCharCallback = { codepoint ->
activeScreen.onType(codepoint.c)
}
}
override fun update(interval: Float) {
timer.tick()
activeScreen.update(interval, input)
}
override fun render(tickDelta: Double) {
activeScreen.render(window, tickDelta)
window.update()
}
override fun input(){
input.input()
}
override fun sync() {
val loopSlot = 1f / TARGET_FPS
val endTime: Double = Timer.frameTime + loopSlot
while (Timer.getCurrentTime() < endTime) {
try {
Thread.sleep(0, 100000)
}
catch (_: InterruptedException) {
}
}
}
fun updateFPS(){
FPS = FPSCounter.f / FPSInterval
FPSCounter = 0
nextUpdateTime = Timer.frameTime + FPSInterval
}
override fun cleanUp() {
resourcesLoader.cleanUp()
activeScreen.cleanUp()
GLFW.glfwTerminate()
}
} | 0 | Kotlin | 0 | 0 | d0cda448dfd2d34f15b8d0c0f4fe9fb24c0cc0cf | 3,444 | GameEngine | MIT License |
app/src/main/java/com/mati/miweather/ui/feature/MainViewModel.kt | mr-mati | 706,210,873 | false | {"Kotlin": 112355} | package com.mati.miweather.ui.feature
import android.os.Handler
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mati.miweather.data.model.CityForecast
import com.mati.miweather.data.model.CitysStatus
import com.mati.miweather.data.repository.DataStoreRepository
import com.mati.miweather.data.repository.NetworkRepository
import com.mati.miweather.util.USER_LANGUAGE
import com.mati.miweather.util.USER_THEME
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.util.Timer
import javax.inject.Inject
import kotlin.concurrent.timerTask
@HiltViewModel
class MainViewModel @Inject constructor(
private val repository: NetworkRepository,
private val dataStoreRepository: DataStoreRepository,
) : ViewModel() {
private val _city: MutableState<CityState> = mutableStateOf(CityState())
val city: State<CityState> = _city
private val _cityForecast: MutableState<ForecastState> = mutableStateOf(ForecastState())
val cityForecast: State<ForecastState> = _cityForecast
fun newData(cityName: String) {
viewModelScope.launch {
repository.newData(cityName, languageRead())
cityNameSave(cityName)
Timer().schedule(timerTask {
_city.value = CityState(repository.cityResponse)
_cityForecast.value = ForecastState(repository.forecastResponse)
}, 1000)
}
}
fun getData() {
viewModelScope.launch {
repository.newData(cityNameRead(), languageRead())
USER_LANGUAGE = languageRead()
USER_THEME = themeRead()
Handler().postDelayed({
if (repository.cityResponse?.id != null || repository.cityResponse?.id != null) {
_city.value = CityState(data = repository.cityResponse)
_cityForecast.value = ForecastState(data = repository.forecastResponse)
CityState(isLoading = false)
ForecastState(isLoading = false)
}
if (repository.cityError != null || repository.ForecastError != null) {
_city.value = CityState(error = repository.cityError!!)
_cityForecast.value = ForecastState(error = repository.ForecastError!!)
}
}, 2000)
}
}
private suspend fun cityNameSave(cityName: String) {
dataStoreRepository.saveCityName(cityName)
}
private suspend fun cityNameRead(): String = dataStoreRepository.readCityName()
fun languageSave(language: String) {
viewModelScope.launch {
dataStoreRepository.saveLanguage(language)
}
}
suspend fun languageRead(): String = dataStoreRepository.readLanguage()
fun themeSave(theme: String) {
viewModelScope.launch {
dataStoreRepository.saveTheme(theme)
}
}
suspend fun themeRead(): String = dataStoreRepository.readTheme()
}
data class CityState(
val data: CitysStatus? = null,
val error: String = " ",
var isLoading: Boolean = true,
)
data class ForecastState(
val data: CityForecast? = null,
val error: String = " ",
var isLoading: Boolean = true,
) | 0 | Kotlin | 0 | 5 | 8136f76fa3315b715e09f0417232a892d5de257c | 3,395 | Mi-Weather | MIT License |
java/kotlin/src/main/kotlin/ibc/core/channel/v1/MsgTimeoutOnCloseResponseKt.kt | dimitar-petrov | 575,395,653 | true | {"Git Config": 1, "Text": 1, "Ignore List": 3, "Makefile": 3, "Markdown": 3, "Gradle Kotlin DSL": 5, "INI": 2, "Shell": 3, "Batchfile": 1, "Java": 181, "Kotlin": 917, "JSON with Comments": 1, "JSON": 3, "Git Attributes": 1, "EditorConfig": 1} | //Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ibc/core/channel/v1/tx.proto
package ibc.core.channel.v1;
@kotlin.jvm.JvmSynthetic
inline fun msgTimeoutOnCloseResponse(block: ibc.core.channel.v1.MsgTimeoutOnCloseResponseKt.Dsl.() -> Unit): ibc.core.channel.v1.Tx.MsgTimeoutOnCloseResponse =
ibc.core.channel.v1.MsgTimeoutOnCloseResponseKt.Dsl._create(ibc.core.channel.v1.Tx.MsgTimeoutOnCloseResponse.newBuilder()).apply { block() }._build()
object MsgTimeoutOnCloseResponseKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
class Dsl private constructor(
@kotlin.jvm.JvmField private val _builder: ibc.core.channel.v1.Tx.MsgTimeoutOnCloseResponse.Builder
) {
companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: ibc.core.channel.v1.Tx.MsgTimeoutOnCloseResponse.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): ibc.core.channel.v1.Tx.MsgTimeoutOnCloseResponse = _builder.build()
}
}
@kotlin.jvm.JvmSynthetic
inline fun ibc.core.channel.v1.Tx.MsgTimeoutOnCloseResponse.copy(block: ibc.core.channel.v1.MsgTimeoutOnCloseResponseKt.Dsl.() -> Unit): ibc.core.channel.v1.Tx.MsgTimeoutOnCloseResponse =
ibc.core.channel.v1.MsgTimeoutOnCloseResponseKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| 1 | null | 0 | 0 | fe9795120e37a7223f331f48c0dd18c29e6e7cac | 1,450 | terra.proto | Apache License 2.0 |
heechan/AppcenterWeek2/app/src/main/java/dev/kichan/appcenterweek2/ui/theme/MainScreen.kt | inu-appcenter | 778,262,806 | false | {"Kotlin": 61740} | package dev.kichan.appcenterweek2.ui.theme
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import dev.kichan.appcenterweek2.ui.Screen
@Composable
fun MainScreen(navController: NavHostController) {
Column(Modifier.fillMaxSize()) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Button(onClick = { navController.navigate(Screen.One.name) }) {
Text(text = "Screen One 이동")
}
Button(onClick = { navController.navigate(Screen.Two.name) }) {
Text(text = "Screen Two 이동")
}
}
LazyColumn {
items(50) {
Text(
text = "Item ${it + 1}",
Modifier
.fillMaxWidth()
.padding(bottom = 12.dp)
.border(1.dp, Color.Black)
.padding(8.dp)
,
textAlign = TextAlign.Center,
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
AppcenterWeek2Theme {
MainScreen(rememberNavController())
}
} | 1 | Kotlin | 0 | 0 | 537bfaefb189946c8bbeeccb21b1c43b88898b52 | 2,018 | android-study-16th | MIT License |
video-sdk/src/main/java/com/kaleyra/video_sdk/call/screen/view/vcallscreen/InputMessageHandle.kt | KaleyraVideo | 686,975,102 | false | {"Kotlin": 5025429, "Shell": 7470, "Python": 6756, "Java": 1213} | package com.kaleyra.video_sdk.call.screen.view.vcallscreen
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import com.kaleyra.video_sdk.call.bottomsheet.CallBottomSheetDefaults
import com.kaleyra.video_sdk.call.bottomsheet.view.inputmessage.view.CameraMessageText
import com.kaleyra.video_sdk.call.bottomsheet.view.inputmessage.view.InputMessageHost
import com.kaleyra.video_sdk.call.bottomsheet.view.inputmessage.view.MicMessageText
internal const val InputMessageDragHandleTag = "InputMessageDragHandleTag"
@Composable
internal fun InputMessageHandle() {
val snackbarHostState = remember { SnackbarHostState() }
val showHandle by remember {
derivedStateOf { snackbarHostState.currentSnackbarData == null }
}
Box(
modifier = Modifier
.fillMaxWidth()
.animateContentSize(),
contentAlignment = Alignment.TopCenter
) {
if (showHandle) {
CallBottomSheetDefaults.HDragHandle(Modifier.testTag(InputMessageDragHandleTag))
}
InputMessageHost(
snackbarHostState = snackbarHostState,
micMessage = { enabled -> MicMessageText(enabled) },
cameraMessage = { enabled -> CameraMessageText(enabled) },
modifier = Modifier.padding(vertical = 6.dp)
)
}
} | 0 | Kotlin | 0 | 1 | d73e4727cec4875a98b21110823947edcfe9e28c | 1,836 | VideoAndroidSDK | Apache License 2.0 |
game/src/commonMain/kotlin/com/lehaine/game/node/entity/Hero.kt | LeHaine | 560,630,640 | false | {"Kotlin": 163750, "Shell": 1658, "HTML": 315} | package com.lehaine.game.node.entity
import com.lehaine.game.Assets
import com.lehaine.game.Config
import com.lehaine.game.GameInput
import com.lehaine.game.node.controller
import com.lehaine.game.node.entity.mob.Effect
import com.lehaine.game.node.entity.mob.Mob
import com.lehaine.game.node.fx
import com.lehaine.game.node.game
import com.lehaine.game.render.FlashFragmentShader
import com.lehaine.littlekt.graph.node.Node
import com.lehaine.littlekt.graph.node.addTo
import com.lehaine.littlekt.graph.node.annotation.SceneGraphDslMarker
import com.lehaine.littlekt.graph.node.node
import com.lehaine.littlekt.graph.node.node2d.Node2D
import com.lehaine.littlekt.graph.node.render.Material
import com.lehaine.littlekt.graphics.shader.ShaderProgram
import com.lehaine.littlekt.graphics.shader.shaders.DefaultVertexShader
import com.lehaine.littlekt.graphics.g2d.tilemap.ldtk.LDtkEntity
import com.lehaine.littlekt.math.PI2
import com.lehaine.littlekt.math.geom.*
import com.lehaine.littlekt.math.isFuzzyZero
import com.lehaine.littlekt.math.random
import com.lehaine.littlekt.util.datastructure.Pool
import com.lehaine.littlekt.util.fastForEach
import com.lehaine.littlekt.util.milliseconds
import com.lehaine.littlekt.util.seconds
import com.lehaine.littlekt.util.signal
import com.lehaine.rune.engine.GameLevel
import com.lehaine.rune.engine.node.EntityCamera2D
import com.lehaine.rune.engine.node.renderable.animatedSprite
import com.lehaine.rune.engine.node.renderable.entity.*
import com.lehaine.rune.engine.node.renderable.sprite
import kotlin.math.floor
import kotlin.math.min
import kotlin.random.Random
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
fun Node.hero(
data: LDtkEntity,
level: GameLevel<*>,
camera: EntityCamera2D,
projectiles: Node2D,
callback: @SceneGraphDslMarker Hero.() -> Unit = {}
) = node(Hero(data, level, camera, projectiles), callback)
/**
* @author <NAME>
* @date 11/2/2022
*/
class Hero(data: LDtkEntity, level: GameLevel<*>, val camera: EntityCamera2D, projectiles: Node2D) :
ObliqueEntity(level, Config.GRID_CELL_SIZE.toFloat()), Effectible {
var godMode = false
val onDeath = signal()
var health = 6
private val orbProjectilePool: Pool<OrbProjectile> by lazy {
Pool(3) {
OrbProjectile(this, level).apply { enabled = false }.addTo(projectiles)
}
}
private val swipeProjectilePool: Pool<SwipeProjectile> by lazy {
Pool(2) {
SwipeProjectile(this).apply { enabled = false }.addTo(projectiles)
}
}
private val boneSpearProjectile: Pool<BoneSpearProjectile> by lazy {
Pool(1) {
BoneSpearProjectile(this).apply { enabled = false }.addTo(projectiles)
}
}
private val explodingProjectile: Pool<ExplodingProjectile> by lazy {
Pool(1) {
ExplodingProjectile(this).apply { enabled = false }.addTo(projectiles)
}
}
private val canMove = data.field<Boolean>("canMove").value
private val flashMaterial = Material(ShaderProgram(DefaultVertexShader(), FlashFragmentShader()))
override val effects: MutableMap<Effect, Duration> = mutableMapOf()
override val effectsToRemove: MutableList<Effect> = mutableListOf()
private val mobsTemp = mutableListOf<Mob>()
private var speed = 0.03f
private var speedMultiplier = 1f
private var xMoveStrength = 0f
private var yMoveStrength = 0f
private val levelUp = animatedSprite {
anchorX = 0.5f
anchorY = 1f
onFrameChanged += {
if (it % 4 == 0) {
fx.levelUp(centerX, attachY)
}
}
}.also { sendChildToTop(it) }
private val shadow = sprite {
name = "Shadow"
slice = Assets.atlas.getByPrefix("shadow").slice
x -= Config.GRID_CELL_SIZE * data.pivotX
y -= Config.GRID_CELL_SIZE * data.pivotY - 2f
}.also { sendChildToTop(it) }
init {
anchorX = data.pivotX
anchorY = data.pivotY
toGridPosition(data.cx, data.cy)
sprite.apply {
registerState(Assets.heroAir, 110) { health <= 0 && !velocityZ.isFuzzyZero(0.05f) }
registerState(Assets.heroDash, 15) { cd.has("dash") }
registerState(Assets.heroWalk, 5) {
!velocityX.isFuzzyZero(0.05f) || !velocityY.isFuzzyZero(
0.05f
)
}
registerState(Assets.heroIdle, 0)
}
if (!canMove) {
addEffect(Effect.Invincible, Duration.INFINITE)
}
onReady += {
setHealthToFull()
flashMaterial.shader?.prepare(context)
}
onDestroy += {
flashMaterial.dispose()
}
}
fun setHealthToFull() {
health = (game.state.heroBaseHealth * game.state.heroHealthMultiplier).toInt().coerceAtLeast(1)
}
override fun update(dt: Duration) {
super.update(dt)
shadow.x = -Config.GRID_CELL_SIZE * 0.5f
shadow.globalY = (cy + yr) * Config.GRID_CELL_SIZE - Config.GRID_CELL_SIZE + 2
updateEffects(dt)
if (cd.has("hit")) {
val hitRatio = 1f - cd.ratio("hit")
sprite.color.r = 1f
sprite.color.g = hitRatio
sprite.color.b = hitRatio
}
if (cd.has("dashDamage")) {
Mob.ALL.fastForEach {
if (it.enabled && isCollidingWithInnerCircle(it)) {
it.hit(angleTo(it))
}
}
}
if (cd.has("dash") || !canMove) return
xMoveStrength = 0f
yMoveStrength = 0f
if (health <= 0) return
dir = dirToMouse
if (controller.down(GameInput.SWING)) {
attemptSwipeAttack()
}
if (controller.down(GameInput.SHOOT)) {
attemptOrbAttack()
}
if (!controller.down(GameInput.SWING) && !controller.down(GameInput.SHOOT) && !hasEffect(Effect.Stun)) {
val movement = controller.vector(GameInput.MOVEMENT)
xMoveStrength = movement.x
yMoveStrength = movement.y
}
if (controller.pressed(GameInput.DASH)) {
attemptDash()
}
if (controller.pressed(GameInput.HAND_OF_DEATH)) {
attemptHandOfDeath()
}
if (controller.pressed(GameInput.BONE_SPEAR)) {
attemptBoneSpearAttack()
}
}
fun attemptSwipeAttack() {
if (!cd.has("swipeCD")) {
cd("swipeCD", (750 * game.state.skillCDMultiplier).milliseconds)
repeat(game.state.extraHeroAttacks + 1) {
if (it > 0) {
cd("swipeRandom${Random.nextFloat()}", (200 * it).milliseconds) {
swipeAttack()
}
} else {
swipeAttack()
}
}
}
}
fun attemptOrbAttack() {
if (!game.state.shootingUnlocked) return
if (!cd.has("shootCD")) {
cd("shootCD", (3 * game.state.skillCDMultiplier).seconds)
repeat(game.state.extraHeroAttacks + 1) {
if (it > 0) {
cd("orbRandom${Random.nextFloat()}", (200 * it).milliseconds) {
orbAttack()
}
} else {
orbAttack()
}
}
camera.shake(100.milliseconds, 0.5f * Config.cameraShakeMultiplier)
}
}
fun attemptDash() {
if (!game.state.dashUnlocked) return
if (!cd.has("dashCD") && !cd.has("dash")) {
val angle = angleToMouse
xMoveStrength = angle.cosine
yMoveStrength = angle.sine
speedMultiplier = 5f
sprite.color.a = 0.5f
scaleX = 1.25f
scaleY = 0.9f
camera.shake(50.milliseconds, 0.5f * Config.cameraShakeMultiplier)
cd("dashCD", (1 * game.state.skillCDMultiplier).seconds)
addEffect(Effect.Invincible, 700.milliseconds)
cd("dashDamage", 350.milliseconds)
cd("dash", 250.milliseconds) {
speedMultiplier = 1f
scaleX = 1f
scaleY = 1f
shadow.globalY // forces to update global position if its dirty just by getting
}
}
}
fun attemptHandOfDeath() {
if (!game.state.handOfDeathUnlocked) return
if (!cd.has("handOfDeathCD")) {
cd("handOfDeathCD", (30 * game.state.skillCDMultiplier).seconds)
repeat(game.state.extraHeroAttacks + 1) {
if (it > 0) {
cd("handOfDeathRandom${Random.nextFloat()}", (200 * it).milliseconds) {
performHandOfDeath()
}
} else {
performHandOfDeath()
}
}
}
}
fun attemptBoneSpearAttack() {
if (!game.state.boneSpearUnlocked) return
if (!cd.has("boneSpearCD")) {
val tcx = (mouseX / Config.GRID_CELL_SIZE).toInt()
val tcy = (mouseY / Config.GRID_CELL_SIZE).toInt()
if (castRayTo(tcx, tcy) { cx, cy -> !level.hasCollision(cx, cy) }) {
cd("boneSpearCD", (15 * game.state.skillCDMultiplier).seconds)
repeat(game.state.extraHeroAttacks + 1) {
if (it > 0) {
cd("boneSpearRandom${Random.nextFloat()}", (200 * it).milliseconds) {
boneSpearAttack(mouseX, mouseY)
}
} else {
boneSpearAttack(mouseX, mouseY)
}
}
}
}
}
override fun onEffectStart(effect: Effect) {
super.onEffectStart(effect)
if (effect == Effect.Invincible) {
sprite.color.a = 0.5f
}
}
override fun onEffectEnd(effect: Effect) {
super.onEffectEnd(effect)
if (effect == Effect.Invincible) {
sprite.color.a = 1f
}
}
override fun fixedUpdate() {
super.fixedUpdate()
velocityX += speed * speedMultiplier * xMoveStrength * game.state.heroSpeedMultiplier
velocityY += speed * speedMultiplier * yMoveStrength * game.state.heroSpeedMultiplier
}
fun hit(from: Angle) {
if (hasEffect(Effect.Invincible) || health <= 0 || godMode) return
health--
addEffect(Effect.Invincible, 2.seconds)
velocityX += 0.25f * from.cosine
velocityY += 0.25f * from.sine
velocityZ += 0.25f
stretchY = 1.25f
if (health <= 0) {
sprite.material = flashMaterial
shadow.material = flashMaterial
Assets.sfxDeathHero.play(0.25f * Config.sfxMultiplier)
} else {
cd.timeout("hit", 250.milliseconds)
game.flashRed()
Assets.sfxHits.random().play(0.25f * Config.sfxMultiplier)
}
}
private fun orbAttack() {
val angle = angleToMouse
var projectile = orbProjectilePool.alloc()
projectile.enabled = true
projectile.globalPosition(centerX + 10f * angle.cosine, centerY + 10f * angle.sine)
projectile.moveTowardsAngle(angle)
var deltaAngle = 10.degrees
repeat(game.state.extraProjectiles) {
projectile = orbProjectilePool.alloc()
projectile.globalX = centerX + 10 * angle.cosine
projectile.globalY = centerY + 10 * angle.sine
projectile.enabled = true
projectile.moveTowardsAngle(if (it % 2 == 0) angle + deltaAngle else angle - deltaAngle)
if (it % 2 != 0) {
deltaAngle += 10.degrees
}
}
Assets.sfxShoot.play(0.2f * Config.sfxMultiplier)
}
private fun swipeAttack() {
cd("swipeDelay${Random.nextFloat()}", 200.milliseconds) {
repeat(1 + game.state.extraProjectiles) {
val projectile = swipeProjectilePool.alloc()
val offset = 20f + 20f * floor(it / 2f)
val angle = if (it % 2 == 0) angleToMouse else angleToMouse + 180.degrees
projectile.sprite.flipY = dir == -1
projectile.rotation = angle
projectile.globalPosition(globalX + offset * angle.cosine, globalY + offset * angle.sine)
projectile.enabled = true
}
}
Assets.sfxSwings.random().play(0.25f * Config.sfxMultiplier)
sprite.playOnce(Assets.heroSwing)
addEffect(Effect.Stun, 300.milliseconds)
}
private fun boneSpearAttack(tx: Float, ty: Float) {
var projectile = boneSpearProjectile.alloc()
projectile.globalX = tx
projectile.globalY = ty
projectile.enabled = true
if (game.state.extraProjectiles > 0) {
val angleBetween = (PI2 / (game.state.extraProjectiles)).radians
var currentAngle = 0.degrees
repeat(game.state.extraProjectiles) {
projectile = boneSpearProjectile.alloc()
projectile.globalX = tx + 48 * currentAngle.cosine
projectile.globalY = ty + 48 * currentAngle.sine
projectile.enabled = true
currentAngle += angleBetween
}
}
}
private fun performHandOfDeath() {
if (Mob.ALL.isEmpty()) return
repeat(min(Mob.ALL.size, 5 + game.state.extraProjectiles)) {
val mob = Mob.ALL.filter { !it.marked }.random()
mob.marked = true
mobsTemp += mob
}
mobsTemp.fastForEach {
it.handleHandOfDeath()
}
mobsTemp.clear()
}
fun projectileFinished(projectile: Projectile) {
when (projectile) {
is SwipeProjectile, is BoneSpearProjectile, is OrbProjectile -> {
if (projectile is Node2D) {
repeat(game.state.extraExplosions) {
cd("explosion$it-${Random.nextFloat()}", (100 * it).milliseconds) {
addExplodingProjectile(
projectile.globalX + (-16f..16f).random(), projectile.globalY + (-16f..16f).random()
)
}
}
}
}
else -> {
// do nothing if any other projectile
}
}
when (projectile) {
is SwipeProjectile -> swipeProjectilePool.free(projectile)
is BoneSpearProjectile -> boneSpearProjectile.free(projectile)
is OrbProjectile -> orbProjectilePool.free(projectile)
is ExplodingProjectile -> explodingProjectile.free(projectile)
}
}
private fun addExplodingProjectile(x: Float, y: Float) {
val projectile = explodingProjectile.alloc()
projectile.globalX = x
projectile.globalY = y
projectile.enabled = true
}
override fun onLand() {
super.onLand()
if (!cd.has("landed")) {
Assets.sfxLands.random().play(0.2f * Config.sfxMultiplier)
cd("landed", 1000.milliseconds)
}
if (health <= 0) {
velocityZ = 0f
sprite.playOnce(Assets.heroDie)
sprite.play(Assets.heroDead, 5.seconds, true)
cd("die", 1.seconds) {
onDeath.emit()
}
}
}
override fun isEffectible(): Boolean = health > 0
fun levelUp() {
levelUp.playOnce(Assets.levelUp)
fx.levelUp(centerX, attachY)
}
} | 0 | Kotlin | 6 | 40 | 743ab3be2e20d72f976694b8b2c7e8caed3acfdf | 15,800 | ggo2022 | MIT License |
storage/store/src/main/kotlin/com/neva/javarel/storage/store/impl/ConnectedStore.kt | neva-dev | 52,150,334 | false | null | package com.neva.javarel.storage.store.impl
import com.mongodb.DB
import com.mongodb.gridfs.GridFS
import com.neva.javarel.storage.store.api.Store
import com.neva.javarel.storage.store.api.StoreConnection
import org.mongodb.morphia.Datastore
class ConnectedStore(
override val connection: StoreConnection,
override val dataStore: Datastore,
override val db: DB = DB(dataStore.mongo, connection.dbName)
) : Store {
private val fileStores = mutableMapOf<String, GridFS>()
override fun fileStore(name: String): GridFS {
return fileStores.getOrPut(name, { GridFS(db, name) })
}
override val fileStore: GridFS
get() = fileStore(GridFS.DEFAULT_BUCKET)
} | 8 | Kotlin | 0 | 8 | 6b75efa9d3e83c5eec23ed7cd4368e901f1f54dc | 709 | javarel-framework | Apache License 2.0 |
core/designsystem/src/main/kotlin/io/devbits/gocart/designsystem/component/Text.kt | etonotieno | 322,909,207 | false | {"Kotlin": 369913, "Shell": 791, "Swift": 322, "Batchfile": 54} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.devbits.gocart.designsystem.component
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
/**
* [Text] component that displays a styled pair.
*
* @param pair The pair of text to display. The style is only applied to the second value of pair.
* @param style The span style to apply
*/
@Composable
fun GCStyledTextPair(
pair: Pair<String, String>,
style: SpanStyle,
textStyle: TextStyle,
modifier: Modifier = Modifier,
textAlign: TextAlign? = null,
) {
val finalText = buildAnnotatedString {
append(pair.first)
append(" ")
withStyle(style) {
append(pair.second)
}
}
Text(
text = finalText,
textAlign = textAlign,
style = textStyle,
modifier = modifier,
)
}
| 17 | Kotlin | 0 | 4 | ffe5adce727efb5edb71f69601cbc6b9f3096ce0 | 1,670 | GoCart | Apache License 2.0 |
src/commonMain/kotlin/serializer/PlaneSerializer.kt | Lepinoid | 377,028,827 | false | {"Kotlin": 47531} | package net.lepinoid.bbdatastructure.serializer
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.DoubleArraySerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonPrimitive
import net.lepinoid.bbdatastructure.util.Plane
object PlaneSerializer : KSerializer<Plane> {
override fun deserialize(decoder: Decoder): Plane {
val input = decoder as? JsonDecoder ?: error("can be deserialized only by JSON")
val json = input.decodeJsonElement().jsonArray
val horizontal = json[0].jsonPrimitive.content
val vertical = json[1].jsonPrimitive.content
return Plane(horizontal.toDouble(), vertical.toDouble())
}
override val descriptor: SerialDescriptor
get() = DoubleArraySerializer().descriptor
override fun serialize(encoder: Encoder, value: Plane) {
encoder.beginCollection(descriptor, 2).apply {
encodeDoubleElement(descriptor, 0, value.horizontal)
encodeDoubleElement(descriptor, 1, value.vertical)
endStructure(descriptor)
}
}
} | 2 | Kotlin | 0 | 0 | 9b89faee5d322a865faf05746ff7eaa3f58eadd9 | 1,309 | bb-data-structure | MIT License |
app/src/main/java/com/silencefly96/piecediary/module/diary/model/local/DiaryDatabase.kt | silencefly96 | 333,001,955 | false | null | package com.silencefly96.piecediary.module.diary.model.local
import androidx.room.Database
import androidx.room.RoomDatabase
import com.silencefly96.piecediary.module.diary.model.Diary
@Database(entities = [Diary::class], version = 1)
abstract class DiaryDatabase : RoomDatabase() {
abstract fun diaryDao(): DiaryDao
} | 0 | Kotlin | 0 | 0 | cd8beac02b9b306bd9290055928df0d4710b21f4 | 325 | PieceDiary | Apache License 2.0 |
android/src/main/java/com/magicleap/magicscript/font/FontProvider.kt | magic-script | 187,085,008 | false | null | /*
* Copyright (c) 2019-2020 Magic Leap, Inc. All Rights Reserved
*
* 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.magicleap.magicscript.font
import android.graphics.Typeface
interface FontProvider {
fun provideFont(fontStyle: FontStyle? = null, fontWeight: FontWeight? = null): Typeface
} | 41 | Swift | 2 | 16 | b1a543f22af76447e9e58788fc494324dc40be14 | 837 | magic-script-components-react-native | Apache License 2.0 |
src/com/android/launcher3/states/EditModeState.kt | LawnchairLauncher | 83,799,439 | false | {"Java": 9665767, "Kotlin": 2674103, "AIDL": 30229, "Python": 17364, "Makefile": 3820, "Shell": 770} | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.states
import android.content.Context
import com.android.launcher3.Launcher
import com.android.launcher3.LauncherState
import com.android.launcher3.logging.StatsLogManager
import com.android.launcher3.views.ActivityContext
/** Definition for Edit Mode state used for home gardening multi-select */
class EditModeState(id: Int) : LauncherState(id, StatsLogManager.LAUNCHER_STATE_HOME, STATE_FLAGS) {
companion object {
private val STATE_FLAGS =
(FLAG_MULTI_PAGE or
FLAG_WORKSPACE_INACCESSIBLE or
FLAG_DISABLE_RESTORE or
FLAG_WORKSPACE_ICONS_CAN_BE_DRAGGED or
FLAG_WORKSPACE_HAS_BACKGROUNDS)
}
override fun <T> getTransitionDuration(context: T, isToState: Boolean): Int where
T : Context?,
T : ActivityContext? {
return 150
}
override fun <T> getDepthUnchecked(context: T): Float where T : Context?, T : ActivityContext? {
return 0.5f
}
override fun getWorkspaceScaleAndTranslation(launcher: Launcher): ScaleAndTranslation {
val scale = launcher.deviceProfile.getWorkspaceSpringLoadScale(launcher)
return ScaleAndTranslation(scale, 0f, 0f)
}
override fun getHotseatScaleAndTranslation(launcher: Launcher): ScaleAndTranslation {
val scale = launcher.deviceProfile.getWorkspaceSpringLoadScale(launcher)
return ScaleAndTranslation(scale, 0f, 0f)
}
override fun getWorkspaceBackgroundAlpha(launcher: Launcher): Float {
return 0.2f
}
override fun onLeavingState(launcher: Launcher?, toState: LauncherState?) {
// cleanup any changes to workspace
}
}
| 388 | Java | 1200 | 9,200 | d91399d2e4c6acbeef9c0704043f269115bb688b | 2,314 | lawnchair | Apache License 2.0 |
backend/src/main/kotlin/at/ac/tuwien/waecm/ss18/group09/web/LogoutController.kt | fuvidani | 125,189,492 | false | null | package at.ac.tuwien.waecm.ss18.group09.web
import at.ac.tuwien.waecm.ss18.group09.service.ISecurityService
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
@CrossOrigin
@RestController
class LogoutController(private val securityService: ISecurityService) {
@PostMapping("/logoutUser")
fun logUserOut(@RequestBody data: String): Mono<HttpStatus> {
securityService.logoutUser(data)
return Mono.just(HttpStatus.OK)
}
}
| 0 | Kotlin | 3 | 2 | 46edad80694a5238715c99afed463a49e02732b4 | 716 | web-app-engineering | MIT License |
app/src/main/java/com/revolgenx/anilib/staff/viewmodel/StaffContainerViewModel.kt | rev0lgenX | 244,410,204 | false | null | package com.revolgenx.anilib.staff.viewmodel
import androidx.lifecycle.ViewModel
class StaffContainerViewModel: ViewModel() {
var title:String? = null
var staffLink:String? = null
} | 9 | Kotlin | 2 | 30 | acb73e94a362e8660a8c868996aceb6df2f2aa9b | 191 | AniLib | Apache License 2.0 |
src/main/kotlin/de/qaware/refactobot/scanner/Scanner.kt | qaware | 98,463,096 | false | null | package de.qaware.refactobot.scanner
import de.qaware.refactobot.model.codebase.Codebase
import java.nio.file.Path
/**
* Interface for a scanner module.
*
* A scanner discovers the codebase structure.
*
* @author Alexander Krauss [email protected]
*/
interface Scanner {
/**
* Scans a codebase, and produces a model of it, containing all modules, and the files they
* contain.
*
* @param rootDir the root path that should be scanned.
* @return the codebase model.
*/
fun scanCodebase(rootDir: Path) : Codebase
} | 0 | Kotlin | 1 | 0 | 2fdb700f913583613d1e8732446f47c8da7cedd4 | 568 | refactobot | MIT License |
app/src/main/java/com/gmail/rallen/gridstrument/gl/GridGLSurfaceView.kt | atommarvel | 189,650,334 | false | null | package com.gmail.rallen.gridstrument.gl
import android.content.Context
import android.opengl.GLSurfaceView
import android.opengl.Matrix
import android.util.Log
import com.gmail.rallen.gridstrument.repo.BaseNotesRepo
import com.gmail.rallen.gridstrument.repo.FingerRepo
import com.gmail.rallen.gridstrument.repo.GridConfigRepo
import com.gmail.rallen.gridstrument.util.xyToNote
/**
* TODO: send pitchBend Range message to the server so they can understand this automatically
*/
class GridGLSurfaceView @JvmOverloads constructor(
context: Context,
private val fingerRepo: FingerRepo,
private val baseNotesRepo: BaseNotesRepo,
private val gridConfigRepo: GridConfigRepo
) : GLSurfaceView(context) {
// rendering vars...
private val renderer: GridGLRenderer = GridGLRenderer()
private var gridLines: GridLines? = null
private var noteRects: ArrayList<GridRects>? = null
private var displayWidth: Int = 0
private var displayHeight: Int = 0
private val mNoteColors = arrayOf(// modulo 12 color keys
floatArrayOf(0.0f, 0.9f, 0.0f, 1.0f), // C
floatArrayOf(0.0f, 0.0f, 0.0f, 1.0f), // C#
floatArrayOf(0.0f, 0.9f, 0.9f, 1.0f), // D
floatArrayOf(0.0f, 0.0f, 0.0f, 1.0f), // D#
floatArrayOf(0.0f, 0.9f, 0.9f, 1.0f), // E
floatArrayOf(0.0f, 0.9f, 0.9f, 1.0f), // F
floatArrayOf(0.0f, 0.0f, 0.0f, 1.0f), // F#
floatArrayOf(0.0f, 0.9f, 0.9f, 1.0f), // G
floatArrayOf(0.0f, 0.0f, 0.0f, 1.0f), // G#
floatArrayOf(0.0f, 0.9f, 0.9f, 1.0f), // A
floatArrayOf(0.0f, 0.0f, 0.0f, 1.0f), // A#
floatArrayOf(0.0f, 0.9f, 0.9f, 1.0f) // B
)
init {
setEGLContextClientVersion(2)
setRenderer(renderer)
}
fun onBaseNotesUpdated() {
val numHorizLines = Math.ceil((displayWidth / gridConfigRepo.cellWidth).toDouble()).toInt() + 1
val numVertLines = Math.ceil((displayHeight / gridConfigRepo.cellHeight).toDouble()).toInt() + 1
var k = 0
for (i in 0..numHorizLines) {
var j = 0
while (j <= numVertLines) {
val note = xyToNote(
i * gridConfigRepo.cellWidth + 1,
j * gridConfigRepo.cellHeight + 1,
gridConfigRepo,
baseNotesRepo
)
val curColor = mNoteColors[note % 12]
noteRects!![k].setColor(curColor[0], curColor[1], curColor[2], curColor[3])
j++
k++
}
}
}
private fun resetRenderer() {
renderer.clearItems()
for (i in 0..15) {
renderer.addItem(fingerRepo.fingers[i].glFinger.lightRect)
}
for (g in noteRects!!) {
renderer.addItem(g)
}
renderer.addItem(gridLines)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
displayWidth = right - left
displayHeight = bottom - top
val numHorizLines = Math.ceil((displayWidth / gridConfigRepo.cellWidth).toDouble()).toInt() + 1
val numVertLines = Math.ceil((displayHeight / gridConfigRepo.cellHeight).toDouble()).toInt() + 1
val numVertCells = numVertLines - 1
Log.d("onLayout", "h=$numHorizLines v=$numVertLines")
gridLines = GridLines(0.9f, 0.9f, 0.9f, 1.0f)
noteRects = ArrayList()
if (baseNotesRepo.notes.size != numVertCells) {
val resizedBaseNotes = baseNotesRepo.notes.toMutableList()
val oldSize = resizedBaseNotes.size
if (oldSize < numVertCells) {
for (i in oldSize until numVertCells) {
resizedBaseNotes.add(baseNotesRepo.notes[oldSize - 1] + 5) // have to pick something
}
} else {
for (i in oldSize - 1 downTo numVertCells) {
resizedBaseNotes.removeAt(i)
}
}
baseNotesRepo.updateBaseNotes(resizedBaseNotes)
}
//gridLines.reset();
for (i in 0..numHorizLines) {
gridLines!!.add(i.toFloat() * gridConfigRepo.cellWidth, 0.0f, 0.0f, i.toFloat() * gridConfigRepo.cellWidth, numHorizLines.toFloat() * gridConfigRepo.cellHeight, 0.0f)
gridLines!!.add(0.0f, i.toFloat() * gridConfigRepo.cellHeight, 0.0f, numHorizLines.toFloat() * gridConfigRepo.cellWidth, i.toFloat() * gridConfigRepo.cellHeight, 0.0f)
for (j in 0..numVertLines) {
val note = xyToNote(
i * gridConfigRepo.cellWidth + 1,
j * gridConfigRepo.cellHeight + 1,
gridConfigRepo,
baseNotesRepo
)
val curColor = mNoteColors[note % 12]
val curRect = GridRects(curColor[0], curColor[1], curColor[2], curColor[3])
curRect.add(-gridConfigRepo.cellWidth / 4f, gridConfigRepo.cellHeight / 6f, 0f, gridConfigRepo.cellWidth / 6f, -gridConfigRepo.cellHeight / 4f, 0f)
val curMatrix = FloatArray(16)
Matrix.setIdentityM(curMatrix, 0)
Matrix.translateM(curMatrix, 0, i * gridConfigRepo.cellWidth + gridConfigRepo.cellWidth / 2, j * gridConfigRepo.cellHeight + gridConfigRepo.cellHeight / 2, 0.0f)
curRect.setModelMatrix(curMatrix)
noteRects!!.add(curRect)
}
}
// TODO: finger.onLayout?
for (i in 0..15) {
fingerRepo.fingers[i].glFinger.apply {
lightRect.reset()
lightRect.add(-gridConfigRepo.cellWidth / 2, gridConfigRepo.cellHeight / 2, 0.0f, gridConfigRepo.cellWidth / 2, -gridConfigRepo.cellHeight / 2, 0.0f)
Matrix.setIdentityM(lightMatrix, 0)
Matrix.translateM(lightMatrix, 0, -gridConfigRepo.cellWidth / 2, -gridConfigRepo.cellHeight / 2, 0.0f) // offscreen
lightRect.setModelMatrix(lightMatrix)
}
}
resetRenderer()
}
}
| 1 | null | 1 | 3 | d51bbae837659ad4130685568053f8863afed972 | 6,116 | GridStrument | MIT License |
app/src/main/java/com/saean/app/store/settings/StoreSettingServicesActivity.kt | defuj | 276,851,703 | false | null | package com.saean.app.store.settings
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.saean.app.R
import com.saean.app.helper.Cache
import com.saean.app.store.StoreAddProductActivity
import com.saean.app.store.model.*
import kotlinx.android.synthetic.main.activity_store_setting_services.*
import kotlinx.android.synthetic.main.activity_store_setting_services.btnClose
class StoreSettingServicesActivity : AppCompatActivity() {
private var service : ArrayList<ServiceModel>? = null
private lateinit var database: FirebaseDatabase
private var sharedPreferences : SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_store_setting_services)
database = FirebaseDatabase.getInstance()
sharedPreferences =getSharedPreferences(Cache.cacheName,0)
setupFunctions()
}
private fun setupFunctions() {
toolbarService.setNavigationOnClickListener {
finish()
}
btnClose.setOnClickListener {
containerNoticeService.visibility = View.GONE
}
btnAddService.setOnClickListener {
startActivity(Intent(this,
StoreAddProductActivity::class.java))
}
setupService()
}
private fun setupService() {
val storeID = sharedPreferences!!.getString(Cache.storeID,"")
database.getReference("product/service/$storeID").addValueEventListener(object :
ValueEventListener {
override fun onCancelled(error: DatabaseError) {
recyclerStoreService.visibility = View.GONE
containerNoServices.visibility = View.VISIBLE
containerNoticeService.visibility = View.VISIBLE
}
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.exists()){
if(snapshot.hasChildren()){
recyclerStoreService.visibility = View.VISIBLE
containerNoServices.visibility = View.GONE
containerNoticeService.visibility = View.GONE
service = ArrayList()
service!!.clear()
recyclerStoreService.layoutManager = LinearLayoutManager(this@StoreSettingServicesActivity,LinearLayoutManager.VERTICAL,false)
for(services in snapshot.children){
val model = ServiceModel()
model.serviceID = services.key.toString()
model.serviceTitle = services.child("serviceName").getValue(String::class.java)
model.serviceDescription = services.child("serviceDescription").getValue(String::class.java)
service!!.add(model)
}
val adapter = ServiceAdapter(this@StoreSettingServicesActivity,service!!)
recyclerStoreService.adapter = adapter
}else{
recyclerStoreService.visibility = View.GONE
containerNoServices.visibility = View.VISIBLE
containerNoticeService.visibility = View.VISIBLE
}
}else{
recyclerStoreService.visibility = View.GONE
containerNoServices.visibility = View.VISIBLE
containerNoticeService.visibility = View.VISIBLE
}
}
})
}
} | 1 | Kotlin | 1 | 1 | 0f02437a2438b8f1fe240e25ac32335e23404333 | 3,988 | Saean | MIT License |
org.librarysimplified.audiobook.tests/src/test/java/org/librarysimplified/audiobook/tests/local/ExoManifestTest.kt | NYPL-Simplified | 139,462,999 | false | {"Kotlin": 544969, "Java": 2451} | package org.librarysimplified.audiobook.tests.local
import org.librarysimplified.audiobook.tests.open_access.ExoManifestContract
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class ExoManifestTest : ExoManifestContract() {
override fun log(): Logger {
return LoggerFactory.getLogger(ExoManifestTest::class.java)
}
}
| 1 | Kotlin | 2 | 2 | 6633bcd1006ead70bc2ffd945cacb6b38af8e8e5 | 335 | audiobook-android | Apache License 2.0 |
app/src/main/java/org/wikipedia/dataclient/mwapi/MwServiceError.kt | codyd51 | 403,582,545 | true | {"Gradle": 6, "Shell": 3, "Text": 2, "INI": 3, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "EditorConfig": 1, "YAML": 6, "XML": 636, "CODEOWNERS": 1, "Proguard": 2, "JSON": 58, "Java Properties": 2, "Java": 92, "Kotlin": 565, "SQL": 2, "SVG": 1, "Python": 5, "Jinja": 1} | package org.wikipedia.dataclient.mwapi
import com.google.gson.annotations.SerializedName
import org.wikipedia.dataclient.ServiceError
import org.wikipedia.json.PostProcessingTypeAdapter.PostProcessable
import org.wikipedia.util.DateUtil
import org.wikipedia.util.ThrowableUtil
import java.util.*
class MwServiceError(val code: String?,
var html: String?,
val data: Data? = null) : ServiceError, PostProcessable {
fun badToken(): Boolean {
return "badtoken" == code
}
fun badLoginState(): Boolean {
return "assertuserfailed" == code
}
fun hasMessageName(messageName: String): Boolean {
return data?.messages?.find { it.name == messageName } != null
}
fun getMessageHtml(messageName: String): String? {
return data?.messages?.first { it.name == messageName }?.html
}
override val title: String get() = code.orEmpty()
override val details: String get() = html.orEmpty()
override fun postProcess() {
// Special case: if it's a Blocked error, parse the blockinfo structure ourselves.
if (("blocked" == code || "autoblocked" == code) && data?.blockinfo != null) {
html = ThrowableUtil.getBlockMessageHtml(data.blockinfo)
}
}
class Data(val messages: List<Message>?, val blockinfo: BlockInfo?)
class Message(val name: String?, val html: String = "")
open class BlockInfo {
@SerializedName("blockedbyid")
val blockedById = 0
@SerializedName("blockid")
val blockId = 0
@SerializedName("blockedby")
val blockedBy: String = ""
@SerializedName("blockreason")
val blockReason: String = ""
@SerializedName("blockedtimestamp")
val blockTimeStamp: String = ""
@SerializedName("blockexpiry")
val blockExpiry: String = ""
val isBlocked: Boolean
get() {
if (blockExpiry.isEmpty()) {
return false
}
val now = Date()
val expiry = DateUtil.iso8601DateParse(blockExpiry)
return expiry.after(now)
}
}
}
| 1 | Kotlin | 0 | 0 | dfb163c7aa7ba193095763c0db65709361c72fef | 2,195 | apps-android-wikipedia | Apache License 2.0 |
MVIArchitecture/app/src/main/java/com/outofbound/mviarchitecture/data/MainSampleModel.kt | Sreedev | 116,258,943 | false | {"Gradle": 19, "Text": 1, "Markdown": 3, "Java Properties": 13, "Shell": 6, "Ignore List": 12, "Batchfile": 6, "Proguard": 6, "Kotlin": 30, "XML": 76, "CODEOWNERS": 1, "Java": 14, "JSON": 1} | package com.outofbound.mviarchitecture.data
data class MainSampleModel(
var stringForList: String? = null
) | 1 | null | 1 | 1 | 16b26fa80d01132af5f0d91de6c5c3d8e3534f51 | 112 | androidappsamples | Apache License 2.0 |
ladon-cassandra/src/main/java/de/mc/ladon/server/persistence/cassandra/entities/impl/DbAccessKey.kt | mindmill | 149,764,094 | false | {"Maven POM": 8, "Ignore List": 1, "Git Attributes": 1, "Markdown": 1, "Kotlin": 128, "Java": 19, "Java Properties": 3, "YAML": 1, "SQL": 2, "Text": 1, "XML": 1, "HTML": 3, "JavaScript": 53, "SVG": 2, "CSS": 13, "Less": 13, "SCSS": 13} | package de.mc.ladon.server.persistence.cassandra.entities.impl
import com.datastax.driver.mapping.annotations.PartitionKey
import com.datastax.driver.mapping.annotations.Table
/**
* @author <NAME>
* 22.10.16
*/
@Table(keyspace = "LADON", name = "KEYS", readConsistency = "ONE", writeConsistency = "LOCAL_QUORUM")
data class DbAccessKey(
@PartitionKey
var accessKeyId: String? = null,
var secretKey: String? = null,
var userid: String? = null,
var roles: Set<String>? = null
) | 4 | JavaScript | 3 | 2 | b8d1aaea5c94988cd57224b3bbb55fdcbd639020 | 520 | ladon-data-center-edition | Academic Free License v1.1 |
app/src/main/java/xyz/adhithyan/scan2pdf/activity/MainActivity.kt | v-khdumi | 232,194,087 | false | {"Java": 1169599, "Kotlin": 60402} | package xyz.adhithyan.scan2pdf.activity
import android.app.Activity
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.PicassoEngine
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import ru.whalemare.sheetmenu.SheetMenu
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper
import xyz.adhithyan.scan2pdf.R
import xyz.adhithyan.scan2pdf.extensions.checkOrGetPermissions
import xyz.adhithyan.scan2pdf.extensions.requestPermissionsResult
import java.io.File
import android.support.v4.content.FileProvider
import android.text.InputType
import android.view.ContextMenu
import android.view.View
import android.widget.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import xyz.adhithyan.scan2pdf.BuildConfig
import xyz.adhithyan.scan2pdf.util.*
class MainActivity : AppCompatActivity() {
val CHOOSE_IMAGES = 3592
private lateinit var PDF_LIST: Array<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
bottomNavigation.setOnNavigationItemSelectedListener(bottomNavigationClickListener)
title = "My Scans"
checkOrGetPermissions()
PDF_LIST = listAllFiles()
var adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, PDF_LIST)
scans_list_view.adapter = adapter
scans_list_view.setOnItemClickListener { adapterView, view, i, l ->
val pdfFile = File(ROOT_PATH + PDF_LIST[i])
val pdfURI = FileProvider.getUriForFile(this@MainActivity,
BuildConfig.APPLICATION_ID + ".provider",
pdfFile)
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(pdfURI, "application/pdf")
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(intent)
}
registerOrRemoveContextMenu()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}
fun chooseFromGallery() {
Matisse.from(this)
.choose(MimeType.ofImage(), false)
.countable(true)
.maxSelectable(5)
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
.thumbnailScale(0.85f)
.imageEngine(PicassoEngine())
.forResult(CHOOSE_IMAGES)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CHOOSE_IMAGES && resultCode == Activity.RESULT_OK) {
val selected = Matisse.obtainResult(data)
for (selectedImage in selected) {
val imageBytes = (selectedImage as Uri).toByteArray(this)
ResultHolder.images?.add(imageBytes)
}
ResultHolder.image = ResultHolder.images?.first
val intent = Intent(this, PreviewActivity::class.java)
startActivity(intent)
Log.d("Chosen images", "selected:" + selected)
}
}
private val bottomNavigationClickListener by lazy {
BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_all_scans -> {
return@OnNavigationItemSelectedListener true
}
R.id.navigation_new_scan -> {
showScanMenu()
return@OnNavigationItemSelectedListener true
}
R.id.navigation_settings -> {
return@OnNavigationItemSelectedListener true
}
}
false
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
this.requestPermissionsResult(requestCode, permissions, grantResults)
}
private fun showScanMenu() {
SheetMenu().apply {
titleId = R.string.sheet_menu_title_new_scan
click = MenuItem.OnMenuItemClickListener {
when (it.itemId) {
R.id.new_scan_cam -> {
startActivity(Intent(this@MainActivity, ScanActivity::class.java));true
}
R.id.new_scan_gallery -> {
chooseFromGallery(); true
}
else -> {
true
}
}
}
menu = R.menu.new_scan
}.show(this)
}
override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
if(PDF_LIST.size == 1 && PDF_LIST[0] == NO_SCANS_PRESENT) {
return;
}
super.onCreateContextMenu(menu, v, menuInfo)
menuInflater.inflate(R.menu.pdf_context_menu, menu)
}
override fun onContextItemSelected(item: MenuItem): Boolean {
val info = item.menuInfo as AdapterView.AdapterContextMenuInfo
when(item.itemId) {
R.id.scan_pdf_rename -> {
val i = info.id.toInt()
val srcFileName = PDF_LIST[i]
showRenameFileDialog(srcFileName, i)
return true
}
R.id.scan_pdf_share -> {
val i = info.id.toInt()
sharePdf(i)
}
R.id.scan_pdf_delete -> {
val i = info.id.toInt()
deletePdf(i)
}
}
return super.onContextItemSelected(item)
}
private fun showRenameFileDialog(srcFile: String, i: Int) {
val builder = AlertDialog.Builder(this)
builder.setTitle("Rename file")
val input = EditText(this)
input.inputType = InputType.TYPE_CLASS_TEXT
builder.setView(input)
builder.setPositiveButton("OK", object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
var destFileName = input.text.toString().trim()
if(!destFileName.endsWith(".pdf")) {
destFileName += ".pdf"
}
if(destFileName.isEmpty()) {
Toast.makeText(this@MainActivity, "File name cannot be empty", Toast.LENGTH_LONG).show()
dialog?.dismiss()
} else {
val isFileRenamed = [email protected](srcFile, destFileName)
if(isFileRenamed) {
Toast.makeText(this@MainActivity, "File rename success", Toast.LENGTH_LONG).show()
PDF_LIST[i] = destFileName
var adapter = ArrayAdapter<String>(this@MainActivity, android.R.layout.simple_list_item_1, PDF_LIST)
scans_list_view.adapter = adapter
adapter.notifyDataSetChanged()
} else {
Toast.makeText(this@MainActivity, "File rename failed.", Toast.LENGTH_LONG).show()
}
}
}
})
builder.setNegativeButton("Cancel", null)
builder.show()
}
private fun sharePdf(i: Int) {
val pdfFile = File(ROOT_PATH + PDF_LIST[i])
val pdfURI = FileProvider.getUriForFile(this@MainActivity,
BuildConfig.APPLICATION_ID + ".provider",
pdfFile)
val intent = Intent()
intent.action = Intent.ACTION_SEND
intent.putExtra(Intent.EXTRA_TEXT, "Pdf created using Scan2Pdf app. \n")
intent.putExtra(Intent.EXTRA_STREAM, pdfURI)
intent.type = "application/pdf"
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(intent, "Share PDF"))
}
private fun deletePdf(i: Int) {
val progress = ProgressDialog(this)
progress.setTitle("Deleting pdf ...")
progress.show()
val pdfFile = File(ROOT_PATH + PDF_LIST[i])
Observable.just<Unit>(Unit)
.map { pdfFile.delete() }
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
if(it) {
Toast.makeText(this, "Pdf deleted successfully.", Toast.LENGTH_LONG).show()
val newPdfList = PDF_LIST.toMutableList()
newPdfList.removeAt(i)
PDF_LIST = listAllFiles()
var adapter = ArrayAdapter<String>(this@MainActivity, android.R.layout.simple_list_item_1, PDF_LIST)
scans_list_view.adapter = adapter
adapter.notifyDataSetChanged()
registerOrRemoveContextMenu()
} else {
Toast.makeText(this, "Pdf deletion failed.", Toast.LENGTH_LONG).show()
}
progress.dismiss()
}
}
private fun registerOrRemoveContextMenu() {
if(PDF_LIST.size == 1 && PDF_LIST[0] == NO_SCANS_PRESENT) {
return;
} else {
registerForContextMenu(scans_list_view)
}
}
}
| 1 | null | 1 | 1 | 4a2457134b0dbb60f483c684f9a0e87654f23a13 | 10,701 | Scan2Pdf | MIT License |
idea/tests/testData/indentationOnNewline/emptyParameters/EmptyParameterInImplicitPrimaryConstructor.after.kt | JetBrains | 278,369,660 | false | null | class A(
<caret>
)
// SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS | 0 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 69 | intellij-kotlin | Apache License 2.0 |
src/api/kotlin/eu/stefanwimmer128/morefood2/api/item/ItemStrawberry.kt | stefanwimmer128 | 110,285,597 | false | {"Gradle Kotlin DSL": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "JSON": 71, "Markdown": 1, "Kotlin": 17, "Java": 1} | package eu.stefanwimmer128.morefood2.api.item
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemFood
import net.minecraft.item.ItemStack
import net.minecraft.util.ResourceLocation
import net.minecraft.world.World
open class ItemStrawberry @JvmOverloads constructor(amount: Int = 2, saturation: Float = 0.6f, isWolfFood: Boolean = false, name: String = "strawberry", resourceDomain: String? = null): ItemFood(amount, saturation, isWolfFood) {
init {
unlocalizedName = name
registryName = if (resourceDomain != null) ResourceLocation(resourceDomain, name) else ResourceLocation(name)
setAlwaysEdible()
}
override fun onFoodEaten(stack: ItemStack, worldIn: World, player: EntityPlayer) {
player.heal(.5f)
super.onFoodEaten(stack, worldIn, player)
}
override fun getMaxItemUseDuration(stack: ItemStack) =
16
}
| 1 | null | 1 | 1 | 4872695609d6a5851e355f139d2c630d2fe0c2b2 | 928 | morefood2 | ISC License |
app/src/main/java/org/hackzurich2017/draw2fashion/PickupFragment.kt | dkhmelenko | 103,714,885 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 21, "XML": 19, "Java": 1} | package org.hackzurich2017.draw2fashion
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main_alternative.*
import org.hackzurich2017.draw2fashion.draw2fashion.R
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [PickupFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [PickupFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class PickupFragment : Fragment() {
private val CAMERA_REQUEST_CODE = 1
private var listener: OnFragmentInteractionListener? = null
var currentPhotoPath: String? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.activity_main_alternative, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
takeImage.setOnClickListener { takePicture() }
openGalery.setOnClickListener { pickFromGalery() }
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
private fun takePicture() {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.CAMERA)) {
Toast.makeText(activity, "Enable camera permission first", Toast.LENGTH_SHORT).show()
} else {
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE);
}
} else {
doStartTakePicture()
}
}
private fun doStartTakePicture() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(activity.packageManager) != null) {
// Create the File where the photo should go
var photoFile: File? = null
try {
photoFile = createImageFile();
} catch (e: IOException) {
e.printStackTrace()
}
// Continue only if the File was successfully created
if (photoFile != null) {
val photoURI = FileProvider.getUriForFile(activity, "com.example.android.fileprovider",
photoFile)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, 0)
}
}
}
private fun copyFile(uri: Uri): File {
var out: OutputStream?
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date());
val imageFileName = "JPEG_" + timeStamp + "_";
val storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
val image = File.createTempFile(
imageFileName,
".jpg",
storageDir
)
out = FileOutputStream(image);
val iStream = activity.contentResolver.openInputStream(uri)
val inputData = getBytes(iStream)
out.write(inputData);
out.close()
currentPhotoPath = image.getAbsolutePath();
return image
}
fun getBytes(inputStream: InputStream): ByteArray {
val byteBuffer = ByteArrayOutputStream()
val bufferSize = 1024
val buffer = ByteArray(bufferSize)
var len = 0
while (len != -1) {
len = inputStream.read(buffer)
if (len == -1) {
break
}
byteBuffer.write(buffer, 0, len)
}
return byteBuffer.toByteArray()
}
private fun pickFromGalery() {
val pickPhoto = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(pickPhoto, 1)//one can be replaced with any action code
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
CAMERA_REQUEST_CODE -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doStartTakePicture()
} else {
Toast.makeText(activity, "Enable camera permission first", Toast.LENGTH_SHORT).show()
}
return
}
}
}
private fun createImageFile(): File {
// Create an image file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date());
val imageFileName = "JPEG_" + timeStamp + "_";
val storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
val image = File.createTempFile(
imageFileName,
".jpg",
storageDir
)
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
override fun onActivityResult(requestCode: Int, resultCode: Int, imageReturnedIntent: Intent?) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent)
when (requestCode) {
0 -> if (resultCode == Activity.RESULT_OK) {
emptyView.visibility = View.GONE
val f = File(currentPhotoPath)
imageView.setImageURI(Uri.fromFile(f))
goToProducts()
}
1 -> if (resultCode == Activity.RESULT_OK) {
emptyView.visibility = View.GONE
val selectedImage = imageReturnedIntent?.data
imageView.setImageURI(selectedImage)
copyFile(selectedImage!!)
goToProducts()
}
}
}
private fun goToProducts() {
val intent = Intent(activity, ProductsActivity::class.java)
intent.putExtra(PRODUCTS_FILE_PATH, currentPhotoPath)
startActivity(intent)
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
*/
interface OnFragmentInteractionListener {
fun onPickupAction(uri: Uri)
}
companion object {
fun newInstance(): PickupFragment {
val fragment = PickupFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
| 1 | null | 1 | 1 | 08a2a864b8c6589e6afcd63899815c3db8de3a0b | 8,233 | draw2fashion | Apache License 2.0 |
app/src/main/java/com/assignment/speedchecker/checker/viewmodel/SpeedInfoViewModel.kt | arunmobiledev | 398,873,821 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Proguard": 1, "JSON": 2, "XML": 72, "Kotlin": 57, "Java": 31} | /*
* Copyright (c) 2021. <NAME>. All rights reserved
*/
package com.assignment.speedchecker.checker.viewmodel
import android.app.Application
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.assignment.speedchecker.MainApplication
import com.assignment.speedchecker.R
import com.assignment.speedchecker.checker.model.SpeedInfoModel
import com.assignment.speedchecker.checker.repo.SpeedInfoDataService
import com.assignment.speedchecker.util.*
import com.assignment.speedchecker.util.speedtest.SpeedTestReport
import com.assignment.speedchecker.util.speedtest.SpeedTestSocket
import com.assignment.speedchecker.util.speedtest.inter.ISpeedTestListener
import com.assignment.speedchecker.util.speedtest.model.SpeedTestError
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import kotlinx.coroutines.*
class SpeedInfoViewModel(private val mFirebaseInstance: FirebaseDatabase, val appUtil: AppUtil, private val speedInfoDataService: SpeedInfoDataService, application: Application, private val gson : Gson, val appData: AppData) : AndroidViewModel(application) {
val toast : SingleLiveEvent<ToastModel> = SingleLiveEvent()
var completeListener : SingleLiveEvent<Pair<String, Boolean>> = SingleLiveEvent()
var speedInfoModel : MutableLiveData<SpeedInfoModel> = MutableLiveData()
private val testUploadFileSize = 5000000 // 1 Mb
private val testDownloadFile = "5M.iso" // 1 Mb
companion object {
private const val TAG : String = "SpeedInfoViewModel"
}
fun updateUploadSpeedTask() {
val startTime = System.currentTimeMillis()
CoroutineScope(Dispatchers.IO).launch {
val speedTestSocket = SpeedTestSocket()
speedTestSocket.addSpeedTestListener(object : ISpeedTestListener {
override fun onCompletion(report: SpeedTestReport) {
val transferTimeInSecs = (System.currentTimeMillis() - startTime) / 1000
val averageTransferRate = report.totalPacketSize / transferTimeInSecs
val averageTransferRateInHumanReadable = appUtil.humanReadableByteCountSI(averageTransferRate * 8)
// Log.d(TAG, "[COMPLETED] rate in octet/s : " + report.transferRateOctet)
// Log.d(TAG, "[COMPLETED] transferTimeInSecs : $transferTimeInSecs")
Log.d(TAG,"[COMPLETED] averageTransferRate : $averageTransferRateInHumanReadable")
Handler(Looper.getMainLooper()).post {
completeListener.value = Pair("upload", true)
val model = speedInfoModel.value as SpeedInfoModel
model.uploadSpeed = averageTransferRateInHumanReadable
speedInfoModel.value = model
}
}
override fun onError(speedTestError: SpeedTestError, errorMessage: String) {
Log.d(TAG, "[Error] onError : $errorMessage%")
Handler(Looper.getMainLooper()).post {
completeListener.value = Pair("upload", false)
}
}
override fun onProgress(percent: Float, report: SpeedTestReport) {
// Log.d(TAG, "[PROGRESS] progress : $percent%")
// Log.d(TAG, "[PROGRESS] rate in octet/s : " + report.transferRateOctet)
val model = speedInfoModel.value as SpeedInfoModel
model.uploadSpeed =
appUtil.humanReadableByteCountSI(report.transferRateOctet.toLong())
Handler(Looper.getMainLooper()).post {
speedInfoModel.value = model
}
}
})
speedTestSocket.startUpload("http://ipv4.ikoula.testdebit.info/", testUploadFileSize)
}
}
fun updateDownloadSpeedTask() {
val startTime = System.currentTimeMillis()
CoroutineScope(Dispatchers.IO).launch {
val speedTestSocket = SpeedTestSocket()
speedTestSocket.addSpeedTestListener(object : ISpeedTestListener {
override fun onCompletion(report: SpeedTestReport) {
val transferTimeInSecs = (System.currentTimeMillis() - startTime) / 1000
val averageTransferRate = report.totalPacketSize / transferTimeInSecs
val averageTransferRateInHumanReadable =
appUtil.humanReadableByteCountSI(averageTransferRate * 8)
// Log.d(TAG, "[COMPLETED] rate in octet/s : " + report.transferRateOctet)
// Log.d(TAG, "[COMPLETED] transferTimeInSecs : $transferTimeInSecs")
Log.d(TAG,"[COMPLETED] averageTransferRate : $averageTransferRateInHumanReadable")
Handler(Looper.getMainLooper()).post {
completeListener.value = Pair("download", true)
val model = speedInfoModel.value as SpeedInfoModel
model.downloadSpeed = averageTransferRateInHumanReadable
speedInfoModel.value = model
}
}
override fun onError(speedTestError: SpeedTestError, errorMessage: String) {
Log.d(TAG, "[Error] onError : $errorMessage%")
Handler(Looper.getMainLooper()).post {
completeListener.value = Pair("download", false)
}
}
override fun onProgress(percent: Float, report: SpeedTestReport) {
// Log.d(TAG, "[PROGRESS] progress : $percent%")
// Log.d(TAG, "[PROGRESS] rate in octet/s : " + report.transferRateOctet)
val model = speedInfoModel.value as SpeedInfoModel
model.downloadSpeed =
appUtil.humanReadableByteCountSI(report.transferRateOctet.toLong())
Handler(Looper.getMainLooper()).post {
speedInfoModel.value = model
}
}
})
speedTestSocket.startDownload("http://ipv4.ikoula.testdebit.info/$testDownloadFile")
}
}
fun updateUser(currentSpeedInfoModel : SpeedInfoModel) {
// get reference to 'users' node
val mFirebaseDatabase = mFirebaseInstance.getReference("users")
// store app title to 'app_title' node
mFirebaseInstance.getReference("app_title").setValue(getApplication<MainApplication>().getString(R.string.app_name))
if (!TextUtils.isEmpty(currentSpeedInfoModel.mobileNumber)) {
mFirebaseDatabase.child(currentSpeedInfoModel.mobileNumber!!).setValue(currentSpeedInfoModel)
mFirebaseDatabase.child(currentSpeedInfoModel.mobileNumber!!).addValueEventListener(object :
ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val speedInfoModel: SpeedInfoModel? = dataSnapshot.getValue(SpeedInfoModel::class.java)
if (speedInfoModel == null) {
Log.e(TAG, "User data is null!")
return
}
Log.e(TAG, "User data is changed!" + speedInfoModel.mobileNumber.toString() + ", " + speedInfoModel.timeStamp)
toast.value = ToastModel(R.drawable.ic_info, "User data updated successfully")
}
override fun onCancelled(error: DatabaseError) {
Log.e(TAG, "Failed to read SpeedInfoModel", error.toException())
}
})
}
}
} | 0 | Kotlin | 0 | 0 | 3b4fd10217c2ba3cff7aa210d018867e5b0f365f | 8,045 | SpeedChecker | Apache License 2.0 |
app/src/main/java/com/qlang/eyepetizer/config/UserConfig.kt | qlang122 | 309,645,125 | false | null | package com.qlang.eyepetizer.config
import android.content.Context
import android.content.SharedPreferences
import android.os.Environment
import com.libs.utils.ByteUtils
import com.qlang.eyepetizer.base.MyApp
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.*
/**
* @author Created by Qlang on 2017/5/26.
*/
object UserConfig {
private val TAG = "UserConfig"
private val FIRST_ENTER = "firstEnter"
private val REGISTER_STATE = "registerState"
private val SERVER_URL = "server_url"
private val DEVICE_NAME = "device_name"
private val VOICE_ENABLE = "voice_anable"
private val DEVICE_SN = "d_sn"
private val SECRET_KEY = "secret_key"
private val USER_NAME = "user_name"
private val USER_PWD = "<PASSWORD>"
private val USER_NICK = "nick_name"
private val LAST_DEVICE_STATE = "last_device_state"
private var mShared: SharedPreferences? = null
private var mEditor: SharedPreferences.Editor? = null
private val dir = File("${Environment.getExternalStorageDirectory().absolutePath}/qlang/${MyApp.instance.packageName}").apply {
if (!exists()) mkdirs()
}
private val configFile = File("${dir.absolutePath}/config").apply { if (!exists()) createNewFile() }
private val properties by lazy { Properties().apply { load(FileInputStream(configFile)) } }
private fun init() {
mShared = mShared
?: MyApp.instance.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE)
mEditor = mEditor ?: mShared?.edit()
}
fun getShared(): SharedPreferences? {
mShared ?: init()
return mShared
}
fun updateProperties() {
mShared = MyApp.instance.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE)
mEditor = mShared?.edit()
properties.apply { load(FileInputStream(configFile)) }
}
@JvmStatic
fun <T : Any> getExternalValue(key: String, tAndDefVal: T): T {
var rtn: T? = tAndDefVal
rtn = when (tAndDefVal) {
is String -> (properties.getProperty(key) ?: tAndDefVal) as? T?
is Int -> (properties.getProperty(key)?.toInt() ?: tAndDefVal) as? T?
is Float -> (properties.getProperty(key)?.toFloat() ?: tAndDefVal) as? T?
is Long -> (properties.getProperty(key)?.toLong() ?: tAndDefVal) as? T?
is Boolean -> (properties.getProperty(key)?.toBoolean() ?: tAndDefVal) as? T?
else -> (properties.getProperty(key) ?: tAndDefVal) as? T?
}
return rtn ?: tAndDefVal
}
@JvmStatic
fun setExternalValue(key: String, `val`: Any) {
try {
properties.load(FileInputStream(configFile))
when (`val`) {
is String -> properties.setProperty(key, `val`)
is Int -> properties.setProperty(key, "${`val`}")
is Boolean -> properties.setProperty(key, `val`.toString())
is Float -> properties.setProperty(key, "${`val`}")
is Long -> properties.setProperty(key, "${`val`}")
else -> properties.setProperty(key, "${`val`}")
}
val fos = FileOutputStream(configFile)
properties.store(fos, null)
fos.flush()
fos.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
@JvmStatic
var isFirstEnter: Boolean
get() = getValue(FIRST_ENTER, 1) == 1
set(`val`) = putValue(FIRST_ENTER, if (`val`) 1 else 0)
@JvmStatic
var deviceSn: String
get() = getValue(DEVICE_SN, "")
set(`val`) = putValue(DEVICE_SN, `val`)
@JvmStatic
var token: String
get() = getValue("token", "")
set(`val`) = putValue("token", `val`)
@JvmStatic
var deviceName: String
get() {
var value = getValue(DEVICE_NAME, "")
if (value.isNullOrEmpty()) {
val hexStr = getExternalValue(DEVICE_NAME, "")
val b = ByteUtils.hexString2bytes(hexStr)
value = b?.let { String(it) } ?: ""
}
return value
}
set(value) {
putValue(DEVICE_NAME, value)
val b = value.toByteArray()
val str = ByteUtils.bytes2HexString(b) ?: ""
setExternalValue(DEVICE_NAME, str)
}
@JvmStatic
var isVoiceEnable: Boolean
get() = getValue(VOICE_ENABLE, 1) == 1
set(`val`) = putValue(VOICE_ENABLE, if (`val`) 1 else 0)
@JvmStatic
var userName: String
set(`val`) = putValue(USER_NAME, `val`)
get() = getValue(USER_NAME, "")
@JvmStatic
var userPwd: String
set(`val`) = putValue(USER_PWD, `val`)
get() = getValue(USER_PWD, "")
@JvmStatic
var nickName: String
set(`val`) = putValue(USER_NICK, `val`)
get() = getValue(USER_NICK, "")
@JvmStatic
fun putValue(key: String, `val`: Any) {
try {
mEditor ?: init()
mEditor?.run {
when (`val`) {
is String -> putString(key, `val`.toString())
is Int -> putInt(key, `val`)
is Boolean -> putBoolean(key, `val`)
is Float -> putFloat(key, `val`)
is Long -> putLong(key, `val`)
else -> putString(key, `val`.toString())
}
val b = commit()
// Log.e("QL", "------putValue----->k:$key v:${`val`} rtn:$b")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
@JvmStatic
fun <T : Any> getValue(key: String, tAndDefVal: T): T {
try {
mEditor ?: init()
var rtn: T? = null
mShared?.run {
rtn = when (tAndDefVal) {
is String -> getString(key, tAndDefVal as? String? ?: "") as T?
is Int -> getInt(key, tAndDefVal as Int? ?: 0) as T?
is Float -> getFloat(key, tAndDefVal as Float? ?: 0f) as T?
is Long -> getLong(key, tAndDefVal as Long? ?: 0L) as T?
is Boolean -> getBoolean(key, tAndDefVal as Boolean? ?: false) as T?
else -> getString(key, tAndDefVal as String? ?: "") as T?
}
}
return rtn ?: tAndDefVal
} catch (e: Exception) {
e.printStackTrace()
return tAndDefVal
}
}
}
| 1 | Kotlin | 3 | 2 | 3eefe4b5734aeb58994ff1af7a1850c7b7740e64 | 6,579 | EyepetizerTv | Apache License 2.0 |
app/src/main/java/org/wikipedia/connectivity/NetworkConnectivityReceiver.kt | greatfire | 460,298,221 | false | null | package org.wikipedia.connectivity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import androidx.core.net.ConnectivityManagerCompat
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.eventplatform.EventPlatformClient
import org.wikipedia.events.NetworkConnectEvent
import java.util.concurrent.TimeUnit
class NetworkConnectivityReceiver : BroadcastReceiver() {
private var online = true
private var lastCheckedMillis: Long = 0
fun isOnline(): Boolean {
if (System.currentTimeMillis() - lastCheckedMillis > ONLINE_CHECK_THRESHOLD_MILLIS) {
updateOnlineState()
lastCheckedMillis = System.currentTimeMillis()
}
return online
}
override fun onReceive(context: Context, intent: Intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
val networkInfo = ConnectivityManagerCompat
.getNetworkInfoFromBroadcast(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager, intent)
updateOnlineState()
if (networkInfo != null && networkInfo.isConnected) {
WikipediaApp.instance.bus.post(NetworkConnectEvent())
}
}
}
private fun updateOnlineState() {
val info = (WikipediaApp.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
online = info != null && info.isConnected
EventPlatformClient.setEnabled(online)
}
companion object {
private val ONLINE_CHECK_THRESHOLD_MILLIS = TimeUnit.MINUTES.toMillis(1)
}
}
| 2 | null | 4 | 38 | 8c8de602274b0132fc5d22b394a2c47fcd0bf2eb | 1,711 | apps-android-wikipedia-envoy | Apache License 2.0 |
sketch/src/main/java/com/github/panpf/sketch/util/AndroidCloseableCompat.kt | fltwlulu | 188,455,050 | false | null | package com.github.panpf.sketch.util
import android.content.res.AssetFileDescriptor
import android.os.Build
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind.EXACTLY_ONCE
import kotlin.contracts.contract
@OptIn(ExperimentalContracts::class)
fun <R> AssetFileDescriptor.useCompat(block: (AssetFileDescriptor) -> R): R {
contract {
callsInPlace(block, EXACTLY_ONCE)
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
this.use(block)
} else {
try {
return block(this)
} catch (e: Throwable) {
throw e
} finally {
try {
close()
} catch (closeException: Throwable) {
// cause.addSuppressed(closeException) // ignored here
}
}
}
}
///**
// * Constant check of api version used during compilation
// *
// * This function is evaluated at compile time to a constant value,
// * so there should be no references to it in other modules.
// *
// * The function usages are validated to have literal argument values.
// */
//@PublishedApi
//@SinceKotlin("1.2")
//internal fun apiVersionIsAtLeast(major: Int, minor: Int, patch: Int) =
// KotlinVersion.CURRENT.isAtLeast(major, minor, patch) | 1 | null | 1 | 1 | c9ff98d80c36d7c4ba5c28bbf358dc8ee53278b1 | 1,293 | sketch | MIT License |
sdk/src/main/java/com/robotemi/sdk/telepresence/Participant.kt | robotemi | 191,618,116 | false | {"Kotlin": 212093, "Java": 58366, "AIDL": 17548} | package com.robotemi.sdk.telepresence
import android.os.Parcel
import android.os.Parcelable
import com.robotemi.sdk.constants.Platform
data class Participant(
val peerId: String,
val platform: Int,
) : Parcelable {
constructor(peerId: String, platform: Platform) : this(peerId, platform.value)
constructor(parcel: Parcel) : this(
parcel.readString()!!,
parcel.readInt()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(peerId)
parcel.writeInt(platform)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Participant> {
override fun createFromParcel(parcel: Parcel): Participant {
return Participant(parcel)
}
override fun newArray(size: Int): Array<Participant?> {
return arrayOfNulls(size)
}
}
} | 128 | Kotlin | 87 | 203 | 8d26d65e97d2b8b7185ec6e7175654d8d3a6c5c9 | 920 | sdk | Apache License 2.0 |
app/src/main/java/com/app/test/Run.kt | sweven-tears | 650,935,527 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Proguard": 2, "XML": 40, "Kotlin": 16, "Java": 72, "JSON": 2, "INI": 1} | package com.app.test
import java.io.File
import java.io.FileWriter
import javax.xml.parsers.DocumentBuilderFactory
open class Run {
companion object {
fun create() {
val file = File("app/src/main/AndroidManifest.xml")
println(file.absoluteFile)
val dbf = DocumentBuilderFactory.newInstance()
val db = dbf.newDocumentBuilder()
val document = db.parse(file)
val `package` = document.documentElement.getAttribute("package")
println(`package`)
val application = document.getElementsByTagName("application")
val activities = application.item(0).ownerDocument.getElementsByTagName("activity")
val importArray = mutableListOf<String>()
println(activities.length)
for (i in 0 until activities.length) {
val namedItem = activities.item(i).attributes.getNamedItem("android:name")
val import = `package` + namedItem.nodeValue
importArray.add(import)
println(import)
}
val builder = StringBuilder("package $`package`")
builder.append("\r\r")
for (imp in importArray) {
builder.append("import $imp").append("\r")
}
builder.append("\r")
builder.append("object Factory {")
builder.append("\r")
builder.append("\tval map = hashMapOf<String, Class<*>>()")
builder.append("\r\r")
builder.append("\tinit {")
builder.append("\r")
for (imp in importArray) {
val index = imp.lastIndexOf(".")
val clazz = imp.substring(index + 1)
var upIndex = 0
clazz.forEachIndexed { index, c ->
if (c.isUpperCase()) {
upIndex = index
}
}
val key = "/${clazz.substring(0, 1).lowercase()}" +
clazz.substring(1, upIndex) +
"/${clazz.substring(upIndex).lowercase()}"
builder.append("\t\tmap[\"$key\"] = $clazz::class.java")
builder.append("\r")
}
builder.append("\t}")
builder.append("\r")
builder.append("}")
val content = builder.toString()
println(content)
val parent = file.parent!! + "\\java\\" + `package`.replace(".", "\\")
val newFile = File(parent, "Factory.kt")
if (!newFile.exists()) {
newFile.createNewFile()
}
try {
val writer = FileWriter(newFile)
// val bw = BufferedWriter(writer)
writer.write(content)
// bw.close()
writer.flush()
writer.close()
} catch (e: Exception) {
e.fillInStackTrace()
}
println(newFile.absoluteFile)
}
}
var a: A? = null
class A {
var b: B? = null
}
class B {
fun print() {
print("b")
}
}
}
fun main() {
Run.create()
} | 0 | Java | 0 | 0 | 4f13cdf9b40b7ff37a85d8ecede8da82680120b9 | 3,211 | kotlin-base | Apache License 2.0 |
src/main/kotlin/io/undefined/FriendOfAppropriateAges.kt | jffiorillo | 138,075,067 | false | null | package io.undefined
import io.utils.runTests
// https://leetcode.com/problems/friends-of-appropriate-ages/
class FriendOfAppropriateAges {
fun execute(input: IntArray): Int {
val count = input.fold(IntArray(121)) { acc, value -> acc.apply { this[value]++ } }
var result = 0
count.forEachIndexed { ageA, numberOfPeople ->
for (ageB in count.indices) {
if (ageA * 0.5 + 7 >= ageB) continue
if (ageA < ageB) continue
result += numberOfPeople * count[ageB]
if (ageA == ageB) result -= numberOfPeople
}
}
return result
}
fun numFriendRequests(input: IntArray): Int {
val numInAge = input.fold(IntArray(121)) { acc, value -> acc.apply { this[value]++ } }
val sumInAge = IntArray(121)
for (i in 1..120) sumInAge[i] = numInAge[i] + sumInAge[i - 1]
var result = 0
for (i in 15..120) {
if (numInAge[i] == 0) continue
val accum = sumInAge[i] - sumInAge[i / 2 + 7]
result += accum * numInAge[i] - numInAge[i] //people will not friend request themselves, so - numInAge[i]
}
return result
}
}
fun main() {
runTests(listOf(
intArrayOf(16, 16) to 2
)) { (input, value) -> value to FriendOfAppropriateAges().execute(input) }
} | 1 | null | 1 | 1 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,244 | coding | MIT License |
src/i_introduction/_5_Nullable_Types/NullableTypes.kt | Jachu5 | 39,684,425 | false | {"Ignore List": 1, "Text": 1, "Markdown": 1, "Kotlin": 109, "Java": 10} | package i_introduction._5_Nullable_Types
import java.io.File
import util.TODO
fun test() {
val s: String = "this variable cannot store null references"
val q: String? = null
fun useNotNullableType(i: Int) {
}
//doesn't compile:
//useNotNullableType(null)
}
fun struggleAgainstNPE() {
val files = File("test").listFiles()
//doesn't compile
//println(files.size)
fun checkForNull1() {
if (files != null) {
files.size()
}
}
fun checkForNull2() {
if (files == null) return
files.size()
}
fun checkForNull3(): Int {
if (files == null) fail()
return files.size()
}
fun nullAsResultIfNullReference(): Int? {
return files?.size()
}
fun defaultValueForNull(): Int {
val size = files?.size()
return size ?: -1
}
fun throwNPEIfNull(): Int {
val f = files!!
return f.size()
}
}
fun fail() = throw Exception()
fun todoTask5(client: Client?, message: String?, mailer: Mailer) {
val personalInfo = client?.personalInfo
val email = personalInfo?.email
//(email != null && message != null) ?: mailer.sendMessage(email,message)
// This is not valid, expected String not String?, sentence below allows
// it since null checking in
// the if statement guarantee the String
if (email != null && message != null) {
mailer.sendMessage(email, message)
}
}
fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) {
todoTask5(client,message,mailer)
}
class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
fun sendMessage(email: String, message: String)
} | 1 | null | 1 | 1 | 0b199de00f2416c59e40ce4af7a8002004e7d1b4 | 1,754 | Koans | MIT License |
src/main/kotlin/net/squarelabs/pgrepl/messages/TxnMsg.kt | avantgardnerio | 112,949,567 | false | null | package net.squarelabs.pgrepl.messages
import net.squarelabs.pgrepl.model.ClientTxn
data class TxnMsg(
val payload: ClientTxn
) {
val type = "TXN"
} | 6 | Kotlin | 1 | 4 | 323304ed85b0497b588ec5f9eeea6cd2933900d9 | 162 | pgrepl | MIT License |
app/src/main/java/com/byd/firstcode/kotlin/four/ListMianActivity.kt | liufangqq | 436,594,629 | false | null | package com.byd.firstcode.kotlin.four
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import com.byd.firstcode.kotlin.R
import kotlinx.android.synthetic.main.activity_list_mian.*
import org.jetbrains.anko.toast
class ListMianActivity : AppCompatActivity() {
// private val data = listOf("Apple", "Banana", "Orange", "water")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_mian)
// val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)
// listView.adapter = adapter
initFruits()
val adapter = FruitAdapter(this, R.layout.fruit_item, fruitList)
listView.adapter = adapter
listView.setOnItemClickListener{ _,_,position,_->
val fruit = fruitList[position]
toast("test")
}
}
private val fruitList = ArrayList<Fruit>()
private fun initFruits() {
repeat(2) {
fruitList.add(Fruit("Apple", R.drawable.switch1))
}
}
} | 0 | Kotlin | 0 | 0 | fcb8f6450a07e4598bf034dbfaaaa47037586107 | 1,135 | TestBYD | Apache License 2.0 |
app/src/main/java/com/tfm/musiccommunityapp/domain/model/PostDomain.kt | luiscruzr8 | 613,985,223 | false | null | package com.tfm.musiccommunityapp.domain.model
import java.time.LocalDate
import java.time.LocalDateTime
data class GenericPostDomain(
val id: Long,
val title: String,
val description: String,
val login: String,
val postType: String,
val createdOn: LocalDateTime,
val tags: List<TagDomain>
)
data class CommentDomain(
val id: Long,
val text: String,
val login: String,
val commentedOn: LocalDateTime,
val responses: List<CommentDomain>
)
data class EventDomain(
val id: Long,
val title: String,
val description: String,
val login: String,
val postType: String,
val cityName: String,
val createdOn: LocalDateTime,
val from: LocalDateTime,
val to: LocalDateTime,
val tags: List<TagDomain>
)
data class AdvertisementDomain(
val id: Long,
val title: String,
val description: String,
val login: String,
val postType: String,
val cityName: String,
val phone: String,
val createdOn: LocalDateTime,
val until: LocalDate,
val tags: List<TagDomain>
)
data class DiscussionDomain(
val id: Long,
val title: String,
val description: String,
val login: String,
val postType: String,
val createdOn: LocalDateTime,
val tags: List<TagDomain>
)
data class OpinionDomain(
val id: Long,
val title: String,
val description: String,
val login: String,
val postType: String,
val scoreId: Long,
val score: ScoreDomain,
val createdOn: LocalDateTime,
val tags: List<TagDomain>
) | 28 | Kotlin | 0 | 1 | e852d00c4b26e54a3f232e1d19b46446dbba4811 | 1,551 | android-musiccommunity | MIT License |
framework/src/main/kotlin/br/com/astrosoft/framework/model/MainQueryBeanGenerator.kt | ivaneyvieira | 154,909,120 | false | null | package br.com.astrosoft.framework.model
import io.ebean.typequery.generator.Generator
import io.ebean.typequery.generator.GeneratorConfig
import java.io.IOException
object MainQueryBeanGenerator {
@Throws(IOException::class)
@JvmStatic
fun main(args: Array<String>) {
val config = GeneratorConfig()
config.lang = "kt"
config.classesDirectory = "./model/out/production/classes/"
//config.classesDirectory = "./model/build/classes/kotlin/main/"
config.destDirectory = "./model/src/main/kotlin"
config.destResourceDirectory = "./model/src/main/resources"
config.entityBeanPackage = "br.com.astrosoft.entradaNF.model"
config.destPackage = "br.com.astrosoft.entradaNF.model.query"
config.isOverwriteExistingFinders = true
val generator = Generator(config)
generator.generateQueryBeans()
// Additionally generate 'finder's
generator.generateFinders()
generator.modifyEntityBeansAddFinderField()
}
} | 0 | Kotlin | 0 | 0 | 28f85092a5d126614a8ba2a2b5ac767782d008ce | 983 | recebimentoNFE | Apache License 2.0 |
app/src/debug/java/app/di/BuildTypeBasedNetworkModule.kt | crow-misia | 125,586,097 | false | {"Kotlin": 28086} | package app.di
import com.facebook.stetho.okhttp3.StethoInterceptor
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import okhttp3.Interceptor
import javax.inject.Singleton
@Module internal class BuildTypeBasedNetworkModule {
@Singleton @Provides @IntoSet
fun provideStetho(): Interceptor = StethoInterceptor()
} | 0 | Kotlin | 0 | 0 | 05021fc463bef4a980e6a647a7ff08887b0d3809 | 354 | android-template | Apache License 2.0 |
subprojects/instant-execution/src/test/kotlin/org/gradle/instantexecution/serialization/codecs/SerializableBeanCodecTest.kt | dhirabayashi | 247,851,701 | true | {"Groovy": 27966695, "Java": 26451047, "Kotlin": 3269750, "C++": 1805886, "JavaScript": 208288, "CSS": 174613, "C": 98580, "HTML": 68883, "XSLT": 42845, "Perl": 37849, "Scala": 27128, "Shell": 7675, "Swift": 6972, "Objective-C": 840, "CoffeeScript": 620, "Objective-C++": 441, "GAP": 424, "Assembly": 277, "Gherkin": 191, "Python": 57, "Brainfuck": 54, "Ruby": 16} | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.serialization.codecs
import com.nhaarman.mockitokotlin2.mock
import org.gradle.api.Project
import org.gradle.instantexecution.problems.PropertyKind
import org.gradle.instantexecution.problems.PropertyTrace
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.sameInstance
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
class SerializableBeanCodecTest : AbstractUserTypeCodecTest() {
@Test
fun `can handle mix of Serializable and plain beans`() {
val bean = Pair(42, "42")
/**
* A [Serializable] object that holds a reference to a plain bean.
**/
val serializable = SerializableWriteObjectBean(bean)
/**
* A plain bean that holds a reference to a serializable object
* sharing a reference to another plain bean.
**/
val beanGraph = Pair(serializable, bean)
val decodedGraph = roundtrip(beanGraph)
val (decodedSerializable, decodedBean) = decodedGraph
assertThat(
"defaultWriteObject / defaultReadObject handles non-transient fields",
decodedSerializable.value,
equalTo(serializable.value)
)
assertThat(
decodedSerializable.transientShort,
equalTo(SerializableWriteObjectBean.EXPECTED_SHORT)
)
assertThat(
decodedSerializable.transientInt,
equalTo(SerializableWriteObjectBean.EXPECTED_INT)
)
assertThat(
decodedSerializable.transientString,
equalTo(SerializableWriteObjectBean.EXPECTED_STRING)
)
assertThat(
decodedSerializable.transientFloat,
equalTo(SerializableWriteObjectBean.EXPECTED_FLOAT)
)
assertThat(
decodedSerializable.transientDouble,
equalTo(SerializableWriteObjectBean.EXPECTED_DOUBLE)
)
assertThat(
"preserves identities across protocols",
decodedSerializable.value,
sameInstance(decodedBean)
)
}
@Test
fun `can handle Serializable writeReplace readResolve`() {
assertThat(
roundtrip(SerializableWriteReplaceBean()).value,
equalTo<Any>("42")
)
}
@Test
fun `can handle Serializable with only writeObject`() {
assertThat(
roundtrip(SerializableWriteObjectOnlyBean()).value,
equalTo<Any>("42")
)
}
@Test
fun `preserves identity of Serializable objects`() {
val writeReplaceBean = SerializableWriteReplaceBean()
val writeObjectBean = SerializableWriteObjectBean(Pair(writeReplaceBean, writeReplaceBean))
val graph = Pair(writeObjectBean, writeObjectBean)
val decodedGraph = roundtrip(graph)
assertThat(
decodedGraph.first,
sameInstance(decodedGraph.second)
)
val decodedPair = decodedGraph.first.value as Pair<*, *>
assertThat(
decodedPair.first,
sameInstance(decodedPair.second)
)
}
@Test
fun `user types codec leaves bean trace of Serializable objects`() {
val bean = SerializableWriteObjectBean(mock<Project>())
val problems = serializationProblemsOf(bean, userTypesCodec())
val fieldTrace = assertInstanceOf<PropertyTrace.Property>(problems.single().trace)
assertThat(
fieldTrace.kind,
equalTo(PropertyKind.Field)
)
assertThat(
fieldTrace.name,
equalTo("value")
)
val beanTrace = assertInstanceOf<PropertyTrace.Bean>(fieldTrace.trace)
assertThat(
beanTrace.type,
sameInstance(bean.javaClass)
)
}
class SerializableWriteReplaceBean(val value: Any? = null) : Serializable {
@Suppress("unused")
private
fun writeReplace() = Memento()
private
class Memento {
@Suppress("unused")
fun readResolve() = SerializableWriteReplaceBean("42")
}
}
class SerializableWriteObjectOnlyBean(var value: Any? = null) : Serializable {
private
fun writeObject(objectOutputStream: ObjectOutputStream) {
value = "42"
objectOutputStream.defaultWriteObject()
}
}
class SerializableWriteObjectBean(val value: Any) : Serializable {
companion object {
const val EXPECTED_SHORT: Short = Short.MAX_VALUE
const val EXPECTED_INT: Int = 42
const val EXPECTED_STRING: String = "42"
const val EXPECTED_FLOAT: Float = 1.618f
const val EXPECTED_DOUBLE: Double = Math.PI
}
@Transient
var transientShort: Short? = null
@Transient
var transientInt: Int? = null
@Transient
var transientString: String? = null
@Transient
var transientFloat: Float? = null
@Transient
var transientDouble: Double? = null
private
fun writeObject(objectOutputStream: ObjectOutputStream) {
objectOutputStream.run {
defaultWriteObject()
writeShort(EXPECTED_SHORT.toInt())
writeInt(EXPECTED_INT)
writeUTF(EXPECTED_STRING)
writeFloat(EXPECTED_FLOAT)
writeDouble(EXPECTED_DOUBLE)
}
}
private
fun readObject(objectInputStream: ObjectInputStream) {
objectInputStream.defaultReadObject()
transientShort = objectInputStream.readShort()
transientInt = objectInputStream.readInt()
transientString = objectInputStream.readUTF()
transientFloat = objectInputStream.readFloat()
transientDouble = objectInputStream.readDouble()
}
}
}
| 0 | Groovy | 0 | 0 | 48f5413877873986be887f5d70b337b7c08b407f | 6,655 | gradle | Apache License 2.0 |
batch/src/main/kotlin/app/visual/log/batch/tasklet/TemplateRegisterTasklet.kt | cxpqwvtj | 96,679,825 | false | null | package app.visual.log.batch.tasklet
import app.visual.log.batch.es.ElasticsearchClient
import app.visual.log.config.AppConfig
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.common.xcontent.XContentFactory
import org.elasticsearch.transport.client.PreBuiltTransportClient
import org.slf4j.LoggerFactory
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.tasklet.Tasklet
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.stereotype.Component
import java.net.InetAddress
/**
* マッピングテンプレート作成タスクレットクラスです。
*/
@Component
class TemplateRegisterTasklet(
val appConfig: AppConfig,
val client: ElasticsearchClient
) : Tasklet {
private val logger = LoggerFactory.getLogger(this.javaClass)
override fun execute(contribution: StepContribution, chunkContext: ChunkContext): RepeatStatus {
logger.debug("${contribution.toString()} ${chunkContext.toString()}")
val client = PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(InetSocketTransportAddress(InetAddress.getByName(appConfig.elasticsearch.transportHost), appConfig.elasticsearch.transportPort))
// @formatter:off
// インデックスとマッピング作成
val response = client.admin().indices().getTemplates(GetIndexTemplatesRequest("logstash-*")).actionGet()
if (response.indexTemplates.isEmpty()) {
logger.debug("テンプレートがありません")
}
client.admin().indices().preparePutTemplate("logstash")
.setTemplate(
XContentFactory.jsonBuilder()
.startObject()
.field("template", "logstash-*")
.startObject("mappings")
.startObject("log")
.startObject("properties")
.startObject("time")
.field("type", "date")
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.string()
).setSettings(Settings.builder()
.put("index.number_of_shards", 10)
.put("index.number_of_replicas", 0)
).get()
// client.admin().indices().prepareCreate(appConfig.analyzedTokenIndexName)
// .addMapping(appConfig.analyzedTokenTypeName, XContentFactory.jsonBuilder()
// .startObject()
// .startObject("doc")
// .startObject("properties")
// .startObject("token")
// .field("type", "keyword")
// .endObject()
// .startObject("index")
// .field("type", "keyword")
// .endObject()
// .startObject("type")
// .field("type", "keyword")
// .endObject()
// .startObject("id")
// .field("type", "keyword")
// .endObject()
// .startObject("filename")
// .field("type", "keyword")
// .endObject()
// .startObject("categoryCode")
// .field("type", "keyword")
// .endObject()
// .startObject("docId")
// .field("type", "keyword")
// .endObject()
// .startObject("startOffset")
// .field("type", "long")
// .endObject()
// .startObject("endOffset")
// .field("type", "long")
// .endObject()
// .startObject("position")
// .field("type", "long")
// .endObject()
// .endObject()
// .endObject()
// .endObject())
// .setSettings(Settings.builder()
// .put("index.number_of_shards", 10)
// .put("index.number_of_replicas", 0)
// .put("index.refresh_interval", -1)
// ).get()
// logger.info("インデックス${appConfig.analyzedTokenIndexName}を作成しました")
// // @formatter:on
// } finally {
// client.close()
return RepeatStatus.FINISHED
}
} | 0 | Kotlin | 0 | 0 | ceb0a5859056439f5a3ae8cf7bbb40c2b7024a2e | 5,350 | visual-log | MIT License |
src/main/kotlin/miragefairy2024/util/Channel.kt | MirageFairy | 721,291,232 | false | {"Kotlin": 574853, "Java": 10164, "Shell": 751} | package miragefairy2024.util
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking
import net.minecraft.network.PacketByteBuf
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.Identifier
abstract class Channel<P>(val packetId: Identifier) {
abstract fun writeToBuf(buf: PacketByteBuf, packet: P)
abstract fun readFromBuf(buf: PacketByteBuf): P
}
fun <P> Channel<P>.sendToClient(player: ServerPlayerEntity, packet: P) {
val buf = PacketByteBufs.create()
this.writeToBuf(buf, packet)
ServerPlayNetworking.send(player, this.packetId, buf)
}
fun <P> Channel<P>.registerServerPacketReceiver(handler: (ServerPlayerEntity, P) -> Unit) {
ServerPlayNetworking.registerGlobalReceiver(this.packetId) { server, player, _, buf, _ ->
val data = this.readFromBuf(buf)
server.execute {
handler(player, data)
}
}
}
| 0 | Kotlin | 1 | 1 | 8ba4226085d367b2c34a4f2a3a41410a3e49a9ee | 969 | MirageFairy2024 | Apache License 2.0 |
shared/src/commonMain/kotlin/com/andigeeky/tripmate/Platform.kt | mamatagelanee07 | 475,798,741 | false | {"Kotlin": 10019, "Ruby": 3366, "Swift": 1030} | package com.andigeeky.tripmate
expect class Platform() {
val platform: String
} | 0 | Kotlin | 0 | 0 | 8bfc169a9dd99f00859071809b53759fdba2e3f5 | 84 | trip-mate | Apache License 2.0 |
pleo-antaeus-models/src/main/kotlin/io/pleo/antaeus/models/PaymentStatus.kt | andersfischernielsen | 331,687,497 | true | {"Kotlin": 28529, "Shell": 861, "Dockerfile": 249} | package io.pleo.antaeus.models
enum class PaymentStatus {
SUCCEEDED,
FAILED
}
| 0 | Kotlin | 0 | 0 | 034745d5d4fb03350b0114d6666f10c1fbbfc391 | 87 | antaeus | Creative Commons Zero v1.0 Universal |
commoncomposeui/src/commonMain/kotlin/PainterRes.kt | oianmol | 528,898,439 | false | {"Kotlin": 752408, "Swift": 113141, "Ruby": 11800, "Shell": 587, "Objective-C": 486, "C": 1} | import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.painter.Painter
import org.jetbrains.compose.resources.*
object PainterRes {
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun gettingStarted(): Painter {
return painterResource("gettingstarted.png")
}
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun slackLogo(): Painter {
return painterResource("ic_launcher_foreground.png")
}
}
| 3 | Kotlin | 21 | 235 | 143f06c11b757641fd3e67809f57dee9f2ffd04b | 489 | SlackComposeMultiplatform | Apache License 2.0 |
app/src/main/java/com/danielefavaro/waround/base/ktx/LocationExt.kt | dfavaro | 338,638,291 | false | null | package com.danielefavaro.waround.base.ktx
import com.google.android.gms.maps.model.LatLng
fun LatLng.toQuery() = StringBuilder().apply {
append(latitude)
append(",")
append(longitude)
}.toString() | 0 | Kotlin | 0 | 0 | 4f27165dd6e3e0bfbb704b56f8fbdbaf04b61fd2 | 211 | waround-android | MIT License |
src/main/kotlin/dev/galiev/sc/items/custom/Darts.kt | GalievDev | 628,931,160 | false | {"Kotlin": 88585, "Java": 6133} | package dev.galiev.sc.items.custom
import dev.galiev.sc.SummerCottage.RANDOM
import dev.galiev.sc.SummerCottage.logger
import dev.galiev.sc.enity.custom.DartsEntity
import net.fabricmc.fabric.api.item.v1.FabricItemSettings
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.projectile.PersistentProjectileEntity
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.sound.SoundCategory
import net.minecraft.sound.SoundEvents
import net.minecraft.stat.Stats
import net.minecraft.util.Hand
import net.minecraft.util.TypedActionResult
import net.minecraft.util.UseAction
import net.minecraft.world.World
class Darts(settings: Settings = FabricItemSettings()) : Item(settings) {
override fun onStoppedUsing(stack: ItemStack, world: World, user: LivingEntity, remainingUseTicks: Int) {
if (user is PlayerEntity) {
val i = getMaxUseTime(stack) - remainingUseTicks
if (i >= 10) {
if (!world.isClient) {
val darts = DartsEntity(world, user, stack)
darts.setVelocity(
user,
user.getPitch(),
user.getYaw(),
0.0f,
1.5f,
1.0f
)
if (user.abilities.creativeMode) {
darts.pickupType = PersistentProjectileEntity.PickupPermission.CREATIVE_ONLY
}
world.spawnEntity(darts)
world.playSoundFromEntity(
null as PlayerEntity?,
darts,
SoundEvents.ENTITY_ARROW_SHOOT,
SoundCategory.PLAYERS,
1.0f,
1.0f
)
if (!user.abilities.creativeMode) user.inventory.removeOne(stack)
}
user.itemCooldownManager[this] = 20
user.incrementStat(Stats.USED.getOrCreateStat(this))
}
}
}
override fun use(world: World?, user: PlayerEntity, hand: Hand?): TypedActionResult<ItemStack> {
val stack = user.getStackInHand(hand)
user.setCurrentHand(hand)
return TypedActionResult.consume(stack)
}
override fun usageTick(world: World?, user: LivingEntity?, stack: ItemStack?, remainingUseTicks: Int) {
if (user is PlayerEntity) {
logger.info("using: ${user.itemUseTime}")
if(user.itemUseTime >= 41) {
if (RANDOM.nextInt(0, 100) <= 89) {
user.yaw += RANDOM.nextInt(-1, 1).toFloat()
user.pitch += RANDOM.nextInt(-1, 1).toFloat()
}
} else {
if (RANDOM.nextInt(0, 100) <= 49) {
user.yaw += RANDOM.nextInt(-1, 1).toFloat()
user.pitch += RANDOM.nextInt(-1, 1).toFloat()
}
}
}
super.usageTick(world, user, stack, remainingUseTicks)
}
override fun getUseAction(stack: ItemStack?): UseAction {
return UseAction.SPEAR
}
override fun getMaxUseTime(stack: ItemStack?): Int {
return 92000
}
} | 0 | Kotlin | 0 | 0 | 5c154c10949b65763e39c69cb26d7bdc3ce9d09d | 3,339 | summer-cottage | MIT License |
app/src/main/java/com/example/inventory/ui/usage/UsageViewModel.kt | giannaSchneider | 630,093,721 | false | null | //package com.example.inventory.ui.usage
//
//import androidx.compose.runtime.getValue
//import androidx.compose.runtime.mutableStateOf
//import androidx.compose.runtime.setValue
//import androidx.lifecycle.SavedStateHandle
//import androidx.lifecycle.ViewModel
//import androidx.lifecycle.viewModelScope
//import com.example.smartpowerconnector_room.internet.idata.AwsRepository
//import com.example.smartpowerconnector_room.internet.idata.UsageData
//import kotlinx.coroutines.flow.SharingStarted
//import kotlinx.coroutines.flow.StateFlow
//import kotlinx.coroutines.flow.filterNotNull
//import kotlinx.coroutines.flow.map
//import kotlinx.coroutines.flow.stateIn
//import kotlinx.coroutines.launch
//import retrofit2.HttpException
//import java.io.IOException
//
///**
// * ViewModel to retrieve, update and delete an timerRoutine from the [RoutinesRepository]'s data source.
// */
//sealed interface AwsUiState{
// data class Success(val iDeviceList: List<UsageData>): AwsUiState
// object Error: AwsUiState
// object Loading: AwsUiState
// //object Updated: AwsUiState
//}
//
//
//class UsageViewModel(private val awsRepository: AwsRepository): ViewModel() {
// var awsUiState: AwsUiState by mutableStateOf(AwsUiState.Loading)
// private set
//
// init{
// getAllDevices()
// }
//
// fun getAllDevices(){
// viewModelScope.launch {
// awsUiState = AwsUiState.Loading
// awsUiState = try{
// AwsUiState.Success(awsRepository.getAllUsage())
// }catch (e: IOException){
// AwsUiState.Error
// }catch(e: HttpException) {
// AwsUiState.Error
// }
// }
// }
//
//
//}
//
| 0 | Kotlin | 0 | 0 | e8d0a9b22be801836c2ad8b37a45560c756e65d9 | 1,726 | SMPApp | Apache License 2.0 |
base/src/main/kotlin/browser/webRequest/OnSendHeadersListener.kt | DATL4G | 372,873,797 | false | null | @file:JsModule("webextension-polyfill")
@file:JsQualifier("webRequest")
package browser.webRequest
/**
* Fired just before a request is going to be sent to the server (modifications of previous
* onBeforeSendHeaders callbacks are visible by the time onSendHeaders is fired).
*/
public external interface OnSendHeadersListener {
public var details: DetailsProperty
}
| 0 | Kotlin | 1 | 37 | ab2a825dd8dd8eb704278f52c603dbdd898d1875 | 373 | Kromex | Apache License 2.0 |
app/src/main/java/org/prography/cakk/navigation/CakkNavigationGraph.kt | Prography-8th-team8 | 625,571,635 | false | {"Kotlin": 177701} | package org.prography.cakk.navigation
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import org.prography.base.BaseBottomDestination
import org.prography.common.navigation.destination.CakkDestination
import org.prography.common.navigation.destination.CakkDestination.Home.DEFAULT_DISTRICTS_INFO
import org.prography.common.navigation.destination.CakkDestination.Home.DEFAULT_STORE_COUNT
import org.prography.common.navigation.destination.CakkDestination.Home.DISTRICTS_INFO
import org.prography.common.navigation.destination.CakkDestination.Home.STORE_COUNT
import org.prography.common.navigation.graph.GraphLabels
import org.prography.designsystem.ui.theme.Light_Deep_Pink
import org.prography.designsystem.ui.theme.Raisin_Black
import org.prography.designsystem.ui.theme.White
import org.prography.designsystem.ui.theme.pretendard
import org.prography.feed.FeedScreen
import org.prography.feed.detail.FeedDetailScreen
import org.prography.home.HomeScreen
import org.prography.home.detail.HomeDetailScreen
import org.prography.my.MyScreen
import org.prography.onboarding.OnBoardingScreen
import org.prography.splash.SplashScreen
import org.prography.utility.extensions.toSp
@Composable
fun CakkNavigationGraph(navController: NavHostController) {
Scaffold(
bottomBar = { CakkBottomBar(navController) }
) { paddingValues ->
NavHost(
navController = navController,
startDestination = CakkDestination.Splash.route,
modifier = Modifier.padding(paddingValues),
route = GraphLabels.ROOT
) {
composable(route = CakkDestination.Splash.route) {
SplashScreen {
navController.navigate(CakkDestination.Home.routeWithArgs) {
popUpTo(CakkDestination.Splash.route) {
inclusive = true
}
}
}
}
composable(
route = CakkDestination.Home.routeWithArgs,
arguments = CakkDestination.Home.arguments
) { navBackStackEntry ->
val districts = navBackStackEntry.arguments?.getString(DISTRICTS_INFO) ?: DEFAULT_DISTRICTS_INFO
val storeCount = navBackStackEntry.arguments?.getInt(STORE_COUNT) ?: DEFAULT_STORE_COUNT
HomeScreen(
districtsArg = districts,
storeCountArg = storeCount,
onNavigateToOnBoarding = {
navController.navigate(CakkDestination.OnBoarding.route) {
popUpTo(CakkDestination.Home.routeWithArgs) {
inclusive = true
}
}
},
onNavigateToDetail = { storeId ->
navController.navigate("${CakkDestination.HomeDetail.route}/$storeId")
}
)
}
composable(
route = CakkDestination.HomeDetail.routeWithArgs,
arguments = CakkDestination.HomeDetail.arguments
) { navBackStackEntry ->
val storeId = navBackStackEntry.arguments?.getInt(CakkDestination.HomeDetail.STORE_ID)
storeId?.let {
HomeDetailScreen(storeId = it) {
navController.popBackStack()
}
}
}
composable(route = CakkDestination.OnBoarding.route) {
OnBoardingScreen { districts, storeCount ->
navController.navigate(
CakkDestination.Home.route + "?" +
"$DISTRICTS_INFO=$districts" + "&" +
"$STORE_COUNT=$storeCount"
) {
popUpTo(CakkDestination.OnBoarding.route) {
inclusive = true
}
}
}
}
composable(route = CakkDestination.Feed.route) {
FeedScreen { storeId ->
navController.navigate("${CakkDestination.FeedDetail.route}/$storeId")
}
}
composable(
route = CakkDestination.FeedDetail.routeWithArgs,
arguments = CakkDestination.FeedDetail.arguments
) { navBackStackEntry ->
val storeId = navBackStackEntry.arguments?.getInt(CakkDestination.FeedDetail.STORE_ID)
storeId?.let {
FeedDetailScreen(
storeId = it,
onNavigateHomeDetail = {
navController.navigate("${CakkDestination.HomeDetail.route}/$storeId")
},
onClose = {
navController.popBackStack()
}
)
}
}
composable(route = CakkDestination.My.route) {
MyScreen(onNavigateToDetail = { storeId ->
navController.navigate("${CakkDestination.HomeDetail.route}/$storeId")
})
}
}
}
}
@Composable
private fun CakkBottomBar(navHostController: NavHostController) {
val bottomDestinations = listOf(
CakkDestination.Home,
CakkDestination.Feed,
CakkDestination.My
)
val navBackStackEntry by navHostController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
val hasBottomNavigation = bottomDestinations.any { destination ->
currentDestination?.route == when (destination) {
is CakkDestination.Home -> destination.routeWithArgs
CakkDestination.Feed -> destination.route
CakkDestination.My -> destination.route
else -> IllegalStateException()
}
}
if (hasBottomNavigation) {
BottomNavigation(
modifier = Modifier.fillMaxWidth(),
backgroundColor = White
) {
bottomDestinations.forEach { bottomDestination ->
CakkBottomBarItem(
bottomDestination = bottomDestination,
currentDestination = currentDestination,
navHostController = navHostController
)
}
}
}
}
@Composable
private fun RowScope.CakkBottomBarItem(
bottomDestination: CakkDestination,
currentDestination: NavDestination?,
navHostController: NavHostController
) {
check(bottomDestination is BaseBottomDestination)
val destinationRoute = when (bottomDestination) {
is CakkDestination.Home -> bottomDestination.routeWithArgs
CakkDestination.Feed -> bottomDestination.route
CakkDestination.My -> bottomDestination.route
else -> throw java.lang.IllegalStateException()
}
val selected = currentDestination?.route == destinationRoute
BottomNavigationItem(
selected = selected,
onClick = {
navHostController.navigate(destinationRoute) {
popUpTo(destinationRoute) {
inclusive = false
}
launchSingleTop = true
}
},
icon = {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Spacer(
modifier = Modifier
.padding(bottom = 8.dp)
.size(56.dp, 2.dp)
.background(if (selected) Light_Deep_Pink else Color.Transparent)
)
Icon(
painter = painterResource(bottomDestination.icon),
contentDescription = null,
modifier = Modifier.size(22.dp),
tint = if (selected) Light_Deep_Pink else Color.Unspecified
)
}
},
label = {
Text(
text = bottomDestination.label,
color = Raisin_Black.copy(alpha = if (selected) 0.8f else 0.4f),
fontSize = 10.dp.toSp(),
fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
fontFamily = pretendard
)
}
)
}
| 5 | Kotlin | 1 | 2 | 56eb28bcb217712d600365ef3faaecfe3eae248a | 9,476 | Cakk-AOS | Apache License 2.0 |
data/src/main/java/com/roxana/recipeapp/data/recipecreation/RecipeCreationSerializer.kt | roxanapirlea | 383,507,335 | false | null | package com.roxana.recipeapp.data.recipecreation
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import com.google.protobuf.InvalidProtocolBufferException
import com.roxana.recipeapp.data.RecipeCreation
import java.io.InputStream
import java.io.OutputStream
object RecipeCreationSerializer : Serializer<RecipeCreation> {
override val defaultValue: RecipeCreation = RecipeCreation.getDefaultInstance()
override suspend fun readFrom(input: InputStream): RecipeCreation {
try {
return RecipeCreation.parseFrom(input)
} catch (exception: InvalidProtocolBufferException) {
throw CorruptionException("Cannot read recipe proto.", exception)
}
}
override suspend fun writeTo(
t: RecipeCreation,
output: OutputStream
) = t.writeTo(output)
}
| 0 | Kotlin | 0 | 1 | 8dc3e7040d806893dddd4538e15dd3a40faa80a4 | 865 | RecipeApp | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.