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
klue-runtime-webview/src/iosMain/kotlin/com/bennyhuo/klue/webview/IosWebViewBridge.kt
bennyhuo
510,040,663
false
{"Kotlin": 62501, "Swift": 9327, "Ruby": 3696, "JavaScript": 2398, "Smarty": 1265, "HTML": 1038, "Objective-C": 312}
package com.bennyhuo.klue.webview import com.bennyhuo.klue.common.invoke.KlueFunctionInfo import com.bennyhuo.klue.common.invoke.KlueFunctionResult import com.bennyhuo.klue.common.utils.KLUE_BRIDGE_NAME import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import platform.Foundation.NSLog import platform.WebKit.WKWebView /** * Created by benny at 2022/7/19 22:56. */ class IosWebViewBridge(val webView: WKWebView): WebViewBridge() { private val messageHandler = KlueMessageHandler(this) init { webView.configuration.userContentController.addScriptMessageHandler(messageHandler, KLUE_BRIDGE_NAME) } fun callNative(value: String) { NSLog("Klue: value, ${value.length} -- $value") call(value) } override fun returnToJs(functionInfo: KlueFunctionInfo, result: KlueFunctionResult) { webView.evaluateJavaScript("${functionInfo.callback}(${Json.encodeToString(result)})", null) } }
0
Kotlin
0
46
025390fa1b0a861240cc4cd82b0a84db013ff75f
973
Klue
MIT License
src/main/java/com/omegas/controller/StartController.kt
omegas82128
266,275,755
false
null
package com.omegas.controller import com.omegas.controller.control.OpenSettingsControl import com.omegas.main.Main.Companion.stage import com.omegas.main.Main.Companion.startAikino import javafx.fxml.Initializable import javafx.stage.DirectoryChooser import java.awt.Desktop import java.net.URI import java.net.URL import java.util.* import kotlin.system.exitProcess /** * @author Muhammad Haris * */ class StartController : Initializable, OpenSettingsControl() { override fun initialize(location: URL?, resources: ResourceBundle?) { } fun start() { val directoryChooser = DirectoryChooser() directoryChooser.title = "Choose a Movie or TV series folder" val file = directoryChooser.showDialog(stage) file?.let { startAikino( mutableListOf(it.absolutePath) ) } } fun faq() { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(URI("https://github.com/omegas82128/aikino#faq")) } } fun support() { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(URI("https://discord.gg/rKAWJhGjxm")) } } fun exit() { exitProcess(0) } }
4
Kotlin
0
9
c9517b802c879cc65750b91f8a7e4fad0397e5cf
1,238
Aikino
Apache License 2.0
misk-config/src/test/kotlin/misk/config/MiskConfigTest.kt
cashapp
113,107,217
false
{"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58}
package misk.config import com.fasterxml.jackson.databind.ObjectMapper import com.google.inject.util.Modules import jakarta.inject.Inject import misk.environment.DeploymentModule import misk.logging.LogCollectorModule import misk.logging.LogCollectorService import misk.testing.MiskTest import misk.testing.MiskTestModule import misk.web.WebConfig import misk.web.exceptions.ActionExceptionLogLevelConfig import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.slf4j.event.Level import wisp.deployment.TESTING import wisp.logging.LogCollector import java.io.File import java.time.Duration import kotlin.test.assertFails import kotlin.test.assertFailsWith @MiskTest class MiskConfigTest { val config = MiskConfig.load<TestConfig>("test_app", TESTING) @MiskTestModule val module = Modules.combine( ConfigModule.create("test_app", config), DeploymentModule(TESTING), LogCollectorModule() // @TODO(jwilson) https://github.com/square/misk/issues/272 ) @Inject private lateinit var testConfig: TestConfig @Inject private lateinit var logCollector: LogCollector @Inject private lateinit var logCollectorService: LogCollectorService @BeforeEach fun setUp() { logCollectorService.startAsync() } @AfterEach fun tearDown() { logCollectorService.stopAsync() } @Test fun configIsProperlyParsed() { assertThat(testConfig.web).isEqualTo(WebConfig(5678, 30_000)) assertThat(testConfig.consumer_a).isEqualTo(ConsumerConfig(0, 1)) assertThat(testConfig.consumer_b).isEqualTo(ConsumerConfig(1, 2)) assertThat(testConfig.duration).isEqualTo(DurationConfig(Duration.parse("PT1S"))) assertThat((testConfig.action_exception_log_level)).isEqualTo( ActionExceptionLogLevelConfig(Level.INFO, Level.ERROR) ) } @Test fun environmentConfigOverridesCommon() { assertThat(testConfig.web.port).isEqualTo(5678) } @Test fun defaultValuesAreUsed() { assertThat(testConfig.consumer_a.min_items).isEqualTo(0) } @Test fun friendlyErrorMessagesWhenFilesNotFound() { val exception = assertFailsWith<IllegalStateException> { MiskConfig.load<TestConfig>("missing", TESTING) } assertThat(exception).hasMessageContaining( "could not find configuration files -" + " checked [classpath:/missing-common.yaml, classpath:/missing-testing.yaml]" ) } @Test fun friendlyErrorMessageWhenConfigPropertyMissing() { val exception = assertFailsWith<IllegalStateException> { MiskConfig.load<TestConfig>("partial_test_app", TESTING) } assertThat(exception).hasMessageContaining( "could not find 'consumer_a' of 'TestConfig' in partial_test_app-testing.yaml" ) } @Test fun friendErrorMessageWhenConfigPropertyMissingInList() { val exception = assertFailsWith<IllegalStateException> { MiskConfig.load<TestConfig>("missing_property_in_list", TESTING) } assertThat(exception).hasMessageContaining( "could not find 'collection.0.name' of 'TestConfig' in missing_property_in_list-testing.yaml" ) } @Test fun friendlyErrorMessagesWhenFileUnparseable() { val exception = assertFailsWith<IllegalStateException> { MiskConfig.load<TestConfig>("unparsable", TESTING) } assertThat(exception).hasMessageContaining("could not parse classpath:/unparsable-common.yaml") } @Test fun friendlyLogsWhenPropertiesNotFound() { // By default, unknown properties don't cause an exception. If a missing property were misspelled, it // would fail because of it being a missing property, rather than due to a new property being // present. MiskConfig.load<TestConfig>("unknownproperty", TESTING) assertThat(logCollector.takeMessages(MiskConfig::class)) .hasSize(1) .allMatch { it.contains("'consumer_b.blue_items' not found") } } @Test fun failsWhenPropertiesNotFoundAndFailOnUnknownPropertiesIsEnabled() { val exception = assertFailsWith<IllegalStateException> { MiskConfig.load<TestConfig>( TestConfig::class.java, "unknownproperty", TESTING, failOnUnknownProperties = true ) } assertThat(exception).hasMessageContaining("Unrecognized field \"blue_items\"") } @Test fun friendLogsWhenConfigPropertyNotFoundInList() { MiskConfig.load<TestConfig>("unknownproperty_in_list", TESTING) assertThat(logCollector.takeMessages(MiskConfig::class)) .hasSize(1) .allMatch { it.contains("'collection.0.power_level' not found") } } @Test fun misspelledRequiredPrimitivePropertiesFail() { val exception = assertFailsWith<IllegalStateException> { MiskConfig.load<TestConfig>("misspelledproperty", TESTING) } assertThat(exception).hasMessageContaining( "could not find 'consumer_b.max_items' of 'TestConfig' in misspelledproperty-testing.yaml" ) // Also contains a message about similar properties that it had found. assertThat(exception).hasMessageContaining("consumer_b.mox_items") } @Test fun misspelledRequiredObjectPropertiesFail() { val exception = assertFailsWith<IllegalStateException> { MiskConfig.load<TestConfig>("misspelledobject", TESTING) } assertThat(exception).hasMessageContaining( "could not find 'duration.interval' of 'TestConfig' in misspelledobject-testing.yaml" ) // Also contains a message about similar properties that it had found. assertThat(exception).hasMessageContaining("duration.intervel") } @Test fun misspelledRequiredStringPropertiesFail() { val exception = assertFailsWith<IllegalStateException> { MiskConfig.load<TestConfig>("misspelledstring", TESTING) } assertThat(exception).hasMessageContaining( "could not find 'nested.child_nested.nested_value' of 'TestConfig' in misspelledstring-testing.yaml" ) // Also contains a message about similar properties that it had found. assertThat(exception).hasMessageContaining("nested.child_nested.nexted_value") } @Test fun mergesExternalFiles() { val overrides = listOf( MiskConfigTest::class.java.getResource("/overrides/override-test-app1.yaml"), MiskConfigTest::class.java.getResource("/overrides/override-test-app2.yaml") ) .map { File(it.file) } val config = MiskConfig.load<TestConfig>("test_app", TESTING, overrides) assertThat(config.consumer_a).isEqualTo(ConsumerConfig(14, 27)) assertThat(config.consumer_b).isEqualTo(ConsumerConfig(34, 122)) } @Test fun mergesResources() { val overrides = listOf( "classpath:/overrides/override-test-app1.yaml", "classpath:/overrides/override-test-app2.yaml" ) val config = MiskConfig.load<TestConfig>("test_app", TESTING, overrides) assertThat(config.consumer_a).isEqualTo(ConsumerConfig(14, 27)) assertThat(config.consumer_b).isEqualTo(ConsumerConfig(34, 122)) } @Test fun mergesResourcesAndFiles() { val file = MiskConfigTest::class.java.getResource("/overrides/override-test-app1.yaml")!!.file val overrides = listOf( "filesystem:${file}", "classpath:/overrides/override-test-app2.yaml" ) val config = MiskConfig.load<TestConfig>("test_app", TESTING, overrides) assertThat(config.consumer_a).isEqualTo(ConsumerConfig(14, 27)) assertThat(config.consumer_b).isEqualTo(ConsumerConfig(34, 122)) } @Test fun mergesJsonNode() { val overrideString = """{ "consumer_a": { "min_items": "12", "max_items": 86 }}""" val overrideValue = ObjectMapper().readTree(overrideString) val config = MiskConfig.load<TestConfig>("test_app", TESTING, listOf(), overrideValue) assertThat(config.consumer_a).isEqualTo(ConsumerConfig(12, 86)) assertThat(config.consumer_b).isEqualTo(ConsumerConfig(1, 2)) } @Test fun mergesResourcesAndJsonNode() { val overrideString = """{ "consumer_a": { "min_items": "12", "max_items": 86 }}""" val overrideValue = ObjectMapper().readTree(overrideString) val file = MiskConfigTest::class.java.getResource("/overrides/override-test-app1.yaml")!!.file val overrideResources = listOf( "filesystem:${file}", "classpath:/overrides/override-test-app2.yaml" ) val config = MiskConfig.load<TestConfig>("test_app", TESTING, overrideResources, overrideValue) assertThat(config.consumer_a).isEqualTo(ConsumerConfig(12, 86)) assertThat(config.consumer_b).isEqualTo(ConsumerConfig(34, 122)) } @Test fun findsFilesInDir() { val dir = MiskConfigTest::class.java.getResource("/overrides").file val filesInDir = MiskConfig.filesInDir(dir).map { it.absolutePath } assertThat(filesInDir).hasSize(2) // NB(mmihic): These are absolute paths, so we can only look at the end which is consistent assertThat(filesInDir[0]).endsWith("/overrides/override-test-app1.yaml") assertThat(filesInDir[1]).endsWith("/overrides/override-test-app2.yaml") } @Test fun handlesDuplicateNamedExternalFiles() { val overrides = listOf( MiskConfigTest::class.java.getResource("/overrides/override-test-app1.yaml"), MiskConfigTest::class.java.getResource("/additional_overrides/override-test-app1.yaml") ) .map { File(it.file) } val config = MiskConfig.load<TestConfig>("test_app", TESTING, overrides) assertThat(config.consumer_a).isEqualTo(ConsumerConfig(14, 27)) assertThat(config.consumer_b).isEqualTo(ConsumerConfig(34, 79)) } @Test fun handlesNonExistentExternalFile() { // A common config does not exist, but the testing config does, loading the config should not fail val config = MiskConfig.load<DurationConfig>("no_common_config_app", TESTING, listOf<File>()) assertThat(config.interval).isEqualTo(Duration.ofSeconds(23)) } }
169
Kotlin
169
400
13dcba0c4e69cc2856021270c99857e7e91af27d
9,876
misk
Apache License 2.0
ergo-runtime/src/main/kotlin/headout/oss/ergo/models/RequestMsg.kt
headout
265,479,506
false
{"Kotlin": 111337}
package headout.oss.ergo.models import headout.oss.ergo.annotations.TaskId import java.util.* /** * Created by shivanshs9 on 29/05/20. */ data class RequestMsg<T>(val taskId: TaskId, val jobId: JobId, val message: T) { val receiveTimestamp = Date() override fun toString(): String { return "RequestMsg(taskId=$taskId, jobId=$jobId)" } }
3
Kotlin
2
6
a02884f90093a11eca291a70123b0c832c84802a
361
ergo-kotlin
MIT License
stream-chat-android-ui-components-sample/src/main/kotlin/io/getstream/chat/ui/sample/data/user/UserRepository.kt
GetStream
177,873,527
false
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
/* * Copyright (c) 2014-2022 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-chat-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.chat.ui.sample.data.user import android.content.Context import android.content.SharedPreferences class UserRepository(context: Context) { private val prefs: SharedPreferences by lazy { context.getSharedPreferences(USER_PREFS_NAME, Context.MODE_PRIVATE) } fun getUser(): SampleUser { val apiKey = prefs.getString(KEY_API_KEY, null) val id = prefs.getString(KEY_ID, null) val name = prefs.getString(KEY_NAME, null) val token = prefs.getString(KEY_TOKEN, null) val image = prefs.getString(KEY_IMAGE, null) return if (apiKey != null && id != null && name != null && token != null && image != null) { SampleUser(apiKey = apiKey, id = id, name = name, token = token, image = image) } else { SampleUser.None } } fun setUser(user: SampleUser) { prefs.edit() .putString(KEY_API_KEY, user.apiKey) .putString(KEY_ID, user.id) .putString(KEY_NAME, user.name) .putString(KEY_TOKEN, user.token) .putString(KEY_IMAGE, user.image) .apply() } fun clearUser() { prefs.edit().clear().apply() } private companion object { private const val USER_PREFS_NAME = "logged_in_user" private const val KEY_API_KEY = "api_key" private const val KEY_ID = "id" private const val KEY_NAME = "name" private const val KEY_TOKEN = "token" private const val KEY_IMAGE = "image" } }
24
Kotlin
273
1,451
8e46f46a68810d8086c48a88f0fff29faa2629eb
2,168
stream-chat-android
FSF All Permissive License
app/src/main/java/com/nafanya/mp3world/core/listManagers/ListManager.kt
AlexSoWhite
445,900,000
false
{"Kotlin": 324834}
package com.nafanya.mp3world.core.listManagers import com.nafanya.mp3world.core.wrappers.playlist.PlaylistWrapper import kotlinx.coroutines.flow.Flow interface ListManager { fun getPlaylistByContainerId(id: Long): Flow<PlaylistWrapper> }
0
Kotlin
0
0
ee7cff2c21e4731caeb3064c21cc89fcfc8a49c2
245
mp3world
MIT License
src/main/kotlin/io/github/robinnunkesser/explicitarchitecture/tunesearch/core/ports/TunesSearchEngine.kt
RobinNunkesser
371,297,954
false
null
package io.github.robinnunkesser.explicitarchitecture.tunesearch.core.ports interface TunesSearchEngine { suspend fun getSongs(term: String): List<TrackEntity> }
0
Kotlin
0
0
9e2962c896b93916343e8e90c1c73a708cd43195
166
explicitarchitecture-tunesearch-core-ports-mvn
Apache License 2.0
app/src/main/java/io/github/gmathi/novellibrary/activity/ChaptersActivity.kt
rakushah
111,003,184
true
{"Kotlin": 418319, "Java": 14788}
package io.github.gmathi.novellibrary.activity import android.annotation.SuppressLint import android.content.Intent import android.graphics.Rect import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.view.ActionMode import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.RecyclerView import android.view.Menu import android.view.MenuItem import android.view.View import android.view.animation.AnimationUtils import co.metalab.asyncawait.async import com.afollestad.materialdialogs.MaterialDialog import com.github.johnpersano.supertoasts.library.Style import com.github.johnpersano.supertoasts.library.SuperActivityToast import com.github.johnpersano.supertoasts.library.utils.PaletteUtils import com.hanks.library.AnimateCheckBox import io.github.gmathi.novellibrary.R import io.github.gmathi.novellibrary.adapter.GenericAdapterWithDragListener import io.github.gmathi.novellibrary.dataCenter import io.github.gmathi.novellibrary.database.* import io.github.gmathi.novellibrary.dbHelper import io.github.gmathi.novellibrary.model.EventType import io.github.gmathi.novellibrary.model.Novel import io.github.gmathi.novellibrary.model.NovelEvent import io.github.gmathi.novellibrary.model.WebPage import io.github.gmathi.novellibrary.network.NovelApi import io.github.gmathi.novellibrary.network.getChapterUrls import io.github.gmathi.novellibrary.service.download.DownloadChapterService import io.github.gmathi.novellibrary.service.download.DownloadNovelService import io.github.gmathi.novellibrary.util.Constants import io.github.gmathi.novellibrary.util.Utils import io.github.gmathi.novellibrary.util.setDefaultsNoAnimation import kotlinx.android.synthetic.main.activity_chapters.* import kotlinx.android.synthetic.main.content_chapters.* import kotlinx.android.synthetic.main.listitem_chapter_ultimate.view.* import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode class ChaptersActivity : BaseActivity(), GenericAdapterWithDragListener.Listener<WebPage>, ActionMode.Callback, AnimateCheckBox.OnCheckedChangeListener { lateinit var novel: Novel lateinit var adapter: GenericAdapterWithDragListener<WebPage> private var isSortedAsc: Boolean = true private var updateSet: HashSet<WebPage> = HashSet() private var removeDownloadMenuIcon: Boolean = false private var actionMode: ActionMode? = null private var confirmDialog: MaterialDialog? = null private var counter = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chapters) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) novel = intent.getSerializableExtra("novel") as Novel val dbNovel = dbHelper.getNovel(novel.name!!) if (dbNovel != null) novel.copyFrom(dbNovel) setRecyclerView() if (novel.id != -1L) setDownloadStatus() setData() } private fun setRecyclerView() { adapter = GenericAdapterWithDragListener(items = ArrayList(), layoutResId = R.layout.listitem_chapter_ultimate, listener = this) dragSelectRecyclerView.setDefaultsNoAnimation(adapter) dragSelectRecyclerView.addItemDecoration(object : DividerItemDecoration(this, VERTICAL) { override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { val position = parent?.getChildAdapterPosition(view) if (position == parent?.adapter?.itemCount?.minus(1)) { outRect?.setEmpty() } else { super.getItemOffsets(outRect, view, parent, state) } } }) swipeRefreshLayout.isEnabled = false swipeRefreshLayout.setOnRefreshListener { getChapters() } } private fun setData() { progressLayout.showLoading() getChaptersFromDB() } private fun getChaptersFromDB() { async { val chapters = await { ArrayList(dbHelper.getAllWebPages(novel.id)) } adapter.updateData(chapters) scrollToBookmark() if (adapter.items.isEmpty()) { progressLayout.showLoading() getChapters() } else { swipeRefreshLayout.isRefreshing = false progressLayout.showContent() if (adapter.items.size < novel.chapterCount.toInt()) { swipeRefreshLayout.isRefreshing = true getChapters() } } } } private fun getChapters() { async chapters@ { if (!Utils.checkNetwork(this@ChaptersActivity)) { if (adapter.items.isEmpty()) progressLayout.showError(ContextCompat.getDrawable(this@ChaptersActivity, R.drawable.ic_warning_white_vector), getString(R.string.no_internet), getString(R.string.try_again), { progressLayout.showLoading() getChapters() }) return@chapters } //Download latest chapters from network try { val chapterList = await { NovelApi().getChapterUrls(novel)?.reversed() } if (chapterList != null) { if (novel.id != -1L) { await { novel.chapterCount = chapterList.size.toLong() novel.newChapterCount = chapterList.size.toLong() dbHelper.updateNovel(novel) } await { dbHelper.addWebPages(chapterList, novel) } getChaptersFromDB() } else { adapter.updateData(ArrayList(chapterList)) swipeRefreshLayout.isRefreshing = false progressLayout.showContent() } } } catch (e: Exception) { e.printStackTrace() if (progressLayout.isLoading) progressLayout.showError(ContextCompat.getDrawable(this@ChaptersActivity, R.drawable.ic_warning_white_vector), getString(R.string.failed_to_load_url), getString(R.string.try_again), { progressLayout.showLoading() getChapters() }) } } } private fun scrollToBookmark() { if (novel.currentWebPageId != -1L) { val index = adapter.items.indexOfFirst { it.id == novel.currentWebPageId } if (index != -1) dragSelectRecyclerView.scrollToPosition(index) } } //region Adapter Listener Methods - onItemClick(), viewBinder() override fun onItemSelected(position: Int, selected: Boolean) { if (dragSelectRecyclerView.findViewHolderForAdapterPosition(position) != null) { @Suppress("UNCHECKED_CAST") (dragSelectRecyclerView.findViewHolderForAdapterPosition(position) as GenericAdapterWithDragListener.ViewHolder<WebPage>) .itemView?.chapterCheckBox?.isChecked = selected } else { val webPage = adapter.items[position] if (selected) addToUpdateSet(webPage) else removeFromUpdateSet(webPage) } } override fun onItemClick(item: WebPage) { if (novel.id != -1L) { novel.currentWebPageId = item.id dbHelper.updateNovel(novel) startReaderPagerDBActivity(novel) } else startReaderPagerActivity(novel, item, adapter.items) } @SuppressLint("SetTextI18n") override fun bind(item: WebPage, itemView: View, position: Int) { if (item.filePath != null) { itemView.greenView.visibility = View.VISIBLE itemView.greenView.setBackgroundColor(ContextCompat.getColor(this@ChaptersActivity, R.color.DarkGreen)) itemView.greenView.animation = null } else { if (Constants.STATUS_DOWNLOAD.toString() == item.metaData[Constants.DOWNLOADING]) { if (item.id != -1L && DownloadChapterService.chapters.contains(item)) { itemView.greenView.visibility = View.VISIBLE itemView.greenView.setBackgroundColor(ContextCompat.getColor(this@ChaptersActivity, R.color.white)) itemView.greenView.startAnimation(AnimationUtils.loadAnimation(this@ChaptersActivity, R.anim.alpha_animation)) } else { itemView.greenView.visibility = View.VISIBLE itemView.greenView.setBackgroundColor(ContextCompat.getColor(this@ChaptersActivity, R.color.Red)) itemView.greenView.animation = null } } else itemView.greenView.visibility = View.GONE } itemView.isReadView.visibility = if (item.isRead == 1) View.VISIBLE else View.GONE itemView.bookmarkView.visibility = if (item.id != -1L && item.id == novel.currentWebPageId) View.VISIBLE else View.INVISIBLE if (item.chapter != null) itemView.chapterTitle.text = item.chapter if (item.title != null) { if ((item.chapter != null) && item.title!!.contains(item.chapter!!)) itemView.chapterTitle.text = item.title else itemView.chapterTitle.text = "${item.chapter}: ${item.title}" } //itemView.chapterCheckBox.visibility = if (novel.id != -1L) View.VISIBLE else View.GONE itemView.chapterCheckBox.isChecked = updateSet.contains(item) itemView.chapterCheckBox.tag = item itemView.chapterCheckBox.setOnCheckedChangeListener(this@ChaptersActivity) // itemView.chapterCheckBox.setOnLongClickListener { // dragSelectRecyclerView.setDragSelectActive(true, position) // } itemView.setOnLongClickListener { dragSelectRecyclerView.setDragSelectActive(true, position) // if (item.redirectedUrl != null) // [email protected](item.redirectedUrl!!) // else // [email protected](item.url!!) true } } override fun onCheckedChanged(buttonView: View?, isChecked: Boolean) { val webPage = (buttonView?.tag as WebPage?) ?: return // If Novel is not in Library if (novel.id == -1L) { if (isChecked) confirmDialog(getString(R.string.add_to_library_dialog_content, novel.name), MaterialDialog.SingleButtonCallback { dialog, _ -> addNovelToLibrary() invalidateOptionsMenu() addToUpdateSet(webPage) dialog.dismiss() }, MaterialDialog.SingleButtonCallback { dialog, _ -> removeFromUpdateSet(webPage) adapter.notifyDataSetChanged() dialog.dismiss() }) } //If Novel is already in library else { if (isChecked) addToUpdateSet(webPage) else removeFromUpdateSet(webPage) } } //endregion //region ActionMode Callback private fun selectAll() { adapter.items.filter { it.id != -1L }.forEach { addToUpdateSet(it) } adapter.notifyDataSetChanged() } private fun clearSelection() { adapter.items.filter { it.id != -1L }.forEach { removeFromUpdateSet(it) } adapter.notifyDataSetChanged() } private fun addToUpdateSet(webPage: WebPage) { if (webPage.id != -1L) updateSet.add(webPage) if (updateSet.isNotEmpty() && actionMode == null) { actionMode = startSupportActionMode(this) } actionMode?.title = getString(R.string.chapters_selected, updateSet.size) } private fun removeFromUpdateSet(webPage: WebPage) { updateSet.remove(webPage) actionMode?.title = getString(R.string.chapters_selected, updateSet.size) if (updateSet.isEmpty()) { actionMode?.finish() } } override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean { when (item?.itemId) { R.id.action_unread -> { confirmDialog(getString(R.string.mark_chapters_unread_dialog_content), MaterialDialog.SingleButtonCallback { dialog, _ -> updateSet.forEach { it.isRead = 0 dbHelper.updateWebPageReadStatus(it) } dialog.dismiss() mode?.finish() }) } R.id.action_read -> { confirmDialog(getString(R.string.mark_chapters_read_dialog_content), MaterialDialog.SingleButtonCallback { dialog, _ -> updateSet.forEach { it.isRead = 1 dbHelper.updateWebPageReadStatus(it) } dialog.dismiss() mode?.finish() }) } R.id.action_download -> { confirmDialog(getString(R.string.download_chapters_dialog_content), MaterialDialog.SingleButtonCallback { dialog, _ -> if (novel.id == -1L) { showNotInLibraryDialog() } else { val listToDownload = ArrayList(updateSet.filter { it.filePath == null }) if (listToDownload.isNotEmpty()) { startChapterDownloadService(novel, ArrayList(updateSet.filter { it.filePath == null })) SuperActivityToast.create(this@ChaptersActivity, Style(), Style.TYPE_STANDARD) .setText(getString(R.string.background_chapter_downloads)) .setDuration(Style.DURATION_LONG) .setFrame(Style.FRAME_KITKAT) .setColor(PaletteUtils.getSolidColor(PaletteUtils.MATERIAL_GREEN)) .setAnimations(Style.ANIMATIONS_POP).show() } dialog.dismiss() mode?.finish() } }) } R.id.action_select_all -> { selectAll() } R.id.action_clear_selection -> { clearSelection() } R.id.action_share_chapter -> { val urls = updateSet.map { if (it.redirectedUrl != null) it.redirectedUrl!! else it.url!! }.joinToString(separator = ", ") shareUrl(urls) } } return false } override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean { mode?.menuInflater?.inflate(R.menu.menu_chapters_action_mode, menu) return true } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { menu?.findItem(R.id.action_download)?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) return true } override fun onDestroyActionMode(mode: ActionMode?) { updateSet.clear() actionMode = null adapter.notifyDataSetChanged() } //endregion //region Dialogs private fun confirmDialog(content: String, callback: MaterialDialog.SingleButtonCallback) { if (confirmDialog == null || !confirmDialog!!.isShowing) { confirmDialog = MaterialDialog.Builder(this) .title(getString(R.string.confirm_action)) .content(content) .positiveText(getString(R.string.okay)) .negativeText(R.string.cancel) .onPositive(callback) .onNegative { dialog, _ -> dialog.dismiss() }.build() confirmDialog!!.show() } } private fun confirmDialog(content: String, positiveCallback: MaterialDialog.SingleButtonCallback, negativeCallback: MaterialDialog.SingleButtonCallback) { if (confirmDialog == null || !confirmDialog!!.isShowing) { confirmDialog = MaterialDialog.Builder(this) .title(getString(R.string.confirm_action)) .content(content) .positiveText(getString(R.string.okay)) .negativeText(R.string.cancel) .onPositive(positiveCallback) .onNegative(negativeCallback).build() confirmDialog!!.show() } } private fun showNotInLibraryDialog() { MaterialDialog.Builder(this) .iconRes(R.drawable.ic_warning_white_vector) .title(getString(R.string.alert)) .content(getString(R.string.novel_not_in_library_dialog_content)) .positiveText(getString(R.string.okay)) .onPositive { dialog, _ -> dialog.dismiss() } .show() } private fun manageDownloadsDialog() { MaterialDialog.Builder(this) .iconRes(R.drawable.ic_info_white_vector) .title(getString(R.string.manage_downloads)) .content("Novel downloads can be managed by navigating to \"Downloads\" through the navigation drawer menu.") .positiveText(getString(R.string.take_me_there)) .negativeText(getString(R.string.okay)) .onPositive { dialog, _ -> dialog.dismiss(); setResult(Constants.OPEN_DOWNLOADS_RES_CODE); finish() } .onNegative { dialog, _ -> dialog.dismiss() } .show() } //endregion //region OptionsMenu override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_activity_chapters, menu) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { menu?.getItem(1)?.isVisible = (novel.id == -1L) menu?.getItem(2)?.isVisible = (novel.id != -1L) && !removeDownloadMenuIcon return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when { item?.itemId == android.R.id.home -> finish() item?.itemId == R.id.action_download -> { confirmDialog(if (novel.id != -1L) getString(R.string.download_all_new_chapters_dialog_content) else getString(R.string.download_all_chapters_dialog_content), MaterialDialog.SingleButtonCallback { dialog, _ -> addNovelToLibrary() dbHelper.createDownloadQueue(novel.id) dbHelper.updateDownloadQueueStatus(Constants.STATUS_DOWNLOAD, novel.id) startNovelDownloadService(novelId = novel.id) setDownloadStatus() dialog.dismiss() }) } item?.itemId == R.id.action_sort -> { isSortedAsc = !isSortedAsc adapter.updateData(ArrayList(adapter.items.asReversed())) checkData() } item?.itemId == R.id.action_add_to_library -> { addNovelToLibrary() invalidateOptionsMenu() } } return super.onOptionsItemSelected(item) } private fun checkData() { counter++ if (counter >= 20) { dataCenter.lockRoyalRoad = false } } //endregion //region Update Download Status private fun setDownloadStatus() { statusCard.setOnClickListener { manageDownloadsDialog() } async { val dq = await { dbHelper.getDownloadQueue(novel.id) } ?: return@async removeDownloadMenuIcon = true invalidateOptionsMenu() val allWebPages = await { dbHelper.getAllWebPages(novel.id) } val readableWebPages = await { dbHelper.getAllReadableWebPages(novel.id) } var removeIcon = false when (dq.status) { Constants.STATUS_STOPPED -> { // statusCard.animation = null statusCard.visibility = View.VISIBLE statusText.text = getString(R.string.downloading_status, getString(R.string.downloading), getString(R.string.status), getString(R.string.download_paused)) removeIcon = true } Constants.STATUS_DOWNLOAD -> { // statusCard.startAnimation(AnimationUtils.loadAnimation(this@ChaptersNewActivity, R.anim.alpha_animation)) statusCard.visibility = View.VISIBLE if (DownloadNovelService.novelId == novel.id) if (allWebPages.size == novel.chapterCount.toInt()) statusText.text = getString(R.string.downloading_status, getString(R.string.downloading), getString(R.string.status), getString(R.string.chapter_count, readableWebPages.size, allWebPages.size)) else statusText.text = getString(R.string.downloading_status, getString(R.string.downloading), getString(R.string.status), getString(R.string.collection_chapters_info)) else statusText.text = getString(R.string.downloading_status, getString(R.string.downloading), getString(R.string.status), getString(R.string.download_paused)) removeIcon = true } Constants.STATUS_COMPLETE -> { // statusCard.animation = null statusCard.visibility = View.GONE removeIcon = novel.chapterCount.toInt() == readableWebPages.size } } if (statusText.text.contains("aused")) statusCard.setCardBackgroundColor(ContextCompat.getColor(this@ChaptersActivity, R.color.DarkRed)) else statusCard.setCardBackgroundColor(ContextCompat.getColor(this@ChaptersActivity, R.color.DarkGreen)) if (removeIcon != removeDownloadMenuIcon) { removeDownloadMenuIcon = removeIcon invalidateOptionsMenu() } } } private fun updateDownloadStatus(orderId: Long?) { statusCard.setCardBackgroundColor(ContextCompat.getColor(this@ChaptersActivity, R.color.DarkGreen)) if (orderId != null) statusText.text = getString(R.string.downloading_status, getString(R.string.downloading), getString(R.string.status), getString(R.string.chapter_count, dbHelper.getAllReadableWebPages(novel.id).size, novel.chapterCount)) } //endregion //region Event Bus override fun onResume() { super.onResume() EventBus.getDefault().register(this) } override fun onPause() { EventBus.getDefault().unregister(this) super.onPause() } @Subscribe(threadMode = ThreadMode.MAIN) fun onNovelEvent(event: NovelEvent) { val webPage = event.webPage if (webPage != null) { adapter.updateItem(webPage) } if ((event.type == EventType.UPDATE && event.webPage == null) || event.type == EventType.COMPLETE) setDownloadStatus() else if (event.type == EventType.UPDATE && event.webPage != null) { updateDownloadStatus(event.webPage?.orderId) } } //endregion override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == Constants.READER_ACT_REQ_CODE) { if (novel.id != -1L) { novel = dbHelper.getNovel(novel.id)!! getChaptersFromDB() } } } private fun addNovelToLibrary() { async { if (novel.id == -1L) { progressLayout.showLoading() novel.id = await { dbHelper.insertNovel(novel) } if (isSortedAsc) await { dbHelper.addWebPages(adapter.items, novel) } else await { dbHelper.addWebPages(adapter.items.asReversed(), novel) } getChaptersFromDB() } } } override fun onDestroy() { super.onDestroy() async.cancelAll() } }
0
Kotlin
0
0
ac0fb29eda349452ddd40efe181f576b0a78981d
24,696
NovelLibrary
Apache License 2.0
roboquant-server/src/main/kotlin/org/roboquant/server/page.kt
neurallayer
406,929,056
false
null
/* * Copyright 2020-2023 Neural Layer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.roboquant.server import kotlinx.html.* fun HTML.page(title: String, bodyFn: BODY.() -> Unit) { lang = "en" head { script { src = "https://cdnjs.cloudflare.com/ajax/libs/htmx/1.9.4/htmx.min.js" } script { src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"} script { src = "/static/htmx-extensions.js"} title { +title } link { href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel = "stylesheet" } link { href = "/static/custom.css" rel = "stylesheet" } } body(classes = "container") { h1 { +title } bodyFn() } }
14
Kotlin
30
228
af9c87ff5c64f67eda395af3ca85809a361cc731
1,328
roboquant
Apache License 2.0
react-kotlin/src/main/kotlin/react/dom/AriaPressed.kt
sgrishchenko
408,553,710
true
{"Kotlin": 592671}
// Automatically generated - do not modify! package react.dom @Suppress("NAME_CONTAINS_ILLEGAL_CHARS") // language=JavaScript @JsName("""({__false__: 'false', mixed: 'mixed', __true__: 'true'})""") external enum class AriaPressed { __false__, mixed, __true__, ; }
0
null
0
0
425d2dcc65a0682419ce9e41934b947f5d2658ce
283
react-types-kotlin
Apache License 2.0
src/main/kotlin/com/framstag/domainbus/sink/ExecutorSink.kt
Framstag
233,686,175
false
null
package com.framstag.domainbus.sink import com.framstag.domainbus.event.Event import com.framstag.domainbus.event.EventBatch import com.framstag.domainbus.event.EventResult import com.framstag.domainbus.source.Source import mu.KLogging import java.time.Duration import java.util.concurrent.CompletableFuture import java.util.concurrent.ExecutorService import java.util.concurrent.TimeUnit import java.util.function.Consumer class ExecutorSink(private val source: Source, private val executor: ExecutorService, private val timeout: Duration) : Sink, Runnable { companion object : KLogging() private fun wait(duration: Duration) { if (duration.isZero) { return } val timeoutInNanos = duration.toMillis() logger.info("Sleeping for $timeoutInNanos milliseconds...") TimeUnit.MILLISECONDS.sleep(timeoutInNanos) logger.info("Sleeping for $timeoutInNanos milliseconds done.") } private fun processEvent(event: Event): EventResult { logger.info("Processing event ${event.serialId}...") TimeUnit.MILLISECONDS.sleep(timeout.toMillis()) val result = EventResult(event.serialId, true) logger.info("Processing event ${event.serialId} done") return result } private fun process(eventProducer: CompletableFuture<Event>, eventResult: CompletableFuture<EventResult>) { eventProducer.thenAcceptAsync(Consumer<Event> { event -> eventResult.complete(processEvent(event)) }, executor) } private fun process(): Duration { val batchProducer = CompletableFuture<EventBatch>() batchProducer.thenAcceptAsync { batch -> logger.debug("Consuming events...") for (event in batch.events) { process(event.event, event.result) } logger.debug("Consuming events done.") } logger.debug("Requesting data...") source.requestData(batchProducer) logger.debug("Requesting data done.") val batch = batchProducer.get() return batch.timeout } override fun run() { while (!Thread.currentThread().isInterrupted) { val timeout = process() wait(timeout) } close() } override fun close() { // TODO: Close Source } }
0
Kotlin
0
0
9b3b358e9ee6b1e5bac8dd9d72cccefe9c4c09ab
2,353
domainbus
Apache License 2.0
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/plant_flower/PlantFlowerAcceptGiveFlowerReq.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.activity.plant_flower import org.anime_game_servers.core.base.Version.GI_2_2_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.ProtoCommand @AddedIn(GI_2_2_0) @ProtoCommand(REQUEST) internal interface PlantFlowerAcceptGiveFlowerReq { var scheduleId: Int var uid: Int }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
472
anime-game-multi-proto
MIT License
src/main/kotlin/org/goodmath/simplex/manifold/MExportOptions.kt
MarkChuCarroll
831,231,194
false
{"Kotlin": 331364, "JavaScript": 5734, "ANTLR": 3591, "Emacs Lisp": 1306, "Scheme": 465}
package org.goodmath.simplex.manifold import com.sun.jna.Memory import com.sun.jna.Pointer class MExportOptions(val options: ManifoldExportOptions): MType(options) { constructor(): this(mc.manifold_export_options(allocate())) fun setFaceted(faceted: Int) { mc.manifold_export_options_set_faceted(options, faceted) } fun setMaterial(material: MMaterial) { mc.manifold_export_options_set_material(options, material.material) } override fun close() { mc.manifold_destruct_export_options(options) super.close() } companion object { fun allocate(): Pointer { return Memory(mc.manifold_export_options_size()) } } }
0
Kotlin
0
0
e1e9c66630557074ac52698556c4289d60335eaf
711
simplex
Apache License 2.0
src/commonMain/kotlin/data/items/EnchantedAdamantiteLeggings.kt
marisa-ashkandi
332,658,265
false
null
package `data`.items import `data`.Constants import `data`.itemsets.ItemSets import `data`.model.Color import `data`.model.Item import `data`.model.ItemSet import `data`.model.Socket import `data`.model.SocketBonus import `data`.socketbonus.SocketBonuses import character.Buff import character.Stats import kotlin.Array import kotlin.Boolean import kotlin.Double import kotlin.Int import kotlin.String import kotlin.collections.List import kotlin.js.JsExport @JsExport public class EnchantedAdamantiteLeggings : Item() { public override var isAutoGenerated: Boolean = true public override var id: Int = 23512 public override var name: String = "Enchanted Adamantite Leggings" public override var itemLevel: Int = 115 public override var quality: Int = 3 public override var icon: String = "inv_pants_plate_12.jpg" public override var inventorySlot: Int = 7 public override var itemSet: ItemSet? = ItemSets.byId(563) public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.PLATE public override var allowableClasses: Array<Constants.AllowableClass>? = null public override var minDmg: Double = 0.0 public override var maxDmg: Double = 0.0 public override var speed: Double = 0.0 public override var stats: Stats = Stats( stamina = 27, armor = 1019 ) public override var sockets: Array<Socket> = arrayOf( Socket(Color.RED), Socket(Color.BLUE), Socket(Color.BLUE) ) public override var socketBonus: SocketBonus? = SocketBonuses.byId(113) public override var phase: Int = 1 public override val buffs: List<Buff> by lazy { listOf()} }
21
null
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
1,746
tbcsim
MIT License
crouter-api/src/main/java/me/wcy/router/FragmentFinder.kt
wangchenyan
207,708,657
false
{"Kotlin": 60564}
package me.wcy.router import androidx.fragment.app.Fragment import me.wcy.router.annotation.RouteMeta import kotlin.reflect.KClass /** * Created by wangchenyan.top on 2022/6/8. */ internal object FragmentFinder { fun findFragmentX(request: Request): KClass<out Fragment>? { val uri = request.uri() ?: return null CRouter.routes.find { route: RouteMeta -> RouterUtils.match(route, uri) && isFragmentX(route.target) }?.let { return it.target as KClass<out Fragment> } return null } fun findFragment(request: Request): KClass<out android.app.Fragment>? { val uri = request.uri() ?: return null CRouter.routes.find { route: RouteMeta -> RouterUtils.match(route, uri) && isFragment(route.target) }?.let { return it.target as KClass<out android.app.Fragment> } return null } fun isAnyFragment(target: KClass<*>): Boolean { return isFragment(target) || isFragmentX(target) } private fun isFragment(target: KClass<*>): Boolean { return android.app.Fragment::class.java.isAssignableFrom(target.java) } private fun isFragmentX(target: KClass<*>): Boolean { return Fragment::class.java.isAssignableFrom(target.java) } }
0
Kotlin
0
18
0a8884f733d89b3fdc0a793b50894a132da01fa8
1,309
crouter
Apache License 2.0
app/src/main/java/android/example/com/udacityfirstproject/ui/shoeList/ShoeListFragment.kt
MinaWadeeBibawey
577,851,084
false
null
package android.example.com.udacityfirstproject.ui.shoeList import android.example.com.udacityfirstproject.R import android.example.com.udacityfirstproject.databinding.ShoeListFragmentBinding import android.example.com.udacityfirstproject.models.ShowDetailsModel import android.example.com.udacityfirstproject.ui.shoeDetails.SharedViewModel import android.os.Build import android.os.Bundle import android.view.* import android.widget.TextView import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.MutableLiveData import androidx.navigation.fragment.findNavController class ShoeListFragment : Fragment() { lateinit var binding: ShoeListFragmentBinding private val viewModel: SharedViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = ShoeListFragmentBinding.inflate(layoutInflater) binding.sharedViewModel = viewModel viewModel.savedNewShowInTheList.observe(viewLifecycleOwner) { newItemIsAdded -> if (newItemIsAdded.isNotEmpty()) for (i in newItemIsAdded) { addNewItem(i) } } binding.addNewItemFloatingButton.setOnClickListener { findNavController().navigate(ShoeListFragmentDirections.actionShoeListFragmentToShoeDetailsFragment()) } setHasOptionsMenu(true) return binding.root } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.logout_menu, menu) } private fun logOutAction() { findNavController().navigate(ShoeListFragmentDirections.actionShoeListFragmentToLoginFragment()) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.logout -> logOutAction() } return super.onOptionsItemSelected(item) } private fun addNewItem(model: ShowDetailsModel) { val shoeName = TextView(requireContext()) val company = TextView(requireContext()) val shoeSize = TextView(requireContext()) val description = TextView(requireContext()) val space = TextView(requireContext()) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { shoeName.setTextColor(requireContext().getColor(R.color.black)) company.setTextColor(requireContext().getColor(R.color.black)) shoeSize.setTextColor(requireContext().getColor(R.color.black)) description.setTextColor(requireContext().getColor(R.color.black)) } binding.shoeListLayout.addView(shoeName) binding.shoeListLayout.addView(company) binding.shoeListLayout.addView(shoeSize) binding.shoeListLayout.addView(description) binding.shoeListLayout.addView(space) shoeName.text = requireContext().getString(R.string.shoeName_format, model.ShoeName) company.text = requireContext().getString(R.string.company_format, model.Company) shoeSize.text = requireContext().getString(R.string.shoe_size_format, model.ShoeSize.toString()) description.text = requireContext().getString(R.string.description_format, model.Description) } }
0
Kotlin
0
0
7750d4cacf8aa04b655dd1f91827ee255c35713b
3,443
UdacityFirstProject
MIT License
app/src/main/java/com/vicky7230/flux/ui/search/SearchMvpView.kt
sam43
143,965,801
true
{"Kotlin": 211153}
package com.vicky7230.flux.ui.search import com.vicky7230.flux.data.network.model.results.Result import com.vicky7230.flux.ui.base.MvpView interface SearchMvpView : MvpView { fun updateSearchList(results: MutableList<Result>) }
0
Kotlin
0
0
373af1fee22a6b0973f7965f22ab2cf7055f96f6
235
Flux
Apache License 2.0
0496.Next Greater Element I.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
import java.util.* internal class Solution { fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray { val stk: Deque<Int> = ArrayDeque() val m: Map<Int, Int> = HashMap() for (v in nums2) { while (!stk.isEmpty() && stk.peek() < v) { m.put(stk.pop(), v) } stk.push(v) } val n = nums1.size val ans = IntArray(n) for (i in 0 until n) { ans[i] = m.getOrDefault(nums1[i], -1) } return ans } }
0
Kotlin
0
0
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
472
kotlin-leetcode
MIT License
src/test/kotlin/de/igorakkerman/challenge/longestnonrepeatingsubstring/LongestNonRepeatingSubstringTest.kt
igorakkerman
190,288,487
false
null
package de.igorakkerman.challenge.longestnonrepeatingsubstring import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek object LongestNonRepeatingSubstringTest : Spek({ group("length") { test("empty -> 0") { assertThat(LongestNonRepeatingSubstring("").length()) .isEqualTo(0) } test("1 char -> 1") { assertThat(LongestNonRepeatingSubstring("a").length()) .isEqualTo(1) } test("2 different -> 2") { assertThat(LongestNonRepeatingSubstring("ab").length()) .isEqualTo(2) } test("2 equal -> 1") { assertThat(LongestNonRepeatingSubstring("aa").length()) .isEqualTo(1) } test("3 different -> 3") { assertThat(LongestNonRepeatingSubstring("abc").length()) .isEqualTo(3) } test("2 equal, 1 different -> 2") { assertThat(LongestNonRepeatingSubstring("aab").length()) .isEqualTo(2) } test("1 different, 2 equal -> 2") { assertThat(LongestNonRepeatingSubstring("abb").length()) .isEqualTo(2) } test("2 different twice -> 2") { assertThat(LongestNonRepeatingSubstring("abab").length()) .isEqualTo(2) } test("abcbde -> cbde -> 4") { assertThat(LongestNonRepeatingSubstring("abcbde").length()) .isEqualTo(4) } test("abba -> ab -> 2") { assertThat(LongestNonRepeatingSubstring("abba").length()) .isEqualTo(2) } test("abbac -> bac -> 3") { assertThat(LongestNonRepeatingSubstring("abbac").length()) .isEqualTo(3) } test("dabbace -> bace -> 4") { assertThat(LongestNonRepeatingSubstring("dabbace").length()) .isEqualTo(4) } } group("sub") { test("'' -> ''") { assertThat(LongestNonRepeatingSubstring("").value()) .isEqualTo("") } test("a -> a") { assertThat(LongestNonRepeatingSubstring("a").value()) .isEqualTo("a") } test("ab -> ab") { assertThat(LongestNonRepeatingSubstring("ab").value()) .isEqualTo("ab") } test("aa -> a") { assertThat(LongestNonRepeatingSubstring("aa").value()) .isEqualTo("a") } test("aaa -> a") { assertThat(LongestNonRepeatingSubstring("aaa").value()) .isEqualTo("a") } test("abc -> abc") { assertThat(LongestNonRepeatingSubstring("abc").value()) .isEqualTo("abc") } test("aab -> ab") { assertThat(LongestNonRepeatingSubstring("aab").value()) .isEqualTo("ab") } test("abb -> ab") { assertThat(LongestNonRepeatingSubstring("abb").value()) .isEqualTo("ab") } test("abab -> ab") { assertThat(LongestNonRepeatingSubstring("abab").value()) .isEqualTo("ab") } test("abcbde -> cbde") { assertThat(LongestNonRepeatingSubstring("abcbde").value()) .isEqualTo("cbde") } test("abba -> ab") { assertThat(LongestNonRepeatingSubstring("abba").value()) .isEqualTo("ab") } test("abbac -> bac") { assertThat(LongestNonRepeatingSubstring("abbac").value()) .isEqualTo("bac") } test("dabbace -> bace") { assertThat(LongestNonRepeatingSubstring("dabbace").value()) .isEqualTo("bace") } } })
0
Kotlin
0
0
292be06b09841d9c6bbf39745acf92bc8ace2110
3,956
longestnonrepeatingsubstring-challenge
MIT License
buildSrc/src/main/kotlin/AndroidSdk.kt
DDsix
629,079,116
false
null
object AndroidSdk { const val min = 24 const val compile = 33 const val target = 33 }
0
Kotlin
0
0
68eaea7559c994e0b175cb06ad9cbe6bc007579c
97
PetFinder
MIT License
src/main/kotlin/com/trader/defichain/indexer/ZMQEventQueue.kt
victorv
606,947,847
false
null
package com.trader.defichain.indexer import com.trader.defichain.db.DBTX import com.trader.defichain.db.insertPoolPairs import com.trader.defichain.db.insertTX import com.trader.defichain.dex.PoolSwap import com.trader.defichain.dex.getTokenSymbol import com.trader.defichain.dex.testPoolSwap import com.trader.defichain.rpc.Block import com.trader.defichain.rpc.RPC import com.trader.defichain.rpc.RPCMethod import com.trader.defichain.zmq.ZMQEvent import com.trader.defichain.zmq.ZMQEventType import com.trader.defichain.zmq.newZMQEventChannel import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.serialization.json.JsonPrimitive import org.slf4j.LoggerFactory import java.time.Instant import kotlin.coroutines.CoroutineContext private val eventChannel = newZMQEventChannel() private val logger = LoggerFactory.getLogger("ZMQEventQueue") private val rawTransactions = mutableMapOf<String, ZMQRawTX>() private var block: Block? = null suspend fun processZMQEvents(coroutineContext: CoroutineContext) { while (coroutineContext.isActive) { val event = eventChannel.receive() try { processEvent(event) } catch (e: Throwable) { logger.error("Failed to process $event; skipping event and suspending processing for ${BLOCK_TIME}ms", e) delay(BLOCK_TIME) } } } private suspend fun processEvent(event: ZMQEvent) { if (event.type == ZMQEventType.HASH_BLOCK) { try { val blockHash = JsonPrimitive(event.payload) val newBlock = RPC.getValue<Block>(RPCMethod.GET_BLOCK, blockHash, JsonPrimitive(2)) block = newBlock val poolPairs = event.poolPairs val oraclePrices = event.oraclePrices if (poolPairs != null && oraclePrices != null) { val dbtx = DBTX("Tokens, pool pairs and oracle prices at block height ${newBlock.height}") val masterNodeTX = RPC.getMasterNodeTX(newBlock.masterNode) val masterNode = dbtx.insertTX( masterNodeTX.tx.txID, masterNodeTX.type, masterNodeTX.fee, masterNodeTX.tx.vsize, isConfirmed = true, valid = true ) val usdtPrices = oraclePrices.map { val tokenSymbol = getTokenSymbol(it.key) if (tokenSymbol == "USDT" || tokenSymbol == "USDC") { return@map it.key to 1.0 } it.key to testPoolSwap( PoolSwap( amountFrom = 1.0, tokenFrom = tokenSymbol, tokenTo = "USDT", desiredResult = 1.0, ) ).estimate }.toMap() dbtx.insertPoolPairs(newBlock, masterNode, poolPairs, usdtPrices) dbtx.submit() } announceZMQBlock(block!!, rawTransactions.values.toList()) } finally { rawTransactions.clear() } } if (event.type == ZMQEventType.RAW_TX) { val currentBlock = block ?: return val hex = event.payload if (rawTransactions.containsKey(hex)) return val tx = ZMQRawTX( time = Instant.now().toEpochMilli(), blockHeight = currentBlock.height, txn = rawTransactions.size, hex = hex, ) rawTransactions[hex] = tx if (rawTransactions.size % 100 == 0) { logger.info("${rawTransactions.size} raw transactions in queue") } } } data class ZMQRawTX( val time: Long, val blockHeight: Int, val hex: String, val txn: Int, )
0
Kotlin
0
0
c64cb9aa7bb4c6298a5ab8ea674a6257e25660f9
3,766
defichain-trader-api
MIT License
ecommerce-cart/src/main/kotlin/com/kotato/context/ecommerce/modules/payment/infrastructure/AxonPaymentRepository.kt
kotato
110,930,032
false
null
package com.kotato.context.ecommerce.modules.payment.infrastructure import com.kotato.context.ecommerce.modules.payment.domain.Payment import com.kotato.context.ecommerce.modules.payment.domain.PaymentId import com.kotato.context.ecommerce.modules.payment.domain.PaymentRepository import com.kotato.shared.money.Money import org.axonframework.commandhandling.model.AggregateNotFoundException import org.springframework.stereotype.Repository import org.axonframework.commandhandling.model.Repository as AggregateRepository @Repository open class AxonPaymentRepository(private val persistenceRepository: AggregateRepository<Payment>) : PaymentRepository { override fun search(paymentId: PaymentId) = try { persistenceRepository.load(paymentId.asString()).invoke { it } } catch (exception: AggregateNotFoundException) { null } override fun new(orderId: PaymentId, amount: Money) { persistenceRepository.newInstance { Payment.create(orderId, amount) Payment() } } }
2
Kotlin
26
25
15db3d036f273de1bf4bb603398a0d24bc3c6ade
1,086
axon-examples
MIT License
src/commonMain/kotlin/data/socketbonus/SocB2865.kt
marisa-ashkandi
332,658,265
false
null
package data.socketbonus import data.Constants data class SocB2865 ( override var id: Int = 2865, override var stat: Constants.StatType = Constants.StatType.MANA_PER_5_SECONDS, override var amount: Int = 2 ) : SocketBonusRaw()
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
235
tbcsim
MIT License
app/src/main/java/com/example/primeiroapp/MainActivity.kt
mgabrielassa
744,258,577
false
{"Kotlin": 4880}
package com.example.primeiroapp import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatDelegate import com.example.primeiroapp.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btDarkMode.setOnCheckedChangeListener { compoundButton, isCheked -> if (isCheked){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) }else{ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } } val btnCalcular: Button = findViewById(R.id.btnCalcular) val edtPeso: EditText = findViewById(R.id.edtPeso) val edtAltura: EditText = findViewById(R.id.edttext_altura) btnCalcular.setOnClickListener { val alturaStr = edtAltura.text.toString() val pesoStr = edtPeso.text.toString() if (alturaStr.isNotEmpty() && pesoStr.isNotEmpty()) { val altura: Float = alturaStr.toFloat() val peso: Float = pesoStr.toFloat() val alturaFinal: Float = altura * altura val result: Float = peso / alturaFinal val intent = Intent(this, ResultActivity::class.java) .apply { putExtra("EXTRA_RESULT", result) } startActivity(intent) } else{ Toast.makeText(this, "Preencher todos os campos", Toast.LENGTH_LONG).show() } } } }
0
Kotlin
0
0
3d3594bdb1ae544280d5a5c613ec144670d20fd7
1,983
CalculadoraIMC
MIT License
src/utils/AppStoreApiRequester.kt
bucketplace
216,353,542
false
null
package utils import io.jsonwebtoken.Jwts import okhttp3.Headers import secrets.AppStoreSecrets import java.security.KeyFactory import java.security.PrivateKey import java.security.spec.PKCS8EncodedKeySpec import java.util.* import java.util.concurrent.TimeUnit.MINUTES import javax.xml.bind.DatatypeConverter object AppStoreApiRequester { suspend inline fun <reified T> get(url: String): T { return ApiRequester.request("GET", url, createHeaders()) } fun createHeaders(): Headers { return Headers.of(mapOf("Authorization" to "Bearer ${getJwtToken()}")) } private fun getJwtToken(): String { return Jwts.builder() .setHeaderParam("alg", "ES256") .setHeaderParam("kid", AppStoreSecrets.JWT_PRIVATE_KEY_ID) .setHeaderParam("typ", "JWT") .setIssuer(AppStoreSecrets.JWT_ISSUER) .setAudience("appstoreconnect-v1") .setExpiration(Date(System.currentTimeMillis() + MINUTES.toMillis(1))) .signWith(loadPrivateKey()) .compact() } private fun loadPrivateKey(): PrivateKey { // val f = File(PRIVATE_KEY_FILE_PATH) // println(f.canonicalFile) // println(f.absolutePath) // val fis = FileInputStream(f) // val dis = DataInputStream(fis) // val keyBytes = ByteArray(f.length().toInt()) // dis.readFully(keyBytes) // dis.close() // val temp = String(keyBytes) val temp = AppStoreSecrets.JWT_PRIVATE_KEY var privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----", "") privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "") //System.out.println("Private key\n"+privKeyPEM); val spec = PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(privKeyPEM)) val kf = KeyFactory.getInstance("EC") return kf.generatePrivate(spec) } }
0
Kotlin
0
0
58e2270ed92bf19fe196613b67172aaf12442368
1,900
error-report-v2
Apache License 2.0
app/src/main/java/com/elementary/tasks/sms/UiSmsListDiffCallback.kt
naz013
165,067,747
false
null
package com.elementary.tasks.sms import androidx.recyclerview.widget.DiffUtil import com.elementary.tasks.core.data.ui.sms.UiSmsList class UiSmsListDiffCallback : DiffUtil.ItemCallback<UiSmsList>() { override fun areContentsTheSame(oldItem: UiSmsList, newItem: UiSmsList) = oldItem == newItem override fun areItemsTheSame(oldItem: UiSmsList, newItem: UiSmsList) = oldItem.id == newItem.id }
0
Kotlin
2
0
a4c2a2bca3afd76e33b3e45bfdde8dbe8e052568
406
reminder-kotlin
Apache License 2.0
FlexChatBoxSDK/src/main/java/in/tilicho/flexchatbox/enums/FlexType.kt
tilicholabs
605,501,253
false
null
package `in`.tilicho.flexchatbox.enums enum class FlexType { GALLERY, VOICE, LOCATION, CONTACTS, FILES, CAMERA }
0
Kotlin
0
2
44f60790bc282b0629345b97af41c3a436527085
138
FlexChatBox-Android
MIT License
z2-core/src/commonMain/kotlin/hu/simplexion/z2/adaptive/AdaptiveLoop.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1580555, "CSS": 166054, "Java": 12046, "HTML": 1560, "JavaScript": 975}
/* * Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.z2.adaptive class AdaptiveLoop<BT, IT>( override val adaptiveAdapter: AdaptiveAdapter<BT>, override val adaptiveClosure: AdaptiveClosure<BT>?, override val adaptiveParent: AdaptiveFragment<BT>, val makeIterator: () -> Iterator<IT>, val makeFragment: (parent : AdaptiveFragment<BT>) -> AdaptiveFragment<BT> ) : AdaptiveFragment<BT> { override val adaptiveExternalPatch: AdaptiveExternalPatchType<BT> = { } var loopVariable: IT? = null val fragments = mutableListOf<AdaptiveFragment<BT>>() lateinit var placeholder: AdaptiveBridge<BT> override fun adaptiveCreate() { for (loopVariable in makeIterator()) { this.loopVariable = loopVariable fragments.add(makeFragment(this)) } } override fun adaptiveMount(bridge: AdaptiveBridge<BT>) { placeholder = adaptiveAdapter.createPlaceholder() bridge.add(placeholder) for (fragment in fragments) { fragment.adaptiveMount(placeholder) } } override fun adaptivePatch() { var index = 0 for (loopVariable in makeIterator()) { this.loopVariable = loopVariable if (index >= fragments.size) { val f = makeFragment(this) fragments.add(f) f.adaptiveCreate() f.adaptiveMount(placeholder) } else { fragments[index].also { it.adaptiveExternalPatch(it) it.adaptivePatch() } } index ++ } while (index < fragments.size) { val f = fragments.removeLast() f.adaptiveUnmount(placeholder) f.adaptiveDispose() index ++ } } override fun adaptiveUnmount(bridge: AdaptiveBridge<BT>) { for (fragment in fragments) { fragment.adaptiveUnmount(placeholder) } bridge.remove(placeholder) } override fun adaptiveDispose() { for (f in fragments) { f.adaptiveDispose() } } }
5
Kotlin
0
1
fbc4e96cf4713d2b67b419c2a2697efcbc36d034
2,254
z2
Apache License 2.0
app/src/main/java/mse/mobop/mymoviesbucketlists/firestore/BucketlistFirestore.kt
RaedAbr
221,748,823
false
{"Kotlin": 130757}
package mse.mobop.mymoviesbucketlists.firestore import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.firebase.Timestamp import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.* import mse.mobop.mymoviesbucketlists.utils.BUCKETLIST_COLLECTION import mse.mobop.mymoviesbucketlists.model.Bucketlist import mse.mobop.mymoviesbucketlists.model.Movie import java.util.* import kotlin.collections.ArrayList object BucketlistFirestore { private val firestoreInstance: FirebaseFirestore by lazy { FirebaseFirestore.getInstance() } private val bucketlistsCollRef: CollectionReference get() = firestoreInstance.collection(BUCKETLIST_COLLECTION) private val snapshotListenersMap = mutableMapOf<String, ListenerRegistration>() fun createBucketlist(bucketlist: Bucketlist) { bucketlistsCollRef.add(bucketlist) .addOnSuccessListener { Log.e("bucketlist", "DocumentSnapshot written with ID: ${it.id}") } .addOnFailureListener { e -> Log.e("bucketlist", "Error adding document", e) } } fun getOwnedBucketlistsQuery(): Query { return bucketlistsCollRef .whereEqualTo("createdBy.id", FirebaseAuth.getInstance().currentUser!!.uid) .orderBy("creationTimestamp", Query.Direction.DESCENDING) } fun getSharedBucketlistsQuery(): Query { return bucketlistsCollRef .whereArrayContains("sharedWithIds", FirebaseAuth.getInstance().currentUser!!.uid) .orderBy("creationTimestamp", Query.Direction.DESCENDING) } fun getById(id: String?): LiveData<Bucketlist> { val bucketlist = MutableLiveData<Bucketlist>() if (id != null) { val registration = bucketlistsCollRef.document(id) .addSnapshotListener { snapshot, e -> if (e != null) { Log.e("getById", "Listen failed.", e) return@addSnapshotListener } if (snapshot != null && snapshot.exists()) { Log.e("getById", "Current data: ${snapshot.data}") bucketlist.value = snapshot.toObject(Bucketlist::class.java) } else { // data has been deleted by another user Log.e("getById", "Current data: null") bucketlist.value = null } } snapshotListenersMap.putIfAbsent(id, registration) } return bucketlist } fun updateBucketlist(bucketlist: Bucketlist) { bucketlistsCollRef.document(bucketlist.id!!) .set(bucketlist) .addOnSuccessListener { Log.e("bucketlist", bucketlist.id + " Updated successfully") } .addOnFailureListener { Log.e("bucketlist", bucketlist.id + " Error writing document") } } fun updateMoviesList(bucketlistId: String, movies: ArrayList<Movie>) { val array = arrayOfNulls<Movie>(movies.size) movies.toArray(array) bucketlistsCollRef.document(bucketlistId) .update("movies", FieldValue.arrayUnion(*array)) .addOnSuccessListener { Log.e("updateMoviesList", "Movies successfully added!") } .addOnFailureListener { e -> Log.e("updateMoviesList", "Error adding movies", e) } } fun deleteBucketlist(bucketlistId: String) { bucketlistsCollRef.document(bucketlistId).delete() } fun toggleIsMovieWatched(bucketlistId: String, movie: Movie) { bucketlistsCollRef.document(bucketlistId) .update("movies", FieldValue.arrayRemove(movie)) movie.apply { isWatched = !isWatched watchedTimestamp = if (isWatched) Timestamp(Date().time / 1000, 0) else null } bucketlistsCollRef.document(bucketlistId) .update("movies", FieldValue.arrayUnion(movie)) } fun deleteBucketlistMovie(bucketlistId: String, movie: Movie) { bucketlistsCollRef.document(bucketlistId) .update("movies", FieldValue.arrayRemove(movie)) } fun stopListener(bucketlistId: String) { snapshotListenersMap.getValue(bucketlistId).remove() } }
0
Kotlin
0
0
b3bfcfef5163d2b94f465893737ae8fd7b701de4
4,377
my-movies-bucket-lists
MIT License
api/src/main/java/danbroid/kipfs/KIPFS.kt
danbrough
409,364,798
false
null
package danbroid.kipfs import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext /** * Client api for accessing an ipfs node */ abstract class KIPFS : AbstractCoroutineContextElement(KIPFSContextKey) { companion object { object KIPFSContextKey : CoroutineContext.Key<KIPFS> } open val defaultDagCodec = "dag-cbor" /** * Default cid version for [KIPFS.add] */ open val defaultCidVersion: String = "1" @Suppress("UNCHECKED_CAST") suspend inline fun <reified T> request( command: String, argument: String? = null, requiresNodeStarted: Boolean = false, vararg options: Pair<String, Any?> ): T = requestRaw(command, argument, requiresNodeStarted, *options).decodeToString().decodeJson() abstract suspend fun requestRaw( command: String, argument: String? = null, requiresNodeStarted: Boolean = false, vararg options: Pair<String, Any?>, ): ByteArray suspend fun <T> send( command: String, arg: String?, data: String, requiresNodeStarted: Boolean = false, vararg options: Pair<String, Any?>, ): String = send(command, arg, data.toPart(), requiresNodeStarted, *options).decodeToString() abstract suspend fun send( command: String, arg: String? = null, part: Part, requiresNodeStarted: Boolean = false, vararg options: Pair<String, Any?>, ): ByteArray }
0
Kotlin
0
1
aee8defe623c4147c5da2beb64552a23a7492673
1,417
kipfs
Apache License 2.0
app/src/main/java/com/sample/android/tmdb/ui/feed/FeedCollectionList.kt
Ali-Rezaei
158,464,119
false
null
package com.sample.android.tmdb.ui.feed import android.content.Intent import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.rememberImagePainter import com.sample.android.tmdb.R import com.sample.android.tmdb.domain.FeedWrapper import com.sample.android.tmdb.domain.Movie import com.sample.android.tmdb.domain.TmdbItem import com.sample.android.tmdb.ui.common.TmdbTheme import com.sample.android.tmdb.ui.paging.main.SortType import com.sample.android.tmdb.ui.paging.main.movie.HighRateMoviesActivity import com.sample.android.tmdb.ui.paging.main.movie.PopularMoviesActivity import com.sample.android.tmdb.ui.paging.main.movie.TrendingMoviesActivity import com.sample.android.tmdb.ui.paging.main.movie.UpcomingMoviesActivity import com.sample.android.tmdb.ui.paging.main.tvshow.HighRateTVShowActivity import com.sample.android.tmdb.ui.paging.main.tvshow.LatestTVShowActivity import com.sample.android.tmdb.ui.paging.main.tvshow.PopularTVShowActivity import com.sample.android.tmdb.ui.paging.main.tvshow.TrendingTVShowActivity @Composable fun <T : TmdbItem> FeedCollectionList( navType: NavType, collection: List<FeedWrapper<T>>, onFeedClick: (TmdbItem) -> Unit ) { LazyColumn { items(collection) { feedCollection -> FeedCollection( feedCollection = feedCollection, navType = navType, onFeedClick = onFeedClick ) } } } @Composable private fun <T : TmdbItem> FeedCollection( feedCollection: FeedWrapper<T>, navType: NavType, onFeedClick: (TmdbItem) -> Unit, modifier: Modifier = Modifier, ) { val context = LocalContext.current Column(modifier = modifier) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .heightIn(min = 36.dp) .padding(start = 12.dp) ) { Text( text = stringResource(id = feedCollection.sortTypeResourceId), maxLines = 1, color = MaterialTheme.colors.onSurface, modifier = Modifier .weight(1f) .wrapContentWidth(Alignment.Start) ) Text( text = stringResource(R.string.more_item), color = MaterialTheme.colors.onSurface, modifier = Modifier .align(Alignment.CenterVertically) .clickable { val activity = when (navType) { NavType.MOVIES -> { when (feedCollection.sortType) { SortType.TRENDING -> { TrendingMoviesActivity::class.java } SortType.MOST_POPULAR -> { PopularMoviesActivity::class.java } SortType.UPCOMING -> { UpcomingMoviesActivity::class.java } SortType.HIGHEST_RATED -> { HighRateMoviesActivity::class.java } } } NavType.TV_SERIES -> { when (feedCollection.sortType) { SortType.TRENDING -> { TrendingTVShowActivity::class.java } SortType.MOST_POPULAR -> { PopularTVShowActivity::class.java } SortType.UPCOMING -> { LatestTVShowActivity::class.java } SortType.HIGHEST_RATED -> { HighRateTVShowActivity::class.java } } } } val intent = Intent(context, activity) context.startActivity(intent) } .padding(start = 12.dp, end = 12.dp, top = 12.dp, bottom = 10.dp) ) } Feeds(feedCollection.feeds, onFeedClick) } } @Composable private fun <T : TmdbItem> Feeds( feeds: List<T>, onFeedClick: (TmdbItem) -> Unit, modifier: Modifier = Modifier ) { LazyRow( modifier = modifier, contentPadding = PaddingValues(start = 2.dp, end = 2.dp) ) { items(feeds) { feed -> TmdbItem(feed, onFeedClick) } } } @Composable private fun <T : TmdbItem> TmdbItem( tmdbItem: T, onFeedClick: (TmdbItem) -> Unit ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .clickable(onClick = { onFeedClick(tmdbItem) }) .padding(6.dp) ) { Image( painter = rememberImagePainter(tmdbItem.posterPath?.let { url -> stringResource(R.string.base_poster_path, url) }), contentDescription = null, modifier = Modifier .size(width = 120.dp, height = 180.dp) .border(.3.dp, Color.White, RectangleShape), contentScale = ContentScale.Crop, ) Text( text = tmdbItem.name, fontSize = TmdbTheme.fontSizes.sp_11, color = MaterialTheme.colors.onSurface, textAlign = TextAlign.Center, overflow = TextOverflow.Ellipsis, modifier = Modifier .size(width = 120.dp, height = 56.dp) .padding(top = 6.dp) ) } } @Preview("default") @Composable fun FeedCardPreview() { TmdbTheme { val movie = Movie(1, "", null, null, null, "Movie", 1.0) TmdbItem( tmdbItem = movie, onFeedClick = {}, ) } }
0
Kotlin
8
70
ea80dd0481f141e55e0d06073d50676758073d34
7,177
TMDb-Paging
The Unlicense
desktop/src/jvmMain/kotlin/me/paranid5/desktop/ui/app_bar_items/Account.kt
dinaraparanid
436,651,144
false
null
package me.paranid5.desktop.me.paranid5.desktop.ui.app_bar_items import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.AbsoluteRoundedCornerShape import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import me.paranid5.common.User import me.paranid5.desktop.me.paranid5.desktop.ui.main_window.RootScreen import me.paranid5.resources.Colors import me.paranid5.resources.Strings @Composable fun ColumnScope.Account(rootScreen: RootScreen, user: User) { Box( Modifier .wrapContentWidth() .weight(weight = 1F, fill = true) .align(Alignment.CenterHorizontally) ) { Button( onClick = { rootScreen.changeConfigToAccount(user) }, modifier = Modifier.align(Alignment.Center), elevation = null, shape = AbsoluteRoundedCornerShape(15.dp) ) { Column { Box( Modifier .align(Alignment.CenterHorizontally) .padding(5.dp) ) { Image( painter = painterResource("images/human.png"), // TODO: User's avatar contentDescription = Strings.account, colorFilter = ColorFilter.tint(Colors.backgroundColor), modifier = Modifier .align(Alignment.TopCenter) .height(50.dp) .clip(CircleShape) .border( width = 2.dp, color = Colors.backgroundColor, shape = CircleShape ), ) } Box( Modifier .align(Alignment.CenterHorizontally) .padding(5.dp) ) { Text( text = Strings.account, fontSize = 14.sp, color = Colors.textColor, ) } } } } }
0
Kotlin
0
1
1f3c0b694bd02a93ac4cf02e48a70bc4709eec01
2,681
Forum_Client
Apache License 2.0
src/main/kotlin/com/github/toncherami/mpd/web/database/data/DatabaseAudioFormat.kt
TonCherAmi
295,049,940
false
null
package com.github.toncherami.mpd.web.database.data data class DatabaseAudioFormat(val bitDepth: Int, val samplingRate: Int, val numberOfChannels: Int) { companion object { fun of(formatString: String): DatabaseAudioFormat { val parts = formatString.split(':') if (parts.size != 3) { throw IllegalArgumentException("Unable to parse format string '$formatString'") } return DatabaseAudioFormat( bitDepth = parts[1].toIntOrNull() ?: -1, samplingRate = parts[0].toIntOrNull() ?: -1, numberOfChannels = parts[2].toIntOrNull() ?: -1, ) } } }
0
Kotlin
0
0
5610baae1d72cbbe4cda118b2fb796f093ff7551
690
mpdweb.backend
MIT License
app/src/main/java/com/awscherb/cardkeeper/di/module/SchedulerModule.kt
ksc91u
172,096,093
false
null
package com.awscherb.cardkeeper.di.module import dagger.Module import dagger.Provides import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers @Module class SchedulerModule { @Provides fun provideUiScheduler(): Scheduler = AndroidSchedulers.mainThread() }
1
Kotlin
0
2
e8c73973d52d5380d2928b2b18c744a45c1a38b3
295
CardKeeper
Apache License 2.0
domain/src/main/kotlin/com/jvmhater/moduticket/model/vo/Amount.kt
jvm-hater
587,725,795
false
null
package com.jvmhater.moduticket.model.vo @JvmInline value class Amount(val value: Long) { // example method operator fun plus(b: Amount) = Amount(value + b.value) operator fun minus(b: Amount) = Amount(value - b.value) operator fun compareTo(b: Amount): Int = (value - b.value).toInt() }
4
Kotlin
0
0
33dcc1ee90d8e3effeb4b6bcbec4a0c542ab8369
307
modu-ticket-backend
MIT License
sw-ui/src/jsMain/kotlin/org/luxons/sevenwonders/ui/router/Router.kt
joffrey-bion
75,569,445
false
{"Kotlin": 498747, "CSS": 8156, "HTML": 670, "Dockerfile": 464, "JavaScript": 254}
package org.luxons.sevenwonders.ui.router import kotlinx.browser.window import kotlinx.coroutines.Job import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import org.luxons.sevenwonders.ui.redux.sagas.SwSagaContext import redux.RAction enum class SwRoute(val path: String) { HOME("/"), GAME_BROWSER("/games"), LOBBY("/lobby"), GAME("/game"); companion object { private val all = values().associateBy { it.path } fun from(path: String) = all.getValue(path) } } data class Navigate(val route: SwRoute) : RAction suspend fun SwSagaContext.routerSaga( startRoute: SwRoute, runRouteSaga: suspend SwSagaContext.(SwRoute) -> Unit, ) { coroutineScope { window.location.hash = startRoute.path launch { changeRouteOnNavigateAction() } var currentSaga: Job = launch { runRouteSaga(startRoute) } window.onhashchange = { event -> val route = SwRoute.from(event.newURL.substringAfter("#")) currentSaga.cancel() currentSaga = [email protected] { runRouteSaga(route) } Unit } } } suspend fun SwSagaContext.changeRouteOnNavigateAction() { onEach<Navigate> { window.location.hash = it.route.path } }
32
Kotlin
8
55
0235fe9451b970ec89183161c174d33852e1dd12
1,307
seven-wonders
MIT License
designsystem/src/main/java/com/babylon/wallet/android/designsystem/composable/RadixPrimaryButton.kt
radixdlt
513,047,280
false
{"Kotlin": 4905038, "HTML": 215350, "Ruby": 2757, "Shell": 1963}
package com.babylon.wallet.android.designsystem.composable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.size import androidx.compose.material.CircularProgressIndicator import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.babylon.wallet.android.designsystem.R import com.babylon.wallet.android.designsystem.darken import com.babylon.wallet.android.designsystem.theme.RadixTheme import com.babylon.wallet.android.designsystem.theme.RadixWalletTheme import com.babylon.wallet.android.designsystem.utils.ClickListenerUtils @Composable fun RadixPrimaryButton( text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, icon: @Composable (() -> Unit)? = null, isLoading: Boolean = false, throttleClicks: Boolean = true ) { val interactionSource = remember { MutableInteractionSource() } val isPressed by interactionSource.collectIsPressedAsState() val lastClickMs = remember { mutableStateOf(0L) } Button( modifier = modifier.heightIn(min = RadixTheme.dimensions.buttonDefaultHeight), onClick = { ClickListenerUtils.throttleOnClick( lastClickMs = lastClickMs, onClick = onClick, enabled = throttleClicks ) }, shape = RadixTheme.shapes.roundedRectSmall, enabled = enabled, colors = ButtonDefaults.buttonColors( contentColor = Color.White, containerColor = if (isPressed) RadixTheme.colors.blue2.darken(0.1f) else RadixTheme.colors.blue2, disabledContainerColor = RadixTheme.colors.gray4, disabledContentColor = RadixTheme.colors.gray3 ), interactionSource = interactionSource ) { Row( horizontalArrangement = Arrangement.spacedBy(RadixTheme.dimensions.paddingSmall), verticalAlignment = Alignment.CenterVertically ) { if (isLoading) { CircularProgressIndicator( modifier = Modifier.size(20.dp), color = RadixTheme.colors.white, strokeWidth = 2.dp ) } else { icon?.invoke() Text(text = text, style = RadixTheme.typography.body1Header) } } } } @Preview @Composable fun RadixPrimaryButtonPreview() { RadixWalletTheme { RadixPrimaryButton(text = "Primary button", onClick = {}, modifier = Modifier.size(200.dp, 50.dp)) } } @Preview @Composable fun RadixPrimaryButtonWithIconPreview() { RadixWalletTheme { RadixPrimaryButton(text = "Primary button", onClick = {}, modifier = Modifier.size(200.dp, 50.dp), icon = { Icon(painter = painterResource(id = R.drawable.ic_search), contentDescription = "") }) } } @Preview @Composable fun RadixPrimaryButtonDisabledPreview() { RadixWalletTheme { RadixPrimaryButton( text = "Primary button", onClick = {}, modifier = Modifier.size(200.dp, 50.dp), enabled = false ) } }
8
Kotlin
6
9
a973af97556c2c3c5c800dac937d0007a13a3a1c
3,940
babylon-wallet-android
Apache License 2.0
src/main/kotlin/Model/AirQuality.kt
JyotimoyKashyap
434,660,784
false
{"Kotlin": 12467, "Assembly": 190}
package Model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AirQuality( val co: Double, @SerialName("gb-defra-index") val gb_defra_index: Int, val no2: Double, val o3: Double, val pm10: Double, val pm2_5: Double, val so2: Double, @SerialName("us-epa-index") val us_epa_index: Int )
0
Kotlin
0
4
1d6278aa60fe930eff06b3d53e34c44fac07f837
384
WeatherComposeDesktopApp
Apache License 2.0
app/src/main/java/com/steleot/jetpackcompose/playground/compose/materialiconsextended/MaterialIconsExtendedScreen.kt
Vivecstel
338,792,534
false
{"Kotlin": 1538487}
package com.steleot.jetpackcompose.playground.compose.materialiconsextended import androidx.compose.runtime.Composable import com.steleot.jetpackcompose.playground.compose.rest.MainScreen import com.steleot.jetpackcompose.playground.navigation.graph.MainNavRoutes import com.steleot.jetpackcompose.playground.navigation.graph.MaterialIconsExtendedNavRoutes val routes = listOf( MaterialIconsExtendedNavRoutes.ExtendedFilled, MaterialIconsExtendedNavRoutes.ExtendedOutlined, MaterialIconsExtendedNavRoutes.ExtendedRounded, MaterialIconsExtendedNavRoutes.ExtendedSharp, MaterialIconsExtendedNavRoutes.ExtendedTwoTone, ) @Composable fun MaterialIconsExtendedScreen() { MainScreen( title = MainNavRoutes.MaterialIConsExtended, list = routes, ) }
1
Kotlin
46
346
0161d9c7bf2eee53270ba2227a61d71ba8292ad0
788
Jetpack-Compose-Playground
Apache License 2.0
src/main/java/fr/mathieugood/vaadinjavakotlin/erp/crm/visitescommerciaux/metier/repository/ClientRepository.kt
MathieuGood
838,695,342
false
{"Kotlin": 320098, "Java": 9384, "HTML": 497}
package fr.mathieugood.vaadinjavakotlin.erp.crm.visitescommerciaux.metier.repository import fr.mathieugood.vaadinjavakotlin.erp.crm.visitescommerciaux.metier.data.Client import org.springframework.data.jpa.repository.JpaRepository /** * Cette interface `ClientRepository` sert de repository pour l'entité `Client`. * Elle hérite de `JpaRepository` qui fournit des méthodes pour les opérations CRUD. * * @property Client? Le type de l'entité pour laquelle ce repository est utilisé. * @property Long? Le type de l'identifiant de l'entité. */ interface ClientRepository : JpaRepository<Client?, Long?>
0
Kotlin
0
0
c4751282f2bc6e6cace4638f9eb6ddfa0311c924
608
VisitesCommerciaux
The Unlicense
plugins/radar-android-google-activity/src/main/java/org/radarbase/passive/google/activity/GoogleActivityProvider.kt
RADAR-base
85,591,443
false
{"Gradle": 21, "Java Properties": 2, "Proguard": 1, "Shell": 2, "Text": 13, "Ignore List": 5, "Batchfile": 1, "YAML": 7, "Markdown": 16, "Java": 80, "XML": 52, "HTML": 5, "Kotlin": 181, "C": 12, "C++": 265, "Makefile": 2, "PHP": 10, "RenderScript": 1, "INI": 1}
/* * Copyright 2017 The Hyve * * 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.radarbase.passive.google.activity import android.Manifest import android.os.Build import org.radarbase.android.RadarService import org.radarbase.android.source.BaseSourceState import org.radarbase.android.source.SourceProvider class GoogleActivityProvider(radarService: RadarService) : SourceProvider<BaseSourceState>(radarService) { override val description: String get() = radarService.getString(R.string.google_activity_description) override val pluginNames: List<String> get() = listOf( "google_activity", "activity", ".google.GoogleActivityProvider", "org.radarbase.passive.google.activity.GoogleActivityProvider", "org.radarcns.google.GoogleActivityProvider" ) override val serviceClass: Class<GoogleActivityService> = GoogleActivityService::class.java override val permissionsNeeded: List<String> = listOf(ACTIVITY_RECOGNITION_COMPAT) override val displayName: String get() = radarService.getString(R.string.google_activity_display_name) override val sourceProducer: String = "GOOGLE" override val sourceModel: String = "ACTIVITY" override val version: String get() = "1.0.0" companion object { val ACTIVITY_RECOGNITION_COMPAT = if ( Build.VERSION.SDK_INT >= 29 ) Manifest.permission.ACTIVITY_RECOGNITION else "com.google.android.gms.permission.ACTIVITY_RECOGNITION" } }
1
null
1
1
d0934db32797dc459076b4289148bbf4778441c0
2,047
radar-commons-android
Apache License 2.0
src/com/switchboxscraper/Interconnect.kt
nasirkhan-lm
282,000,663
true
{"Text": 3, "Markdown": 3, "YAML": 1, "Maven POM": 1, "XML": 2, "Gradle": 1, "Ignore List": 1, "Kotlin": 4, "Java": 165, "Tcl": 1, "TeX": 3}
package com.switchboxscraper import com.xilinx.rapidwright.device.Tile import com.xilinx.rapidwright.device.Wire import org.json.JSONObject enum class PJClass { CLK, ELEC, ROUTING } enum class PJType { SOURCE, SINK, BUF, INTERNAL, UNCLASSIFIED } enum class PJRoutingType { GLOBAL, CLB, INTERNAL, UNCLASSIFIED } enum class GlobalRouteDir { EE, WW, SS, NN, NE, NW, SE, SW, SR, SL, EL, ER, WL, WR, NL, NR, UNCLASSIFIED } data class GRJunctionType(val dir: GlobalRouteDir, val type: PJType) { override fun toString(): String = dir.toString() + type.toString() } data class PJProperty(val pjClass: PJClass, val pjType: PJType, val routingType: PJRoutingType) data class Point(val x : Int, val y : Int) fun getDirection(p1 : Point, p2 : Point) : GlobalRouteDir { // Check rectilinear if(p1.x == p2.x) { return if(p1.y < p2.y) GlobalRouteDir.NN else GlobalRouteDir.SS; }else if (p1.y == p2.y) { return if(p1.x > p2.x) GlobalRouteDir.WW else GlobalRouteDir.EE; } // Check diagonal if(p1.x > p2.x){ return if(p1.y < p2.y) GlobalRouteDir.NW else GlobalRouteDir.SW; } else { return if(p1.y < p2.y) GlobalRouteDir.NE else GlobalRouteDir.SE; } } data class JunctionQueryResult(val pipJunctions: Set<Wire>, val clusters: Map<GRJunctionType, Set<Wire>>) // A directed graph of the connectivity of each GRJunctionType data class ClusterQueryResult(val types: Set<GRJunctionType>, val connections: Map<GRJunctionType, Set<GRJunctionType>>) // Collection of each type of query result data class InterconnectQueryResult(val junctionResult: JunctionQueryResult, val clusterResult: ClusterQueryResult) data class NutcrackerPipJunctionConn (val name : String, val pos : String); data class NutcrackerPipJunction (var name : String, var backwards_pjs : MutableList<NutcrackerPipJunctionConn> = mutableListOf(), var forward_pjs : MutableList<NutcrackerPipJunctionConn> = mutableListOf()) data class NutcrackerData(var name : String, var pos : String, val options : Map<String,String>, val pjs : List<NutcrackerPipJunction> = mutableListOf()) class Interconnect(tile: Tile) { // List of all pip junctions in the switchbox var pipJunctions = mutableSetOf<Wire>() // List of all pip junctions in the switchbox switch begin or end a global routing wire var globalPipJunctions = mutableSetOf<Wire>() // List of all pip junctions classified by their directionality var dirGlobalPipJunctions = mutableMapOf<GlobalRouteDir, MutableSet<Wire>>() var pjClassification = mutableMapOf<Wire, PJProperty>() var name: String = "" var tile: Tile = tile; var nutData : NutcrackerData? = null val multidropLongWires = listOf<String>("LV9", "LH6", "LV_L9") init { name = tile.name gatherPipJunctions() gatherGlobalPipJunctions() classifyGlobalPipJunctionDir() dumpToNutcracker() // Perform PIP junction classification pipJunctions.fold(pjClassification) { acc, pj -> acc[pj] = classifyPJ(pj); acc } } fun dumpToNutcracker(): JSONObject { // Gather all required information for the Nutcracker data format, and translate to the appropriate string // format val pos = "X${tile.tileXCoordinate}Y${tile.tileYCoordinate}" var options = mutableMapOf<String,String>() if (tile.tileXCoordinate % 2 == 0) { options["side"] = "L" } else { options["side"] = "R" } var pjs = mutableListOf<NutcrackerPipJunction>() for(pj in pipJunctions) { var npj = NutcrackerPipJunction(name = pj.wireName) // Either forwardPIPs or backwardPIPs will be empty. For the empty direction, we use getWireExternalWireTerminations // to determine the PIP Junctions of the external wire(s) which drive or is driven by this PIP junction. var fw = pj.forwardPIPs var bk = pj.backwardPIPs // If we identify that a PIP Junction connects to a long wire, the below logic will not manage to include // the input/output global wire, and need to manually account for this var isLongWirePJ = false if(pj.forwardPIPs.isNotEmpty()) { for (pip in pj.forwardPIPs) { var endTile = pip.endWire.tile var endPos = "X${endTile.tileXCoordinate}Y${endTile.tileYCoordinate}" if(pip.isBidirectional) { // Add the end of the PIP which is -not- this pip junction var w = pip.endWire if (pip.endWire == pj) { w = pip.startWire } npj.forward_pjs.add(NutcrackerPipJunctionConn(name = w.wireName, pos = endPos)) isLongWirePJ = true } else { npj.forward_pjs.add(NutcrackerPipJunctionConn(name = pip.endWireName, pos = endPos)) } } } else { for(wire in getWireExternalWireTerminations(pj)) { var endTile = wire.tile var endPos = "X${endTile.tileXCoordinate}Y${endTile.tileYCoordinate}" npj.forward_pjs.add(NutcrackerPipJunctionConn(name = wire.wireName, pos = endPos)) } } if(pj.backwardPIPs.isNotEmpty()){ for(pip in pj.backwardPIPs) { var startTile = pip.startWire.tile var startPos = "X${startTile.tileXCoordinate}Y${startTile.tileYCoordinate}" if(pip.isBidirectional) { // Disregard the PIP, it has already been counted as a forward pip and will be counted in the // other direction once the PJ of the other end of the bidirectional PIP is being dumped. continue } else { npj.backwards_pjs.add(NutcrackerPipJunctionConn(name = pip.startWireName, pos = startPos)) } } } else { for(wire in getWireExternalWireTerminations(pj)) { var startTile = wire.tile var startPos = "X${startTile.tileXCoordinate}Y${startTile.tileYCoordinate}" npj.backwards_pjs.add(NutcrackerPipJunctionConn(name = wire.wireName, pos = startPos)) } } if(isLongWirePJ) { // This is a long wire; wires are bidirectional and may have multiple drops. // However, to keep things uniform, we will select the PJ the furthest away from this tile to be the // connection which we keep for further analysis var externalWires = mutableSetOf<Wire>() for (pip in pj.node.allDownhillPIPs) { if(pip.startWire.tile != tile) { externalWires.add(pip.startWire) } } // Find furthest away PJ var w : Wire? = null for(wire in externalWires) { if(w == null){ w = wire } else { if (tile.getManhattanDistance(wire.tile) > tile.getManhattanDistance(w.tile)) { w = wire } } } var startTile = w!!.tile var startPos = "X${startTile.tileXCoordinate}Y${startTile.tileYCoordinate}" npj.forward_pjs.add(NutcrackerPipJunctionConn(name = w.wireName, pos = startPos)) } pjs.add(npj) } var nutOut = JSONObject() nutOut.put("name", name) nutOut.put("pos", pos) nutOut.put("options", options) nutOut.put("pip_junctions", pjs) return nutOut } fun gatherPipJunctions() { // Extract all pip junctions by iterating over all PIPs in the tile and collecting the pip start/stop wires // which are defined as the pip junctions. Only gather routable pips for( pip in tile.getPIPs()) { for (wire in listOf(pip.startWire, pip.endWire)){ if(getPJClass(wire) == PJClass.ROUTING) { pipJunctions.add(wire); } } } } fun gatherGlobalPipJunctions() { // A global pip junction will be located by determining whether the source (for END junctions) or sink // (for BEG junctions) are located in this tile, or in an external tile for(wire in pipJunctions){ val node = wire.node var candidateExternalTile = getExternalTile(wire) if (candidateExternalTile != null) { // Are we logically still on the same tile? This would be the case if the node terminated in ie. the CLB // connected to the switchbox, which will have the same coordinates val x = candidateExternalTile.tileXCoordinate val y = candidateExternalTile.tileYCoordinate if(x == tile.tileXCoordinate && y == tile.tileYCoordinate){ continue } globalPipJunctions.add(wire) } } } fun getWireExternalWireTerminations(wire : Wire): List<Wire> { var externalWires = mutableSetOf<Wire>() var node = wire.node var externalTile: Tile? = null var allWires = node.allWiresInNode if (wire.startWire == wire) { if (node.allDownhillPIPs.isEmpty()) println("?") var dhp = node.allDownhillPIPs // This is a source wire. Identify sink wires by iterating over the downhill PIPs and sanity checking that // they all terminate in the same tile. The downhill PIPs corresponds to the *outputs* within the pip // junction of the *end* switchbox which this wire connects to for (pip in node.allDownhillPIPs) { if(pip.startWire.tile != tile) { externalWires.add(pip.startWire) } } } else { for(multidropW in multidropLongWires){ if (wire.wireName.contains(multidropW)){ // This is a special case which cant seem to be handled properly by the default rapidwright functions. // This is the middle of a long wire wherein the long wire drives this PIP junction, but the junction // is unidirectional. // In this case, we want to add both possible drivers (both ends of the long wire) as external wires // these two wires are always the first two of the allWiresInNode struct externalWires.add(node.allWiresInNode[0]) externalWires.add(node.allWiresInNode[1]) return externalWires.toList() } } // This is a sink wire. The source wire will be the base wire of the associated node externalWires.add(node.allWiresInNode[0]) } return externalWires.toList() } /** * Given @param wire, a wire on the border of this switchbox, returns the tile of which the node of this wire * connects to. */ fun getExternalTile(wire : Wire): Tile? { var node = wire.node var externalTile: Tile? = null if (wire.startWire == wire) { if (node.allDownhillPIPs.isEmpty()) println("?") // This is a source wire. Identify sink wires by iterating over the downhill PIPs and sanity checking that // they all terminate in the same tile. The downhill PIPs corresponds to the *outputs* within the pip // junction of the *end* switchbox which this wire connects to // Filter any pips which are located in the current tile. These may be bounces into the tile var externalPips = node.allDownhillPIPs.filter { it.tile != tile } if(externalPips.isEmpty()) return null // Cannot be an external tile; all pips are internal (possibly a FAN wire) // Get a candidate external tile which we check others against externalTile = externalPips[0].tile // Next, we want to ensure that all other downhill pips are located in the same external tile val pipsInSameTile = externalPips.all { it.tile == externalTile } if (wire.wireName.contains("NL1BEG0")) { // println("") } if (!pipsInSameTile) { println("Wire ${wire.toString()} fanned out to pips located in different external tiles!") for (pip in externalPips) { if (tile.getTileManhattanDistance(pip.tile) > tile.getTileManhattanDistance(externalTile)) { externalTile = pip.tile } } println("Selected tile furthest away: ${externalTile!!.name}\n") } } else { // This is a sink wire. The source wire will be the base wire of the associated node externalTile = node.tile } if (externalTile == this.tile){ // This implies that both sourc and sink of the wire was within the current tile. // In this case - even if the wires appears in the global routing network, we ignore the connection. // (Where ignoring implies that we count the wire as being part of the internal routing network of the // switchbox). return null } return externalTile } /** * Analyses the connectivity of each Pip junction onto the global routing network, to determine the direction * of the incoming wire (from the global routing network) into the PIP junction. */ fun classifyGlobalPipJunctionDir() { for(pip in globalPipJunctions) { var externalTile = getExternalTile(pip) if(externalTile == null) continue // External tile detected. Get the direction between the two tiles val p1 = Point(tile.tileXCoordinate, tile.tileYCoordinate) val p2 = Point(externalTile.tileXCoordinate, externalTile.tileYCoordinate) val dir = getDirection(p1, p2) if (dirGlobalPipJunctions[dir] == null){ dirGlobalPipJunctions[dir] = mutableSetOf<Wire>() } dirGlobalPipJunctions[dir]?.add(pip) } } fun wireLength(wire : Wire): Int? { val externalTile = getExternalTile(wire) ?: return null return tile.getTileManhattanDistance(externalTile) } fun wireSpan(wire : Wire): Point? { val externalTile = getExternalTile(wire) ?: return null val p1 = Point(tile.tileXCoordinate, tile.tileYCoordinate) val p2 = Point(externalTile.tileXCoordinate, externalTile.tileYCoordinate) return Point(p2.x - p1.x, p2.y - p1.y) } fun processQuery(query: GraphQuery): InterconnectQueryResult { // -------------------------------------------------------------------- // Step 1: Process interconnect // -------------------------------------------------------------------- var pipJunctions = pipJunctions.toMutableSet() // Copy PIP junctions of the interconnect // Cluster PIP Junctions based on inferred position in the switch box var pipJunctionClusters = mutableMapOf<GRJunctionType, MutableSet<Wire>>() var pipJunctionToCluster = mutableMapOf<Wire, GRJunctionType>() // Convenience map for looking up the cluster of a PIP junction pipJunctions.map { clusterPIPJunction(it, pipJunctionClusters, pipJunctionToCluster) } // Remove any excluded clusters and the PIP junctions of these clusters in our list of pip junctions included // in this graph val excludedClusters = pipJunctionClusters.filter { it.key in query.excludes } var excludedNodes = excludedClusters.entries.fold(mutableListOf<Wire>()) { nodes, excludedCluster -> excludedCluster.value.map { nodes.add(it) }; nodes } pipJunctions.removeAll { it in excludedNodes } pipJunctionClusters.keys.removeAll { it in excludedClusters.keys } val junctionResult = JunctionQueryResult(pipJunctions, pipJunctionClusters) // -------------------------------------------------------------------- // Step 2: Process cluster connectivity // -------------------------------------------------------------------- var clusterConnectivity = mutableMapOf<GRJunctionType, MutableSet<GRJunctionType>>() // Initialize graph pipJunctionClusters.map { clusterConnectivity[it.key] = mutableSetOf() } val clusterTypes = pipJunctionClusters.keys // For each cluster type pipJunctionClusters.map { cluster -> // For each PIP Junction within the cluster cluster.value.map { pipj -> // For each forward PIP pipj.forwardPIPs.map {pip -> if(pipJunctions.contains(pip.endWire)) { val connectsToCluster = pipJunctionToCluster[pip.endWire]!! clusterConnectivity[cluster.key]?.add(connectsToCluster) } } } } val clusterResult = ClusterQueryResult(clusterTypes, clusterConnectivity) // -------------------------------------------------------------------- // Step 3: Return results // -------------------------------------------------------------------- return InterconnectQueryResult(junctionResult, clusterResult) } private fun clusterPIPJunction(pj: Wire, clusters: MutableMap<GRJunctionType, MutableSet<Wire>>, reverseClusters: MutableMap<Wire, GRJunctionType>) { var dir: GlobalRouteDir var type = PJType.UNCLASSIFIED val wn = pj.wireName // Deduce direction dir = when { wn.startsWith("EE") -> GlobalRouteDir.EE wn.startsWith("NN") -> GlobalRouteDir.NN wn.startsWith("SS") -> GlobalRouteDir.SS wn.startsWith("WW") -> GlobalRouteDir.WW wn.startsWith("NE") -> GlobalRouteDir.NE wn.startsWith("NW") -> GlobalRouteDir.NW wn.startsWith("SE") -> GlobalRouteDir.SE wn.startsWith("SW") -> GlobalRouteDir.SW else -> GlobalRouteDir.UNCLASSIFIED } if (dir != GlobalRouteDir.UNCLASSIFIED) { // Deduce type type = when { wn.contains("BEG") -> PJType.SINK wn.contains("END") -> PJType.SOURCE else -> PJType.UNCLASSIFIED // unhandled } } val grjType = GRJunctionType(dir, type) if (!clusters.containsKey(grjType)) { clusters[grjType] = mutableSetOf() } clusters[grjType]?.add(pj) reverseClusters[pj] = grjType } private fun getPJClass(wire: Wire): PJClass { val wn = wire.wireName return when { wn.contains("CLK") -> PJClass.CLK wn.contains("VCC") || wn.contains("GND") -> PJClass.ELEC else -> PJClass.ROUTING } } private fun getPJType(pj: Wire): PJType { val bkPips = pj.backwardPIPs val fwPips = pj.forwardPIPs when { bkPips.size == 1 && fwPips.size == 1 -> return PJType.BUF fwPips.size == 0 -> return PJType.SINK bkPips.size == 0 -> return PJType.SOURCE fwPips.size > 1 && bkPips.size > 1 -> return PJType.INTERNAL else -> assert(false) } return PJType.SOURCE } private fun getPJRoutingType(pj: Wire) = PJRoutingType.GLOBAL private fun classifyPJ(pj: Wire) = PJProperty(getPJClass(pj), getPJType(pj), getPJRoutingType(pj)) }
0
null
0
0
38e9c43320209f33877300052394b3f7346c2da4
20,362
RapidWright
Apache License 2.0
plugins/kotlin/idea/tests/testData/copyPaste/imports/withConflict/ConflictsExplicitStarImport.kt
JetBrains
2,489,216
false
{"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// IGNORE_K2_COPY // IGNORE_K2_CUT /* this test should pass once KTIJ-29859 is fixed */ package a fun foo() {} fun Int.ext() {} fun Int.test() { <selection>ext() foo()</selection> }
1
null
1
1
0d546ea6a419c7cb168bc3633937a826d4a91b7c
190
intellij-community
Apache License 2.0
src/main/kotlin/sschr15/aocsolutions/Day9.kt
sschr15
317,887,086
false
null
package sschr15.aocsolutions import sschr15.aocsolutions.util.* /** * Day 9: Smoke Basin * * - Part 1: Find the sum of all "low points'" "risk levels" * - Part 2: Find the three largest "basins" and multiply their sizes */ fun day9() { val input = getChallenge(2021, 9) val grid = input.map { it.toList() .filter { c -> c.isDigit() } .map { c -> c.digitToInt() } } .toGrid() // region Part 1 val lowPoints = grid.toPointMap().filter { (point, value) -> val neighbors = grid.getNeighbors(point, includeDiagonals = false) neighbors.all { (_, i) -> i > value } }.toList() // a "risk level" is just a low point's value plus 1 val riskLevels = lowPoints.map { (_, value) -> value + 1 } println("Part 1: ${riskLevels.sum()}") // endregion // region Part 2 val lowPointsToCheck = lowPoints.toMutableList() val basinSizes = mutableListOf<Int>() while (lowPointsToCheck.isNotEmpty()) { val (lowPoint, _) = lowPointsToCheck.removeAt(0) val basinPoints = findBasin(grid, lowPoint) lowPointsToCheck.removeIf { (point, _) -> point in basinPoints } basinSizes.add(basinPoints.size) } // largest three basins val largestBasins = basinSizes.sortedDescending().take(3) println("Part 2: ${largestBasins.mul()}") // endregion } fun main() { day9() } /** * Finds the points in a basin around a given point. A basin is a set of points enclosed by * points with a value of 9. */ private fun findBasin(grid: Grid<Int>, lowPoint: Point): Set<Point> { val visited = mutableSetOf<Point>() val queue = mutableListOf(lowPoint) while (queue.isNotEmpty()) { val point = queue.removeAt(0) visited.add(point) val neighbors = grid.getNeighbors(point, includeDiagonals = false) queue.addAll(neighbors.filter { (it, value) -> value < 9 && !visited.contains(it) }.keys) } return visited }
0
Kotlin
0
0
8b68ad1aa6584e16f9af9a0eb121d76781402020
1,974
advent-of-code
MIT License
client/app/src/main/java/com/petrov/vitaliy/caraccidentapp/domain/models/responses/accident/CarAccidentEntityGetResponse.kt
ADsty
493,215,764
false
null
package com.petrov.vitaliy.caraccidentapp.domain.models.responses.accident data class CarAccidentEntityGetResponse( val carAccidentEntityID: Long, val entityState: String, val carAccidentID: Long, val trafficPoliceOfficerID: Long )
0
Kotlin
0
0
d3e957717cb51980d428c533530d45673c1b42fc
249
thesis-2022
MIT License
api/src/main/kotlin/io/sparkled/viewmodel/StageSummaryViewModel.kt
sparkled
53,776,686
false
null
package io.sparkled.viewmodel import io.sparkled.model.entity.v2.StageEntity data class StageSummaryViewModel( val id: Int, val name: String, ) { companion object { fun fromModel(model: StageEntity) = StageSummaryViewModel( id = model.id, name = model.name, ) } }
20
Kotlin
21
72
562e917af188c2ebf98c8e729446cde101f96dc2
322
sparkled
MIT License
kotlin-api/repository/src/main/kotlin/com/kotlin/api/app/DepartmentRepository.kt
savasdd
695,105,370
false
{"Kotlin": 22615}
package com.kotlin.api.app import com.kotlin.api.entity.Department import org.springframework.data.jpa.repository.JpaRepository interface DepartmentRepository : JpaRepository<Department, Long> {}
0
Kotlin
0
0
924a04f7c9ff52418e54a0489f0f19b18d6c9269
197
kotlin-projects
MIT License
src/main/java/me/m64diamondstar/ingeniamccore/general/player/IngeniaPlayer.kt
M64DiamondStar
526,220,818
false
null
package me.m64diamondstar.ingeniamccore.general.player import me.m64diamondstar.ingeniamccore.IngeniaMC import me.m64diamondstar.ingeniamccore.attractions.utils.AttractionUtils import me.m64diamondstar.ingeniamccore.data.files.PlayerConfig import me.m64diamondstar.ingeniamccore.games.PhysicalGameType import me.m64diamondstar.ingeniamccore.games.parkour.Parkour import me.m64diamondstar.ingeniamccore.general.levels.LevelUtils.getLevel import me.m64diamondstar.ingeniamccore.general.levels.LevelUtils.getLevelUpLevels import me.m64diamondstar.ingeniamccore.general.levels.LevelUtils.getRewards import me.m64diamondstar.ingeniamccore.general.levels.LevelUtils.isLevelUp import me.m64diamondstar.ingeniamccore.general.scoreboard.Scoreboard import me.m64diamondstar.ingeniamccore.general.tablist.TabList import me.m64diamondstar.ingeniamccore.general.warps.WarpUtils import me.m64diamondstar.ingeniamccore.utils.LocationUtils.getLocationFromString import me.m64diamondstar.ingeniamccore.utils.TeamHandler import me.m64diamondstar.ingeniamccore.utils.Times import me.m64diamondstar.ingeniamccore.utils.messages.Colors import me.m64diamondstar.ingeniamccore.utils.messages.MessageLocation import me.m64diamondstar.ingeniamccore.utils.messages.MessageType import me.m64diamondstar.ingeniamccore.wands.Wands.getAccessibleWands import net.kyori.adventure.audience.Audience import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.TextColor import net.md_5.bungee.api.ChatMessageType import net.md_5.bungee.api.chat.TextComponent import org.bukkit.* import org.bukkit.entity.Player import org.bukkit.event.inventory.InventoryType import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack import org.bukkit.persistence.PersistentDataType import org.bukkit.scheduler.BukkitRunnable import java.text.SimpleDateFormat import java.util.* class IngeniaPlayer(val player: Player) { private var scoreboard: Scoreboard? = null private var previousInventory: Inventory? = null val playerConfig: PlayerConfig = PlayerConfig(player.uniqueId) fun startUp() { game = null allowDamage = false player.teleport(WarpUtils.getNearestLocation(player)) setScoreboard(true) setTablist(true) giveMenuItem() TeamHandler.addPlayer(player) player.isCollidable = false if (player.isOp) player.setPlayerListName(Colors.format("#c43535&lLead #ffdede$name")) else if (player.hasPermission( "ingenia.team" ) ) player.setPlayerListName( Colors.format( "#4180bf&lTeam #deefff$name" ) ) else if (player.hasPermission("ingenia.vip+")) player.setPlayerListName( Colors.format( "#9054b0VIP+ #f9deff$name" ) ) else if (player.hasPermission("ingenia.vip")) player.setPlayerListName( Colors.format( "#54b0b0VIP #defdff$name" ) ) else player.setPlayerListName(Colors.format("#a1a1a1Visitor #cccccc$name")) AttractionUtils.getAllAttractions().forEach { it.spawnRidecountSign(player) } } val name: String get() = player.name val prefix: String get() = if (player.isOp) Colors.format("#c43535&lLead") else if (player.hasPermission( "ingenia.team" ) ) Colors.format("#4180bf&lTeam") else if (player.hasPermission("ingenia.vip+")) Colors.format( "#9054b0VIP+" ) else if (player.hasPermission("ingenia.vip")) Colors.format("#54b0b0VIP") else Colors.format( "#a1a1a1Visitor" ) var currentAreaName: String? get() { val container = player.persistentDataContainer val name = container.get(NamespacedKey(IngeniaMC.plugin, "current-area"), PersistentDataType.STRING) if(name.equals("null", ignoreCase = true)) return null return name } set(value) { val container = player.persistentDataContainer if(value == null) container.set( NamespacedKey(IngeniaMC.plugin, "current-area"), PersistentDataType.STRING, "null") else container.set( NamespacedKey(IngeniaMC.plugin, "current-area"), PersistentDataType.STRING, "$value") } fun sendMessage(string: String) { player.sendMessage(Colors.format(string)) } fun setNewLinkAttempt(){ val container = player.persistentDataContainer container.set( NamespacedKey(IngeniaMC.plugin, "discord-link-cooldown"), PersistentDataType.LONG, System.currentTimeMillis()) } fun isNewLinkingAttemptAvailable(): Boolean{ val container = player.persistentDataContainer val cooldown = container.get(NamespacedKey(IngeniaMC.plugin, "discord-link-cooldown"), PersistentDataType.LONG) ?: return true if(System.currentTimeMillis() - cooldown < 82800000) return false // Still on cooldown return true // Difference in time is bigger than 1 day -> May attempt new linking session } fun getLinkingCooldown(): String{ val container = player.persistentDataContainer val cooldown = container.get(NamespacedKey(IngeniaMC.plugin, "discord-link-cooldown"), PersistentDataType.LONG)!! + 82800000 - System.currentTimeMillis() val format = SimpleDateFormat("kk:mm:ss") val args = format.format(Date(cooldown)).split(":") return "${args[0]}h ${args[1]}m ${args[2]}s" } fun resetLinkingCooldown(){ val container = player.persistentDataContainer container.remove(NamespacedKey(IngeniaMC.plugin, "discord-link-cooldown"),) } fun sendMessage(string: String, messageType: MessageType) { player.sendMessage(Colors.format(string, messageType)) } fun sendMessage(string: String, messageLocation: MessageLocation) { if (messageLocation == MessageLocation.CHAT) player.sendMessage(Colors.format(string)) if (messageLocation == MessageLocation.HOTBAR) player.spigot().sendMessage( ChatMessageType.ACTION_BAR, TextComponent( Colors.format(string) ) ) if (messageLocation == MessageLocation.TITLE) player.sendTitle(Colors.format(string), "", 10, 50, 10) if (messageLocation == MessageLocation.SUBTITLE) player.sendTitle("", Colors.format(string), 10, 50, 10) } fun setGameMode(gameMode: GameMode) { player.gameMode = gameMode this.sendMessage( "Your gamemode has changed to: " + gameMode.toString().lowercase(Locale.getDefault()), MessageType.BACKGROUND ) } fun sendMessage(s: String, color: String) { this.sendMessage(Colors.format(color + s)) } val isInGame: Boolean get() { val container = player.persistentDataContainer val name = container.get(NamespacedKey(IngeniaMC.plugin, "current-game"), PersistentDataType.STRING) ?: return false try{ PhysicalGameType.valueOf(name) }catch (ex: Exception){ return false } return true } var game: PhysicalGameType? get(){ val container = player.persistentDataContainer val name = container.get(NamespacedKey(IngeniaMC.plugin, "current-game"), PersistentDataType.STRING) ?: return null return try { PhysicalGameType.valueOf(name) }catch (ex: IllegalArgumentException){ null } } set(value) { val container = player.persistentDataContainer container.set( NamespacedKey(IngeniaMC.plugin, "current-game"), PersistentDataType.STRING, value.toString() ) } var isInGameLeavingState: Boolean get() { val container = player.persistentDataContainer val name = container.get(NamespacedKey(IngeniaMC.plugin, "is-in-game-leaving-state"), PersistentDataType.STRING) return name.toBoolean() } set(value) { val container = player.persistentDataContainer container.set( NamespacedKey(IngeniaMC.plugin, "is-in-game-leaving-state"), PersistentDataType.STRING, value.toString() ) } var exp: Long get() = playerConfig.getExp() set(l) { if (isLevelUp(exp, l)) levelUp(exp, l) playerConfig.setExp(l) } fun addExp(l: Long) { if (isLevelUp(exp, exp + l)) levelUp(exp, exp + l) val newExp = l + exp playerConfig.setExp(newExp) } fun getLevel(): Int{ return getLevel(exp) } private fun levelUp(previousExp: Long, newExp: Long) { for (level in getLevelUpLevels(previousExp, newExp)) { for (reward in getRewards(level)) { reward.execute(this) } } var rewardDisplay = "" for(reward in getRewards(getLevel(newExp))){ if(rewardDisplay == ""){ rewardDisplay = reward.getDisplay() }else{ rewardDisplay += "${MessageType.BACKGROUND}, ${reward.getDisplay()}" } } player.sendMessage(Colors.format("\uFE01")) player.sendMessage(Colors.format(" ${MessageType.SUCCESS}&lLevel Up")) player.sendMessage(Colors.format(" ${MessageType.BACKGROUND}Level ${getLevel(previousExp)} ➡ ${getLevel(newExp)}")) player.sendMessage(Colors.format(" ${MessageType.BACKGROUND}Rewards: ")) player.sendMessage(Colors.format(" $rewardDisplay")) player.sendMessage(" ") } var bal: Long get() = playerConfig.getBal() set(l) { playerConfig.setBal(l) } fun addBal(l: Long) { playerConfig.setBal(l + bal) } var allowDamage: Boolean get() { val container = player.persistentDataContainer return container.get(NamespacedKey(IngeniaMC.plugin, "allow-damage"), PersistentDataType.STRING).toBoolean() } set(value) { val container = player.persistentDataContainer container.set( NamespacedKey(IngeniaMC.plugin, "allow-damage"), PersistentDataType.STRING, "$value") } fun setScoreboard(on: Boolean) { if (scoreboard == null) scoreboard = Scoreboard(this) if (on) { scoreboard!!.createBoard() scoreboard!!.startUpdating() scoreboard!!.showBoard() } else { scoreboard!!.hideBoard() } } private fun setTablist(on: Boolean) { val tabList = TabList(IngeniaMC.plugin) if (on) { for (header in Objects.requireNonNull(IngeniaMC.plugin.config.getConfigurationSection("Tablist")) !!.getStringList("Header")) { tabList.addHeader(header, player) } for (footer in Objects.requireNonNull(IngeniaMC.plugin.config.getConfigurationSection("Tablist")) !!.getStringList("Footer")) { tabList.addFooter( footer.replace( "%online%", Bukkit.getOnlinePlayers().size.toString() + "" ) ) } } else { tabList.clearHeader() tabList.clearFooter() } tabList.showTab(player) } val wands: List<ItemStack> get() = getAccessibleWands(player) fun setWand(item: ItemStack?) { player.inventory.setItem(5, item) player.playSound(player.location, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 2f, 1.5f) } var joinMessage: String? get() = playerConfig.getJoinMessage()!!.replace("%player%", Colors.format(playerConfig.getJoinColor() + player.name + "#ababab")) set(msg) { playerConfig.setJoinMessage(msg!!) } var leaveMessage: String? get() = playerConfig.getLeaveMessage()!!.replace("%player%", Colors.format(playerConfig.getJoinColor() + player.name + "#ababab")) set(msg) { playerConfig.setLeaveMessage(msg!!) } fun openInventory(inventory: Inventory?) { Bukkit.getScheduler().runTask(IngeniaMC.plugin, Runnable { if (player.openInventory.type != InventoryType.CRAFTING) previousInventory = player.openInventory.topInventory player.openInventory(inventory!!) }) } fun giveMenuItem() { val itemStack = ItemStack(Material.NETHER_STAR) val itemMeta = itemStack.itemMeta!! itemMeta.setDisplayName(Colors.format("#f4b734&lIngeniaMC")) itemMeta.lore = listOf(Colors.format(MessageType.LORE + "Click to open the IngeniaMC menu.")) itemStack.itemMeta = itemMeta player.inventory.setItem(4, itemStack) } fun setPreviousLocation(location: Location) { val container = player.persistentDataContainer container.set( NamespacedKey(IngeniaMC.plugin, "previous-location"), PersistentDataType.STRING, location.world!!.name + ", " + location.x + ", " + location.y + ", " + location.z + ", " + location.yaw + ", " + location.pitch ) } val previousLocation: Location? get() { val container = player.persistentDataContainer val string = container.get(NamespacedKey(IngeniaMC.plugin, "previous-location"), PersistentDataType.STRING) return if (string != null) { getLocationFromString(string) } else null } fun givePermission(permission: String) { Bukkit.dispatchCommand( Bukkit.getConsoleSender(), "lp user " + player.name + " permission set " + permission + " true" ) } fun startParkour(parkour: Parkour){ game = PhysicalGameType.PARKOUR isInGameLeavingState = false sendMessage(MessageType.PLAYER_UPDATE + "Use '/leave' to cancel the parkour.") object: BukkitRunnable(){ val startTime = System.currentTimeMillis() var currentTime = System.currentTimeMillis() override fun run() { val timeDisplay = Times.formatTime(currentTime - startTime) //Display normal time in actionbar (player as Audience).sendActionBar(Component.text("${parkour.displayName} current time: $timeDisplay").color(TextColor .fromHexString(MessageType.PLAYER_UPDATE))) //If player is at end if(player.location.distanceSquared(parkour.endLocation!!) <= parkour.endRadius){ (player as Audience).sendActionBar(Component.text("${parkour.displayName} finished in: $timeDisplay").color(TextColor .fromHexString(MessageType.PLAYER_UPDATE))) sendMessage(MessageType.PLAYER_UPDATE + "${parkour.displayName} has been finished in $timeDisplay.") player.playSound(player.location, Sound.UI_TOAST_CHALLENGE_COMPLETE, 0.5f, 1f) player.sendTitle(Colors.format(MessageType.PLAYER_UPDATE + parkour.displayName), Colors.format(MessageType.PLAYER_UPDATE + timeDisplay), 10, 50, 10) game = null this.cancel() return } if(isInGameLeavingState){ player.sendTitle(Colors.format(MessageType.PLAYER_UPDATE + parkour.displayName), Colors.format(MessageType.ERROR + "Cancelled"), 10, 50, 10) sendMessage(MessageType.PLAYER_UPDATE + "You left the parkour.") game = null isInGameLeavingState = false this.cancel() return } currentTime = System.currentTimeMillis() } }.runTaskTimer(IngeniaMC.plugin, 0L, 1L) } }
0
Kotlin
0
3
500313c223ca987ceb18b806671ad67dd5a7f725
16,515
IngeniaMC-Core
MIT License
src/main/kotlin/com/linusfinance/es/boilerplate/controller/ReplayController.kt
amaljoyc
384,190,256
false
{"Kotlin": 34340}
package com.linusfinance.es.boilerplate.controller import com.linusfinance.es.boilerplate.replay.ReplayService import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RestController @RestController class ReplayController(private val replayService: ReplayService) { @PostMapping("/replay") fun replay(): String { replayService.replay("com.linusfinance.es.boilerplate.query") return "Replay started" } }
0
Kotlin
0
0
e860b837584e6ccac71f5d95db5213fcdcfb17bd
483
event-sourcing-and-cqrs
MIT License
automotive/src/main/java/us/berkovitz/plexaaos/library/MusicSource.kt
joeyberkovitz
549,953,378
false
{"Kotlin": 111880}
/* * Copyright 2017 Google 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 us.berkovitz.plexaaos.library import android.os.Bundle import android.support.v4.media.MediaMetadataCompat import androidx.annotation.IntDef import us.berkovitz.plexapi.media.MediaItem import us.berkovitz.plexapi.media.Playlist /** * Interface used by [MusicService] for looking up [MediaMetadataCompat] objects. * * Because Kotlin provides methods such as [Iterable.find] and [Iterable.filter], * this is a convenient interface to have on sources. */ interface MusicSource : Iterable<Playlist> { /** * Begins loading the data for this music source. */ suspend fun load() suspend fun loadPlaylist(playlistId: String): Playlist? fun getPlaylist(playlistId: String): Playlist? fun playlistIterator(playlistId: String): Iterator<MediaItem>? fun getPlaylistItems(playlistId: String): Array<MediaItem>? /** * Method which will perform a given action after this [MusicSource] is ready to be used. * * @param performAction A lambda expression to be called with a boolean parameter when * the source is ready. `true` indicates the source was successfully prepared, `false` * indicates an error occurred. */ fun whenReady(performAction: (Boolean) -> Unit): Boolean fun playlistWhenReady(playlistId: String, performAction: (Playlist?) -> Unit): Boolean fun search(query: String, extras: Bundle): List<MediaMetadataCompat> } @IntDef( STATE_CREATED, STATE_INITIALIZING, STATE_INITIALIZED, STATE_ERROR ) @Retention(AnnotationRetention.SOURCE) annotation class State /** * State indicating the source was created, but no initialization has performed. */ const val STATE_CREATED = 1 /** * State indicating initialization of the source is in progress. */ const val STATE_INITIALIZING = 2 /** * State indicating the source has been initialized and is ready to be used. */ const val STATE_INITIALIZED = 3 /** * State indicating an error has occurred. */ const val STATE_ERROR = 4 /** * Base class for music sources in UAMP. */ abstract class AbstractMusicSource : MusicSource { @State var state: Int = STATE_CREATED set(value) { if (value == STATE_INITIALIZED || value == STATE_ERROR) { synchronized(onReadyListeners) { field = value onReadyListeners.forEach { listener -> listener(state == STATE_INITIALIZED) } onReadyListeners.clear() } } else { field = value } } private val playlistState: MutableMap<String, Int> = hashMapOf() private val playlistReadyListeners = mutableMapOf<String, MutableList<(Playlist?) -> Unit>>() fun getPlaylistState(playlistId: String): Int { return playlistState[playlistId] ?: STATE_CREATED } fun setPlaylistState(playlistId: String, playlist: Playlist?, state: Int){ synchronized(playlistState) { if (state == STATE_INITIALIZED || state == STATE_ERROR) { synchronized(playlistReadyListeners) { playlistState[playlistId] = state playlistReadyListeners[playlistId]?.forEach { listener -> listener(playlist) } playlistReadyListeners.clear() } } else { playlistState[playlistId] = state } } } private val onReadyListeners = mutableListOf<(Boolean) -> Unit>() /** * Performs an action when this MusicSource is ready. * * This method is *not* threadsafe. Ensure actions and state changes are only performed * on a single thread. */ override fun whenReady(performAction: (Boolean) -> Unit): Boolean = when (state) { STATE_CREATED, STATE_INITIALIZING -> { onReadyListeners += performAction false } else -> { performAction(state != STATE_ERROR) true } } override fun playlistWhenReady(playlistId: String, performAction: (Playlist?) -> Unit): Boolean = synchronized(playlistState) { when (playlistState[playlistId]) { null, STATE_CREATED, STATE_INITIALIZING -> { synchronized(playlistReadyListeners) { if (playlistReadyListeners[playlistId] == null) { playlistReadyListeners[playlistId] = mutableListOf() } playlistReadyListeners[playlistId]!! += performAction false } } else -> { performAction(getPlaylist(playlistId)) true } } } /** * Handles searching a [MusicSource] from a focused voice search, often coming * from the Google Assistant. */ override fun search(query: String, extras: Bundle): List<MediaMetadataCompat> { return emptyList() } } private const val TAG = "MusicSource"
9
Kotlin
3
8
475fc64d321b545693ee3968aa2af8e598aaaa85
5,814
plex-aaos
MIT License
src/main/kotlin/com/raynigon/raylevation/base/service/LocationsParser.kt
raynigon
524,500,850
false
null
package com.raynigon.raylevation.base.service import com.raynigon.raylevation.infrastructure.model.GeoPoint import org.springframework.stereotype.Service import java.text.ParseException /** * The location parser consumes a string and produces a list of GeoPoints. * * The input String should be formatted according to this EBNF syntax: * ``` * INPUT = GEO_POINT, {"|", GEO_POINT}; * GEO_POINT = FLOATING_POINT, ",", FLOATING_POINT; * FLOATING_POINT = ["-"], DIGIT, {DIGIT}, ["."], {DIGIT}; * DIGIT = "0" |"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"; * ``` */ interface LocationsParser { /** * Parse the query string into [GeoPoint]s. * * @param input The query string which should be parsed * @return The GeoPoints which were serialized to the query string */ fun parse(input: String): List<GeoPoint> } /** * Implementation of [LocationsParser] */ @Service class LocationsParserImpl : LocationsParser { override fun parse(input: String): List<GeoPoint> { if (input.isEmpty()) return emptyList() return input.split('|') .map { toGeoPoint(it, input) } } private fun toGeoPoint(point: String, totalInput: String): GeoPoint { val parts = point.split(",").mapNotNull { it.toDoubleOrNull() } if (parts.size != 2) { val index = totalInput.indexOf(point) throw ParseException("Unexpected input '$point' at position $index", index) } return GeoPoint(parts[0], parts[1]) } }
3
Kotlin
0
1
b92322f564060eb860e1d7c81432ce4d38e6935f
1,557
raylevation
Apache License 2.0
plugins/reporters/evaluated-model/src/main/kotlin/CopyrightStatement.kt
oss-review-toolkit
107,540,288
false
null
/* * Copyright (C) 2017 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.reporter.reporters.evaluatedmodel /** * Wrapper class for copyright statements. Allows Jackson to generate IDs for them when storing them in a separate list * for de-duplication. */ data class CopyrightStatement( val statement: String )
317
null
309
1,590
ed4bccf37bab0620cc47dbfb6bfea8542164725a
1,025
ort
Apache License 2.0
src/main/java/dev/sora/relay/game/utils/MathUtils.kt
Rmejia39
733,988,687
false
{"Kotlin": 278950, "Java": 46466}
package dev.sora.relay.game.utils import org.cloudburstmc.math.vector.Vector3f import org.cloudburstmc.math.vector.Vector3i import kotlin.math.hypot import kotlin.math.roundToInt data class Rotation(var yaw: Float, var pitch: Float) fun toRotation(from: Vector3f, to: Vector3f): Rotation { val diffX = (to.x - from.x).toDouble() val diffY = (to.y - from.y).toDouble() val diffZ = (to.z - from.z).toDouble() return Rotation( (Math.toDegrees(Math.atan2(diffZ, diffX)).toFloat() - 90f), ((-Math.toDegrees(Math.atan2(diffY, Math.sqrt(diffX * diffX + diffZ * diffZ)))).toFloat()) ) } /** * Calculate difference between two rotations * * @param a rotation * @param b rotation * @author CzechHek * @return difference between rotation */ fun getRotationDifference(a: Rotation, b: Rotation) = hypot(getAngleDifference(a.yaw, b.yaw), a.pitch - b.pitch) /** * Calculate difference between two angle points * * @param a angle point * @param b angle point * @author CzechHek * @return difference between angle points */ fun getAngleDifference(a: Float, b: Float) = ((a - b) % 360f + 540f) % 360f - 180f fun Vector3i.toVector3f(): Vector3f { return Vector3f.from(x.toFloat(), y.toFloat(), z.toFloat()) } fun Vector3f.toVector3i(): Vector3i { return Vector3i.from(x.roundToInt(), y.roundToInt(), z.roundToInt()) } fun Vector3f.toVector3iFloor(): Vector3i { return Vector3i.from(floorX, floorY, floorZ) } fun Vector3f.distance(x: Int, y: Int, z: Int): Float { return distance(x.toFloat(), y.toFloat(), z.toFloat()) } fun Vector3f.distance(vector3i: Vector3i): Float { return distance(vector3i.x, vector3i.y, vector3i.z) }
0
Kotlin
0
0
cab149c57e1011ae2ac184fb0666f2b7218f1443
1,672
ProtoHax
MIT License
src/main/kotlin/engine/repositories/UserRepository.kt
h8-h4
361,759,133
false
{"JavaScript": 18136, "Kotlin": 17178, "HTML": 6262, "CSS": 2699}
package engine.repositories import engine.entities.User import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.data.jpa.repository.Modifying import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.PagingAndSortingRepository import org.springframework.data.repository.query.Param import org.springframework.stereotype.Repository import org.springframework.transaction.annotation.Transactional import javax.persistence.ColumnResult import javax.persistence.ConstructorResult import javax.persistence.SqlResultSetMapping @Repository interface UserRepository: PagingAndSortingRepository<User, Long> { fun findByNickname(nickname: String): User? fun existsByNickname(nickname: String): Boolean @Transactional @Modifying @Query("update users u set u.highestScore = :score where u.nickname = :nickname") fun updateScoreByNickname(@Param("nickname") nickname: String, @Param("score") score: Int) /* @SqlResultSetMapping( name="groupDetailsMapping", classes = arrayOf( ConstructorResult( targetClass = User::class, columns = arrayOf( ColumnResult(name="nickname", type=String::class), ColumnResult(name="highestScore", type=Int::class) ) ) ) )*/ @Query( value = "select nickname, highestScore from users", countQuery = "select count(u.nickname) from users u" ) fun findAllExceptPassword(pageable: Pageable): Page<User> }
0
JavaScript
0
0
3d986f0796e7a751e0b50018ef7341c2b8b5a65c
1,722
Pong-kcs-2020
MIT License
sample/src/main/java/com/paulrybitskyi/valuepicker/sample/moviefilteringpicker/model/StreamingService.kt
mars885
287,747,523
false
null
/* * Copyright 2020 <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paulrybitskyi.valuepicker.sample.moviefilteringpicker.model internal enum class StreamingService(val title: String) { NETFLIX("Netflix"), PRIME("Prime"), HULU("Hulu"), HBO_MAX("HBO"), DISNEY("Disney"), APPLE_TV("Apple"), }
1
null
9
52
97bad659f3658c943b681731491680217b40bdfe
860
value-picker
Apache License 2.0
app/src/main/java/com/rekyb/jyro/ui/discover/DiscoverViewModel.kt
rekyb
421,738,590
false
{"Kotlin": 77959}
package com.rekyb.jyro.ui.discover import android.os.Parcelable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.rekyb.jyro.common.Resources import com.rekyb.jyro.domain.use_case.remote.SearchUserUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DiscoverViewModel @Inject constructor( private val search: SearchUserUseCase, ) : ViewModel() { private val _query = MutableStateFlow("") private val _dataState = MutableStateFlow(DiscoverState()) val dataState get() = _dataState.asStateFlow() var scrollState: Parcelable? = null fun searchUser(query: String) { val isErrorEncountered = _dataState.value.result is Resources.Error if (query == _query.value && !isErrorEncountered) return viewModelScope.launch { search(query) .flowOn(Dispatchers.IO) .distinctUntilChanged() .collect { _dataState.value = dataState.value.copy(result = it) } _query.value = query } } }
0
Kotlin
0
2
1e3ac8c8f3372275c25137ccd153d52688bad639
1,389
github-app
MIT License
app/src/main/java/com/rekyb/jyro/ui/discover/DiscoverViewModel.kt
rekyb
421,738,590
false
{"Kotlin": 77959}
package com.rekyb.jyro.ui.discover import android.os.Parcelable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.rekyb.jyro.common.Resources import com.rekyb.jyro.domain.use_case.remote.SearchUserUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DiscoverViewModel @Inject constructor( private val search: SearchUserUseCase, ) : ViewModel() { private val _query = MutableStateFlow("") private val _dataState = MutableStateFlow(DiscoverState()) val dataState get() = _dataState.asStateFlow() var scrollState: Parcelable? = null fun searchUser(query: String) { val isErrorEncountered = _dataState.value.result is Resources.Error if (query == _query.value && !isErrorEncountered) return viewModelScope.launch { search(query) .flowOn(Dispatchers.IO) .distinctUntilChanged() .collect { _dataState.value = dataState.value.copy(result = it) } _query.value = query } } }
0
Kotlin
0
2
1e3ac8c8f3372275c25137ccd153d52688bad639
1,389
github-app
MIT License
src/main/kotlin/fr/clevertechware/introduction/spring/cloud/stream/messaging/MessageProducer.kt
clevertechware
752,829,503
false
{"Kotlin": 8929}
package fr.clevertechware.introduction.spring.cloud.stream.messaging import fr.clevertechware.introduction.spring.cloud.stream.Message import fr.clevertechware.introduction.spring.cloud.stream.Result import org.springframework.cloud.stream.function.StreamOperations class MessageProducer(private val streamOperations: StreamOperations) { fun produce(message: Message) { LOGGER.info("Producing message: {}", message) val result = Result( id = message.id, timestamp = message.timestamp, content = message.content, sender = message.sender, receiver = message.receiver ) streamOperations.send("processor-out-0", result) } private companion object { private val LOGGER = org.slf4j.LoggerFactory.getLogger(MessageProducer::class.java) } }
1
Kotlin
0
0
875e7b92508080ccb90dc6395f3892e1d912207a
851
spring-boot-native-compilation
MIT License
src/main/kotlin/no/nav/k9punsj/brev/dto/FritekstbrevDto.kt
navikt
216,808,662
false
null
package no.nav.k9punsj.brev.dto data class FritekstbrevDto( val overskrift: String, val brødtekst: String )
9
Kotlin
1
1
69241bba5ffdcfc1c11c24f2d7b6e7eebae84f8f
117
k9-punsj
MIT License
foryouandme/src/main/java/com/foryouandme/ui/studyinfo/compose/StudyInfoHeader.kt
4YouandMeData
610,425,317
false
null
package com.foryouandme.ui.studyinfo.compose import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.foryouandme.core.arch.deps.ImageConfiguration import com.foryouandme.core.arch.deps.logoStudySecondary import com.foryouandme.core.arch.toData import com.foryouandme.entity.configuration.Configuration import com.foryouandme.entity.user.User import com.foryouandme.ui.compose.ForYouAndMeTheme @Composable fun StudyInfoHeader( user: User?, configuration: Configuration, imageConfiguration: ImageConfiguration, modifier: Modifier = Modifier, ) { Box( modifier = modifier ) { if (user != null) Image( painter = painterResource( id = imageConfiguration.logoStudySecondary(user, configuration) ), contentDescription = null, modifier = Modifier .fillMaxWidth() .align(Alignment.Center) ) Text( text = configuration.text.tab.studyInfoTitle, color = configuration.theme.secondaryColor.value, style = MaterialTheme.typography.h1, modifier = Modifier .align(Alignment.BottomCenter) .padding(bottom = 30.dp) ) } } @Preview @Composable private fun StudyInfoHeaderPreview() { ForYouAndMeTheme(Configuration.mock().toData()) { StudyInfoHeader( user = User.mock(), it, ImageConfiguration.mock(), Modifier .fillMaxWidth() .height(200.dp) ) } }
0
Kotlin
0
0
bc82972689db5052344365ac07c8f6711f5ad7fa
2,169
4YouandMeAndroid
MIT License
modules/repository/src/main/java/com/uogames/repository/map/ModuleCardMap.kt
Gizcerbes
476,234,521
false
{"Kotlin": 676334}
package com.uogames.repository.map import com.uogames.database.entity.ModuleCardEntity import com.uogames.dto.local.LocalCardView import com.uogames.dto.local.LocalModuleCard import com.uogames.dto.local.LocalModuleCardView import com.uogames.dto.local.LocalModuleView import java.util.UUID object ModuleCardMap { fun ModuleCardEntity.toDTO() = LocalModuleCard( id = id, idModule = idModule, idCard = idCard, globalId = UUID.fromString(globalId) ?: UUID.randomUUID(), globalOwner = globalOwner ) fun LocalModuleCard.toEntity() = ModuleCardEntity( id = id, idModule = idModule, idCard = idCard, globalId = globalId.toString(), globalOwner = globalOwner ) suspend fun ModuleCardEntity.toViewDTO( moduleBuilder: suspend (id: Int) -> LocalModuleView, cardBuilder: suspend (id: Int) -> LocalCardView ) = LocalModuleCardView( id = id, module = moduleBuilder(idModule), card = cardBuilder(idCard), globalId = UUID.fromString(globalId) ?: UUID.randomUUID(), globalOwner = globalOwner ) fun LocalModuleCardView.toEntity() = ModuleCardEntity( id = id, idModule = module.id, idCard = card.id, globalId = globalId.toString(), globalOwner = globalOwner ) }
0
Kotlin
0
0
ea694bd872c4ec2e76e761bb9735127a326fce8e
1,205
Remember
Apache License 2.0
local/src/iosMain/kotlin/io/github/gmvalentino8/local/core/DefaultSettingsFactory.kt
wasabi-muffin
457,416,965
false
{"Kotlin": 55509}
package io.github.gmvalentino8.local.core import com.russhwolf.settings.AppleSettings import com.russhwolf.settings.Settings import platform.Foundation.NSUserDefaults actual class DefaultSettingsFactory( private val delegate: NSUserDefaults, ) : SettingsFactory { override fun create(): Settings = AppleSettings(delegate) }
1
Kotlin
0
0
56f14f334670e691775f4028c97b3e76d947fb3a
334
Cyclone-Modular-Template-KMM
MIT License
app/src/main/java/com/ivan/androidultimateexample/ui/main/activities/ActivityEditFragment.kt
IvanSimovic
237,819,921
false
null
package com.ivan.androidultimateexample.ui.main.activities import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.ivan.androidultimateexample.R import com.ivan.androidultimateexample.ui.main.activity.MainActivity import com.ivan.androidultimateexample.ui.util.setUpAsDateTimePicker import kotlinx.android.synthetic.main.activity_edit_fragment.* import org.koin.androidx.viewmodel.ext.android.viewModel class ActivityEditFragment : Fragment(R.layout.activity_edit_fragment) { private val viewModel by viewModel<ActivityEditViewModel>() private val args by navArgs<ActivityEditFragmentArgs>() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (requireActivity() as MainActivity).setHeader( getString(R.string.title_activities), MainActivity.HeaderStyles.INFO_SCREEN ) { findNavController().navigateUp() } viewModel.activity.observe(viewLifecycleOwner) { it?.let { txtDate.setUpAsDateTimePicker({ viewModel.activity.value!!.date = it }, it.date) } } viewModel.getActivity(args.activityId) btnSave.setOnClickListener { viewModel.updateActivity() } viewModel.navigationEvent.observe(viewLifecycleOwner) { it?.let { navigation -> when (navigation) { ActivityEditViewModel.NavigationEvent.BACK -> findNavController().navigateUp() } } } } }
0
Java
1
1
5705012f912f7884434abda2381ec6b82322da81
1,731
AndroidUltimateExample
MIT License
ui/src/androidMain/kotlin/kiwi/orbit/compose/ui/foundation/LocalRoundedContainerScope.kt
kiwicom
289,355,053
false
{"Kotlin": 909017, "Shell": 1833, "CSS": 443}
package kiwi.orbit.compose.ui.foundation import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.staticCompositionLocalOf public val LocalRoundedContainerScope: ProvidableCompositionLocal<Boolean> = staticCompositionLocalOf { false }
20
Kotlin
17
97
10e765f359518f667d9a1c77952b7fcf63ce96d2
275
orbit-compose
MIT License
peerdroid/src/test/java/rdx/works/peerdroid/messagechunking/MessageSplitterTest.kt
radixdlt
513,047,280
false
{"Kotlin": 4940882, "HTML": 215350, "Ruby": 2757, "Shell": 1963}
package rdx.works.peerdroid.messagechunking import io.ktor.util.decodeBase64String import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import rdx.works.core.blake2Hash import rdx.works.core.toHexString import rdx.works.peerdroid.data.PackageDto import kotlin.random.Random import kotlin.test.assertEquals class MessageSplitterTest { @Test fun `verify a byte array which contains a test message is properly split to a list of packages`() = runBlocking { val textMessage = "this is a test message" val textMessageByteArray = textMessage.toByteArray() val actualSizeOfPackages = 2 val actualHashOfMessageInHexString = "afa5476b53c5a84d311c3ed8ff8f77e4990fe190e52cfeba745df6f67c83b7c6" val actualMessageByteCount = 22 val actualChunkData = "dGhpcyBpcyBhIHRlc3QgbWVzc2FnZQ==" val listOfPackages = splitMessage(textMessageByteArray) assertEquals(listOfPackages.size, actualSizeOfPackages) assert(listOfPackages[0] is PackageDto.MetaData) val metadataPackage = listOfPackages[0] as PackageDto.MetaData val expectedHashOfMessageInHexString = metadataPackage.hashOfMessage//.toHexString() assertEquals(expectedHashOfMessageInHexString, actualHashOfMessageInHexString) val expectedMessageByteCount = metadataPackage.messageByteCount assertEquals(expectedMessageByteCount, actualMessageByteCount) assert(listOfPackages[1] is PackageDto.Chunk) val chunkPackage = listOfPackages[1] as PackageDto.Chunk val expectedChunkData = chunkPackage.chunkData assertEquals(expectedChunkData, actualChunkData) assertEquals(expectedChunkData.decodeBase64String(), textMessage) } @Test fun givenByteArrayIsLargerThanChunkSize_WhenSplit_VerifyChunkCountIsCorrect() = runBlocking { // given val byteArraySize = 100 val chunkSize = 20 val byteArray = Random.nextBytes(byteArraySize) // when val result = byteArray.splitMessage(chunkSize = chunkSize) // then val metadataPackage = result.first() as PackageDto.MetaData Assert.assertEquals(metadataPackage.chunkCount, byteArraySize / chunkSize) } @Test fun givenByteArrayIsLargerThanChunkSize_WhenSplit_VerifyHashOfMessageIsCorrect() = runBlocking { // given val byteArraySize = 100 val chunkSize = 20 val byteArray = Random.nextBytes(byteArraySize) // when val result = byteArray.splitMessage(chunkSize = chunkSize) // then val metadataPackage = result.first() as PackageDto.MetaData Assert.assertTrue(metadataPackage.hashOfMessage.contentEquals(byteArray.blake2Hash().toHexString())) } @Test fun givenByteArrayIsLargerThanChunkSize_WhenSplit_VerifyMessageByteCountIsCorrect() = runBlocking { // given val byteArraySize = 100 val chunkSize = 20 val byteArray = Random.nextBytes(byteArraySize) // when val result = byteArray.splitMessage(chunkSize = chunkSize) // then val metadataPackage = result.first() as PackageDto.MetaData Assert.assertEquals(metadataPackage.messageByteCount, byteArraySize) } @Test fun givenByteArrayIsSmallerThanChunkSize_WhenSplit_VerifyChunkCountIsOne() = runBlocking { // given val byteArraySize = 100 val chunkSize = 120 val byteArray = Random.nextBytes(byteArraySize) // when val result = byteArray.splitMessage(chunkSize = chunkSize) // then val metadataPackage = result.first() as PackageDto.MetaData Assert.assertEquals(metadataPackage.chunkCount, 1) } @Test fun givenByteArrayIsSmallerThanChunkSize_WhenSplit_VerifyHashOfMessageIsCorrect() = runBlocking { // given val byteArraySize = 100 val chunkSize = 120 val byteArray = Random.nextBytes(byteArraySize) // when val result = byteArray.splitMessage(chunkSize = chunkSize) // then val metadataPackage = result.first() as PackageDto.MetaData Assert.assertTrue(metadataPackage.hashOfMessage.contentEquals(byteArray.blake2Hash().toHexString())) } @Test fun givenByteArrayIsSmallerThanChunkSize_WhenSplit_VerifyMessageByteCountIsCorrect() = runBlocking { // given val byteArraySize = 100 val chunkSize = 120 val byteArray = Random.nextBytes(byteArraySize) // when val result = byteArray.splitMessage(chunkSize = chunkSize) // then val metadataPackage = result.first() as PackageDto.MetaData Assert.assertEquals(metadataPackage.messageByteCount, byteArraySize) } }
6
Kotlin
6
9
36c670dd32d181e462e9962d476cb8a370fbe4fe
4,797
babylon-wallet-android
Apache License 2.0
Src/app/src/main/java/com/jakubisz/obd2ai/ui/adapters/BluetoothRecyclerViewAdapter.kt
JaKuBisz
729,487,821
false
{"Kotlin": 58492}
package com.jakubisz.obd2ai.ui.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.jakubisz.obd2ai.R import com.jakubisz.obd2ai.model.BluetoothDeviceDTO class BluetoothRecyclerViewAdapter ( private val devices: List<BluetoothDeviceDTO>, private val onItemClick: (BluetoothDeviceDTO) -> Unit ) : RecyclerView.Adapter<BluetoothRecyclerViewAdapter.DeviceViewHolder>() { class DeviceViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val deviceNameTextView: TextView = view.findViewById(R.id.deviceNameTextView) fun bind(device: BluetoothDeviceDTO, onItemClick: (BluetoothDeviceDTO) -> Unit) { deviceNameTextView.text = device.name ?: "Unknown Device" itemView.setOnClickListener { onItemClick(device) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeviceViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_bluetooth_device, parent, false) return DeviceViewHolder(view) } override fun onBindViewHolder(holder: DeviceViewHolder, position: Int) { holder.bind(devices[position], onItemClick) } override fun getItemCount(): Int = devices.size }
2
Kotlin
1
4
e6a6b9c8820ce8ab699e263160ef9944ff793785
1,373
OBD2AI
Apache License 2.0
soil-query-core/src/commonMain/kotlin/soil/query/QueryFilter.kt
soil-kt
789,648,330
false
{"Kotlin": 255620, "Makefile": 915}
// Copyright 2024 Soil Contributors // SPDX-License-Identifier: Apache-2.0 package soil.query import soil.query.internal.SurrogateKey interface QueryFilter { val type: QueryFilterType? val keys: Array<SurrogateKey>? val predicate: ((QueryModel<*>) -> Boolean)? } class InvalidateQueriesFilter( override val type: QueryFilterType? = null, override val keys: Array<SurrogateKey>? = null, override val predicate: ((QueryModel<*>) -> Boolean)? = null, ) : QueryFilter class RemoveQueriesFilter( override val type: QueryFilterType? = null, override val keys: Array<SurrogateKey>? = null, override val predicate: ((QueryModel<*>) -> Boolean)? = null, ) : QueryFilter class ResumeQueriesFilter( override val keys: Array<SurrogateKey>? = null, override val predicate: (QueryModel<*>) -> Boolean ) : QueryFilter { override val type: QueryFilterType = QueryFilterType.Active } enum class QueryFilterType { Active, Inactive }
0
Kotlin
0
32
44e9b452d7473078472749cfc6c16717ac4827be
981
soil
Apache License 2.0
benchmarks/src/jmh/kotlin/kotlinx/io/tests/benchmarks/TextDecodeBenchmark.kt
MaTriXy
113,157,182
true
{"Kotlin": 738718}
package kotlinx.io.tests.benchmarks import kotlinx.io.core.* import org.openjdk.jmh.annotations.* import java.util.concurrent.* @State(Scope.Benchmark) @Fork(1) @Warmup(iterations = 10) @Measurement(iterations = 15) //@BenchmarkMode(Mode.Throughput, Mode.AverageTime) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) class TextDecodeBenchmark { /* # Run complete. Total time: 00:05:05 Benchmark Mode Cnt Score Error Units TextDecodeBenchmark.largeASCIIKt thrpt 15 5,090 ± 0,186 ops/ms TextDecodeBenchmark.largeASCIIReader thrpt 15 17,374 ± 0,769 ops/ms TextDecodeBenchmark.largeASCIIStringCtor thrpt 15 49,870 ± 2,700 ops/ms TextDecodeBenchmark.largeMbKt thrpt 15 3,146 ± 0,066 ops/ms TextDecodeBenchmark.largeMbReader thrpt 15 6,137 ± 0,244 ops/ms TextDecodeBenchmark.largeMbStringCtor thrpt 15 7,640 ± 0,541 ops/ms TextDecodeBenchmark.smallASCIIKt thrpt 15 11766,753 ± 371,396 ops/ms TextDecodeBenchmark.smallASCIIReader thrpt 15 584,426 ± 67,464 ops/ms TextDecodeBenchmark.smallASCIIStringCtor thrpt 15 27157,153 ± 965,774 ops/ms TextDecodeBenchmark.smallMbKt thrpt 15 9256,542 ± 478,120 ops/ms TextDecodeBenchmark.smallMbReader thrpt 15 642,241 ± 48,872 ops/ms TextDecodeBenchmark.smallMbStringCtor thrpt 15 19371,117 ± 437,930 ops/ms */ @Benchmark fun smallMbKt() = smallTextPacket.copy().readText() @Benchmark fun smallMbReader() = smallTextBytes.inputStream().reader().readText() @Benchmark fun smallMbStringCtor() = String(smallTextBytes, Charsets.UTF_8) @Benchmark fun largeMbKt() = largeTextPacket.copy().readText() @Benchmark fun largeMbReader() = largeTextBytes.inputStream().reader().readText() @Benchmark fun largeMbStringCtor() = String(largeTextBytes, Charsets.UTF_8) @Benchmark fun smallASCIIKt() = smallTextPacketASCII.copy().readText() @Benchmark fun smallASCIIReader() = smallTextBytesASCII.inputStream().reader().readText() @Benchmark fun smallASCIIStringCtor() = String(smallTextBytesASCII, Charsets.UTF_8) @Benchmark fun largeASCIIKt() = largeTextPacketASCII.copy().readText() @Benchmark fun largeASCIIReader() = largeTextBytesASCII.inputStream().reader().readText() @Benchmark fun largeASCIIStringCtor() = String(largeTextBytesASCII, Charsets.UTF_8) companion object { private val smallTextBytes = "\u0422\u0432\u0437.".toByteArray(Charsets.UTF_8) private val smallTextBytesASCII = "ABC.".toByteArray(Charsets.UTF_8) private val largeTextBytes = ByteArray(smallTextBytes.size * 10000) { smallTextBytes[it % smallTextBytes.size] } private val largeTextBytesASCII = ByteArray(smallTextBytesASCII.size * 10000) { smallTextBytesASCII[it % smallTextBytesASCII.size] } private val smallTextPacket = buildPacket { writeFully(smallTextBytes) } private val smallTextPacketASCII = buildPacket { writeFully(smallTextBytesASCII) } private val largeTextPacket = buildPacket { writeFully(largeTextBytes) } private val largeTextPacketASCII = buildPacket { writeFully(largeTextBytesASCII) } } }
0
Kotlin
0
0
ce254a62eb3419e5138037d662cde6d45c4da06c
3,373
kotlinx-io
Apache License 2.0
src/main/kotlin/dev/frozenmilk/mercurial/subsystems/SDKSubsystem.kt
Dairy-Foundation
768,236,531
false
{"Kotlin": 106094}
package dev.frozenmilk.mercurial.subsystems import com.qualcomm.robotcore.hardware.HardwareMap import dev.frozenmilk.dairy.core.FeatureRegistrar import org.firstinspires.ftc.robotcore.external.Telemetry @Suppress("unused") abstract class SDKSubsystem : Subsystem { private val hardwareMapCell: SubsystemObjectCell<HardwareMap> by lazy { subsystemCell { FeatureRegistrar.activeOpMode.hardwareMap } } protected val hardwareMap by hardwareMapCell private val telemetryCell: SubsystemObjectCell<Telemetry> by lazy { subsystemCell { FeatureRegistrar.activeOpMode.telemetry } } protected val telemetry by telemetryCell }
0
Kotlin
0
0
c7a964f625e31698a604750d6ae3dde96fd7137a
637
Mercurial
BSD 3-Clause Clear License
app/src/main/java/linusfessler/alarmtiles/shared/MediaPlaybackManager.kt
linusfessler
108,552,006
false
null
package linusfessler.alarmtiles.shared import android.media.AudioAttributes import android.media.AudioFocusRequest import android.media.AudioManager import android.os.Build import javax.inject.Inject import javax.inject.Singleton @Singleton class MediaPlaybackManager @Inject constructor(private val audioManager: AudioManager) { fun stopMediaPlayback() { requestAudioFocus() } private fun requestAudioFocus() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val audioAttributes = AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .build() val audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN) .setAudioAttributes(audioAttributes) .build() audioManager.requestAudioFocus(audioFocusRequest) } else { @Suppress("DEPRECATION") audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) } } }
0
Kotlin
0
1
720475951dfedce0a2c6d813269adec6ee6ed613
1,062
alarm-tiles
MIT License
src/test/kotlin/g1201_1300/s1262_greatest_sum_divisible_by_three/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
package g1201_1300.s1262_greatest_sum_divisible_by_three import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun maxSumDivThree() { assertThat(Solution().maxSumDivThree(intArrayOf(3, 6, 5, 1, 8)), equalTo(18)) } @Test fun maxSumDivThree2() { assertThat(Solution().maxSumDivThree(intArrayOf(4)), equalTo(0)) } @Test fun maxSumDivThree3() { assertThat(Solution().maxSumDivThree(intArrayOf(1, 2, 3, 4, 4)), equalTo(12)) } }
0
Kotlin
20
43
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
589
LeetCode-in-Kotlin
MIT License
src/main/kotlin/io/hirasawa/server/handlers/ScoreHandler.kt
HirasawaProject
256,633,551
false
null
package io.hirasawa.server.handlers import io.hirasawa.server.Hirasawa import io.hirasawa.server.bancho.enums.GameMode import io.hirasawa.server.bancho.user.BanchoUser import io.hirasawa.server.database.tables.BeatmapsTable import io.hirasawa.server.database.tables.UsersTable import io.hirasawa.server.objects.Beatmap import io.hirasawa.server.objects.Score import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.transactions.transaction class ScoreHandler(encodedScore: String) { private val separator = ':' var fileChecksum: String var username: String var scoreChecksum: String var count300: Int var count100: Int var count50: Int var countGeki: Int var countKatu: Int var countMiss: Int var countScore: Int var combo: Int var fullCombo: Boolean var ranking: String var mods: Int var pass: Boolean var mode: GameMode var date: String var version: String var score: Score? = null init { val scoreArray = encodedScore.split(separator) fileChecksum = scoreArray[0] username = scoreArray[1].trim() scoreChecksum = scoreArray[2] count300 = scoreArray[3].toInt() count100 = scoreArray[4].toInt() count50 = scoreArray[5].toInt() countGeki = scoreArray[6].toInt() countKatu = scoreArray[7].toInt() countMiss = scoreArray[8].toInt() countScore = scoreArray[9].toInt() combo = scoreArray[10].toInt() fullCombo = scoreArray[11] == "True" ranking = scoreArray[12] mods = scoreArray[13].toInt() pass = scoreArray[14] == "True" mode = GameMode.values()[scoreArray[15].toInt()] date = scoreArray[16] version = scoreArray[17] val user = Hirasawa.databaseToObject<BanchoUser>(BanchoUser::class, transaction { UsersTable.select { UsersTable.username eq username }.firstOrNull() }) val beatmap = Hirasawa.databaseToObject<Beatmap>(Beatmap::class, transaction { BeatmapsTable.select { BeatmapsTable.hash eq fileChecksum }.firstOrNull() }) if (user != null && beatmap != null) { score = Score(-1, user, countScore, combo, count50, count100, count300, countMiss, countKatu, countGeki, fullCombo, mods, -1, mode, -1, beatmap.id, calculateAccuracy()) } } private fun calculateAccuracy(): Float { // Ported from old closed-source nosue! project keeping variable names the same // TODO redo with better readability var accuracy = 0F when(mode) { GameMode.OSU -> { val totalPoints = (count300 * 300) + (count100 * 100) + (count50 * 50) val totalHits = count300 + count100 + count50 + countMiss accuracy = totalPoints / (totalHits * 300F) } GameMode.TAIKO -> { val totalPoints = ((count100 * 0.5F) + count300) * 300 val totalHits = count300 + count100 + countMiss accuracy = totalPoints / (totalHits * 300F) } GameMode.CATCH_THE_BEAT -> { val totalPoints = count300 + count100 + count50 val totalHits = count300 + count100 + count50 + countMiss accuracy = totalPoints / (totalHits * 300F) } GameMode.MANIA -> { val totalPoints = (count300 * 300F) + (count100 * 100F) + (count50 * 50F) + (countGeki * 300) + (countKatu * 200) val totalHits = count300 + count100 + count50 + countGeki + countKatu + countMiss accuracy = totalPoints / totalHits } } return accuracy } }
51
Kotlin
0
4
759951059996d438d8ede8c44d036a6908d6b80a
3,832
Hirasawa-Server
MIT License
app/src/main/java/com/webitel/mobile_demo_app/data/local/MessageDataItem.kt
webitel
718,075,081
false
{"Kotlin": 113068}
package com.webitel.mobile_demo_app.data.local import androidx.room.Entity import androidx.room.Index @Entity(tableName = "message_table", primaryKeys = ["uuid"], indices = [Index(value = ["id"],unique = true)]) data class MessageDataItem( override val uuid: String, override val id: Long?, override val dialogId: String, override val authorName: String, override val authorType: String, override val dateCreated: Long, override val body: String?, override val isIncoming: Boolean, override val isSent: Boolean, override val attribute: Long? = null, override val mediaName: String? = null, override val mediaId: String? = null, override val mediaType: String? = null, override val mediaSize: Long? = null, override val mediaUri: String? = null, override val mediaDownloadedBytes: Long? = null, override val mediaDownloading: Boolean? = null, override val mediaUploading: Boolean? = null, override val mediaUploadedBytes: Long? = null, override val errorCode: Int? = null, override val errorMessage: String? = null ): MessageItem interface MessageItem { val uuid: String val id: Long? val dialogId: String val authorName: String val authorType: String val dateCreated: Long val body: String? val isIncoming: Boolean val isSent: Boolean val attribute: Long? val mediaId: String? val mediaName: String? val mediaType: String? val mediaSize: Long? val mediaUri: String? val mediaDownloadedBytes: Long? val mediaDownloading: Boolean? val mediaUploading: Boolean? val mediaUploadedBytes: Long? val errorCode: Int? val errorMessage: String? }
0
Kotlin
0
0
4e6ff1930c63a674db8a15d3e84c82872b89f567
1,708
mobile-demo-app
MIT License
app/src/main/java/com/example/DiarioApplication/ui/Navegacion/InventoryNavGraph.kt
AdrianZa1
860,056,200
false
{"Kotlin": 135595}
package com.example.DiarioApplication.ui.navigation import CameraScreen import LoginScreen import NoteScreen import UserProfileScreen // Importamos la pantalla del perfil de usuario import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.example.DiarioApplication.DiarioApplication import com.example.DiarioApplication.ui.configuracion.ConfiguracionScreen import com.example.DiarioApplication.ui.pantalla_principal.HomeScreen import com.example.DiarioApplication.ui.vivencia.VivenciasScreen import com.example.inventory.ui.inicio_sesion.RegisterScreen import com.example.menu.MenuDesplegableScreen @Composable fun InventoryNavHost( navController: NavHostController, modifier: Modifier = Modifier, isDarkThemeEnabled: Boolean, onThemeChange: () -> Unit // Función para alternar el tema ) { NavHost( navController = navController, startDestination = "login", // Pantalla inicial modifier = modifier ) { composable("login") { LoginScreen( onLoginSuccess = { navController.navigate("vivencias") }, onNavigateToRegister = { navController.navigate("register") } ) } composable("register") { RegisterScreen( onRegisterClick = { navController.navigate("login") { popUpTo("login") { inclusive = true } } }, onNavigateToLogin = { navController.navigate("login") } ) } composable("camera") { CameraScreen( onCustomAction = { navController.navigate("home") } // Volver a la pantalla anterior tras capturar imagen ) } composable("home") { HomeScreen( onImageClick = { navController.navigate("camera") }, onNavigateToHome = { navController.navigate("vivencias") } ) } composable("vivencias") { // Nueva ruta para la pantalla de vivencias VivenciasScreen( navController = navController, onNavigateToAddVivencia = { navController.navigate("home") }, ) } composable("vivenciaDetalle") { NoteScreen( onHomeClick = { navController.navigate("vivencias") } // Vuelve a la pantalla anterior tras capturar imagen ) } composable("menuScreen") { MenuDesplegableScreen(navController = navController) } composable("configuracion") { ConfiguracionScreen( navController = navController, noteRepository = (LocalContext.current.applicationContext as DiarioApplication).container.noteRepository, isDarkThemeEnabled = isDarkThemeEnabled, // Pasa el valor del tema onThemeChange = onThemeChange // Pasa la función de cambio de tema ) } // Ruta para "Nueva Vivencia" que te lleva a la pantalla de Home composable("nuevaVivencia") { HomeScreen( onImageClick = { navController.navigate("camera") }, onNavigateToHome = { navController.navigate("vivencias") } ) } // Ruta para el perfil de usuario composable("userProfile/{userId}") { backStackEntry -> val userId = backStackEntry.arguments?.getString("userId")?.toIntOrNull() ?: 0 UserProfileScreen( userId = userId, onBackClick = { navController.popBackStack() } // Aquí se pasa el onBackClick ) } } }
0
Kotlin
0
0
b4879190d9581510d2f1fd7dfe11217f4a1f67cc
3,873
diario_personal
Apache License 2.0
StudyPlanet/src/main/java/com/qwict/studyplanetandroid/common/Resource.kt
Qwict
698,396,315
false
{"Kotlin": 194543}
package com.qwict.studyplanetandroid.common // Based on great tutorial by <NAME>: /** * A sealed class representing different states of a resource, typically used for data fetching operations. * * The [Resource] class has three subclasses: * - [Loading]: Indicates that the data is currently being loaded. * - [Success]: Indicates that the data has been successfully loaded. * - [Error]: Indicates that an error occurred during data loading, with an associated error message. * * @param T The type of data held by the resource. * @property data The data associated with the resource, if available. * @property message A descriptive message associated with the resource, usually for error states. */ sealed class Resource<T>(val data: T? = null, val message: String? = null) { /** * Represents the loading state of a resource. * * @param T The type of data being loaded. * @property data The data being loaded, if available. */ class Loading<T>(data: T? = null) : Resource<T>(data) /** * Represents the success state of a resource. * * @param T The type of data loaded successfully. * @property data The successfully loaded data. */ class Success<T>(data: T) : Resource<T>(data) /** * Represents the error state of a resource. * * @param T The type of data for which an error occurred. * @property message A descriptive message explaining the error. * @property data The data associated with the error, if available. */ class Error<T>(message: String, data: T? = null) : Resource<T>(data, message) }
0
Kotlin
0
0
79e50c70b579d5380a927d760f6a9398cee5db2b
1,619
StudyPlanetAndroid
MIT License
app/src/test/java/com/appttude/h_mal/atlas_weather/helper/ServicesHelperTest.kt
hmalik144
163,556,459
false
{"Kotlin": 277496, "Ruby": 3065}
package com.appttude.h_mal.atlas_weather.helper import com.appttude.h_mal.atlas_weather.data.location.LocationProviderImpl import com.appttude.h_mal.atlas_weather.data.network.response.weather.WeatherApiResponse import com.appttude.h_mal.atlas_weather.data.repository.Repository import com.appttude.h_mal.atlas_weather.data.repository.SettingsRepository import com.appttude.h_mal.atlas_weather.data.room.entity.CURRENT_LOCATION import com.appttude.h_mal.atlas_weather.data.room.entity.EntityItem import com.appttude.h_mal.atlas_weather.model.weather.FullWeather import com.appttude.h_mal.atlas_weather.utils.BaseTest import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.every import io.mockk.impl.annotations.MockK import kotlinx.coroutines.runBlocking import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import java.io.IOException import kotlin.properties.Delegates class ServicesHelperTest : BaseTest() { lateinit var helper: ServicesHelper @MockK lateinit var repository: Repository @MockK lateinit var settingsRepository: SettingsRepository @MockK lateinit var locationProvider: LocationProviderImpl lateinit var weatherResponse: WeatherApiResponse private var lat by Delegates.notNull<Double>() private var long by Delegates.notNull<Double>() private lateinit var latlon: Pair<Double, Double> private lateinit var fullWeather: FullWeather @Before fun setUp() { MockKAnnotations.init(this) helper = ServicesHelper(repository, settingsRepository, locationProvider) weatherResponse = getTestData("new_response.json", WeatherApiResponse::class.java) lat = weatherResponse.latitude!! long = weatherResponse.longitude!! latlon = Pair(lat, long) fullWeather = weatherResponse.mapData().apply { temperatureUnit = "°C" locationString = CURRENT_LOCATION } } @Test fun testWidgetDataAsync_successfulResponse() = runBlocking { // Arrange val entityItem = EntityItem(CURRENT_LOCATION, fullWeather) // Act coEvery { locationProvider.getCurrentLatLong() } returns Pair(lat, long) every { repository.isSearchValid(CURRENT_LOCATION) }.returns(true) coEvery { repository.getWeatherFromApi( lat.toString(), long.toString() ) }.returns(weatherResponse) coEvery { locationProvider.getLocationNameFromLatLong( lat, long ) }.returns(CURRENT_LOCATION) every { repository.saveLastSavedAt(CURRENT_LOCATION) } returns Unit coEvery { repository.saveCurrentWeatherToRoom(entityItem) } returns Unit // Assert val result = helper.fetchData() assertTrue(result) } @Test fun testWidgetDataAsync_unsuccessfulResponse() = runBlocking { // Act coEvery { locationProvider.getCurrentLatLong() } returns Pair(0.0, 0.0) every { repository.isSearchValid(CURRENT_LOCATION) }.returns(true) coEvery { repository.getWeatherFromApi("0.0", "0.0") } throws IOException("error") // Assert val result = helper.fetchData() assertTrue(!result) } @Test fun testWidgetDataAsync_invalidSearch() = runBlocking { // Act every { repository.isSearchValid(CURRENT_LOCATION) }.returns(false) // Assert val result = helper.fetchData() assertTrue(!result) } }
2
Kotlin
0
0
de8802f7b4c6d41f9fb04748d876e86f9f671575
3,570
Weather-apps
MIT License
emoji-google/src/main/java/dev/leonardpark/emoji/google/category/FoodCategory.kt
leokwsw
410,840,614
false
{"Kotlin": 2112009, "JavaScript": 13836}
package dev.leonardpark.emoji.google.category import dev.leonardpark.emoji.emoji.Emoji import dev.leonardpark.emoji.emoji.EmojiCategory import dev.leonardpark.emoji.google.R; @SuppressWarnings("PMD.MethodReturnsInternalArray") class FoodCategory: EmojiCategory { companion object { private val DATA = listOf( Emoji(0x1f34f, R.drawable.emoji_google_1f34f), Emoji(0x1f34e, R.drawable.emoji_google_1f34e), Emoji(0x1f350, R.drawable.emoji_google_1f350), Emoji(0x1f34a, R.drawable.emoji_google_1f34a), Emoji(0x1f34b, R.drawable.emoji_google_1f34b), Emoji(0x1f34c, R.drawable.emoji_google_1f34c), Emoji(0x1f349, R.drawable.emoji_google_1f349), Emoji(0x1f347, R.drawable.emoji_google_1f347), Emoji(0x1fad0, R.drawable.emoji_google_1fad0), Emoji(0x1f353, R.drawable.emoji_google_1f353), Emoji(0x1f348, R.drawable.emoji_google_1f348), Emoji(0x1f352, R.drawable.emoji_google_1f352), Emoji(0x1f351, R.drawable.emoji_google_1f351), Emoji(0x1f96d, R.drawable.emoji_google_1f96d), Emoji(0x1f34d, R.drawable.emoji_google_1f34d), Emoji(0x1f965, R.drawable.emoji_google_1f965), Emoji(0x1f95d, R.drawable.emoji_google_1f95d), Emoji(0x1f345, R.drawable.emoji_google_1f345), Emoji(0x1f346, R.drawable.emoji_google_1f346), Emoji(0x1f951, R.drawable.emoji_google_1f951), Emoji(0x1fad2, R.drawable.emoji_google_1fad2), Emoji(0x1f966, R.drawable.emoji_google_1f966), Emoji(0x1f96c, R.drawable.emoji_google_1f96c), Emoji(0x1fad1, R.drawable.emoji_google_1fad1), Emoji(0x1f952, R.drawable.emoji_google_1f952), Emoji(0x1f336, R.drawable.emoji_google_1f336), Emoji(0x1f33d, R.drawable.emoji_google_1f33d), Emoji(0x1f955, R.drawable.emoji_google_1f955), Emoji(0x1f9c4, R.drawable.emoji_google_1f9c4), Emoji(0x1f9c5, R.drawable.emoji_google_1f9c5), Emoji(0x1f954, R.drawable.emoji_google_1f954), Emoji(0x1f360, R.drawable.emoji_google_1f360), Emoji(0x1f950, R.drawable.emoji_google_1f950), Emoji(0x1f96f, R.drawable.emoji_google_1f96f), Emoji(0x1f35e, R.drawable.emoji_google_1f35e), Emoji(0x1f956, R.drawable.emoji_google_1f956), Emoji(0x1fad3, R.drawable.emoji_google_1fad3), Emoji(0x1f968, R.drawable.emoji_google_1f968), Emoji(0x1f9c0, R.drawable.emoji_google_1f9c0), Emoji(0x1f95a, R.drawable.emoji_google_1f95a), Emoji(0x1f373, R.drawable.emoji_google_1f373), Emoji(0x1f9c8, R.drawable.emoji_google_1f9c8), Emoji(0x1f95e, R.drawable.emoji_google_1f95e), Emoji(0x1f9c7, R.drawable.emoji_google_1f9c7), Emoji(0x1f953, R.drawable.emoji_google_1f953), Emoji(0x1f969, R.drawable.emoji_google_1f969), Emoji(0x1f357, R.drawable.emoji_google_1f357), Emoji(0x1f356, R.drawable.emoji_google_1f356), Emoji(0x1f32d, R.drawable.emoji_google_1f32d), Emoji(0x1f354, R.drawable.emoji_google_1f354), Emoji(0x1f35f, R.drawable.emoji_google_1f35f), Emoji(0x1f355, R.drawable.emoji_google_1f355), Emoji(0x1f96a, R.drawable.emoji_google_1f96a), Emoji(0x1f959, R.drawable.emoji_google_1f959), Emoji(0x1f9c6, R.drawable.emoji_google_1f9c6), Emoji(0x1f32e, R.drawable.emoji_google_1f32e), Emoji(0x1f32f, R.drawable.emoji_google_1f32f), Emoji(0x1fad4, R.drawable.emoji_google_1fad4), Emoji(0x1f957, R.drawable.emoji_google_1f957), Emoji(0x1f958, R.drawable.emoji_google_1f958), Emoji(0x1fad5, R.drawable.emoji_google_1fad5), Emoji(0x1f96b, R.drawable.emoji_google_1f96b), Emoji(0x1f35d, R.drawable.emoji_google_1f35d), Emoji(0x1f35c, R.drawable.emoji_google_1f35c), Emoji(0x1f372, R.drawable.emoji_google_1f372), Emoji(0x1f35b, R.drawable.emoji_google_1f35b), Emoji(0x1f363, R.drawable.emoji_google_1f363), Emoji(0x1f371, R.drawable.emoji_google_1f371), Emoji(0x1f95f, R.drawable.emoji_google_1f95f), Emoji(0x1f9aa, R.drawable.emoji_google_1f9aa), Emoji(0x1f364, R.drawable.emoji_google_1f364), Emoji(0x1f359, R.drawable.emoji_google_1f359), Emoji(0x1f35a, R.drawable.emoji_google_1f35a), Emoji(0x1f358, R.drawable.emoji_google_1f358), Emoji(0x1f365, R.drawable.emoji_google_1f365), Emoji(0x1f960, R.drawable.emoji_google_1f960), Emoji(0x1f96e, R.drawable.emoji_google_1f96e), Emoji(0x1f362, R.drawable.emoji_google_1f362), Emoji(0x1f361, R.drawable.emoji_google_1f361), Emoji(0x1f367, R.drawable.emoji_google_1f367), Emoji(0x1f368, R.drawable.emoji_google_1f368), Emoji(0x1f366, R.drawable.emoji_google_1f366), Emoji(0x1f967, R.drawable.emoji_google_1f967), Emoji(0x1f9c1, R.drawable.emoji_google_1f9c1), Emoji(0x1f370, R.drawable.emoji_google_1f370), Emoji(0x1f382, R.drawable.emoji_google_1f382), Emoji(0x1f36e, R.drawable.emoji_google_1f36e), Emoji(0x1f36d, R.drawable.emoji_google_1f36d), Emoji(0x1f36c, R.drawable.emoji_google_1f36c), Emoji(0x1f36b, R.drawable.emoji_google_1f36b), Emoji(0x1f37f, R.drawable.emoji_google_1f37f), Emoji(0x1f369, R.drawable.emoji_google_1f369), Emoji(0x1f36a, R.drawable.emoji_google_1f36a), Emoji(0x1f330, R.drawable.emoji_google_1f330), Emoji(0x1f95c, R.drawable.emoji_google_1f95c), Emoji(0x1f36f, R.drawable.emoji_google_1f36f), Emoji(0x1f95b, R.drawable.emoji_google_1f95b), Emoji(0x1f37c, R.drawable.emoji_google_1f37c), Emoji(0x2615, R.drawable.emoji_google_2615), Emoji(0x1f375, R.drawable.emoji_google_1f375), Emoji(0x1fad6, R.drawable.emoji_google_1fad6), Emoji(0x1f9c9, R.drawable.emoji_google_1f9c9), Emoji(0x1f9cb, R.drawable.emoji_google_1f9cb), Emoji(0x1f9c3, R.drawable.emoji_google_1f9c3), Emoji(0x1f964, R.drawable.emoji_google_1f964), Emoji(0x1f376, R.drawable.emoji_google_1f376), Emoji(0x1f37a, R.drawable.emoji_google_1f37a), Emoji(0x1f37b, R.drawable.emoji_google_1f37b), Emoji(0x1f942, R.drawable.emoji_google_1f942), Emoji(0x1f377, R.drawable.emoji_google_1f377), Emoji(0x1f943, R.drawable.emoji_google_1f943), Emoji(0x1f378, R.drawable.emoji_google_1f378), Emoji(0x1f379, R.drawable.emoji_google_1f379), Emoji(0x1f37e, R.drawable.emoji_google_1f37e), Emoji(0x1f9ca, R.drawable.emoji_google_1f9ca), Emoji(0x1f944, R.drawable.emoji_google_1f944), Emoji(0x1f374, R.drawable.emoji_google_1f374), Emoji(0x1f37d, R.drawable.emoji_google_1f37d), Emoji(0x1f963, R.drawable.emoji_google_1f963), Emoji(0x1f961, R.drawable.emoji_google_1f961), Emoji(0x1f962, R.drawable.emoji_google_1f962), Emoji(0x1f9c2, R.drawable.emoji_google_1f9c2) ) } override fun getEmojis(): List<Emoji> = DATA override fun getIcon(): Int = R.drawable.emoji_google_category_food }
1
Kotlin
2
6
47558b5d81c5bb7c86b988dfa9b192bee706f897
6,911
Emoji-Keyboard
Apache License 2.0
data/preferences/session/src/test/kotlin/dev/alvr/katana/data/preferences/session/datastore/SessionDataStoreTest.kt
alvr
446,535,707
false
null
package dev.alvr.katana.data.preferences.session.datastore import androidx.datastore.core.DataStore import dev.alvr.katana.common.tests.KoinTest4 import dev.alvr.katana.data.preferences.session.di.corruptedDataStoreNamed import dev.alvr.katana.data.preferences.session.di.dataStoreModule import dev.alvr.katana.data.preferences.session.di.dataStoreNamed import dev.alvr.katana.data.preferences.session.models.Session import io.kotest.matchers.equality.shouldBeEqualToComparingFields import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import org.junit.Test import org.koin.core.KoinApplication import org.koin.test.inject @ExperimentalCoroutinesApi internal class SessionDataStoreTest : KoinTest4() { private val dataStores by inject<Array<DataStore<Session>>>(dataStoreNamed) private val corruptedDataStores by inject<Array<DataStore<Session>>>(corruptedDataStoreNamed) override fun KoinApplication.initKoin() { modules(dataStoreModule) } @Test fun `initial session should equal to the Session class`() = runTest { dataStores.forEach { dataStore -> dataStore.data.first() shouldBeEqualToComparingFields Session() } } @Test fun `saving a session should return the same values`() = runTest { dataStores.forEach { dataStore -> with(dataStore) { updateData { p -> p.copy(anilistToken = "token", isSessionActive = true) } data.first() shouldBeEqualToComparingFields Session( anilistToken = "token", isSessionActive = true, ) } } } @Test fun `corrupted dataStore should recreate again the file with initial values`() = runTest { corruptedDataStores.forEach { corruptedDataStore -> corruptedDataStore.data.first() shouldBeEqualToComparingFields Session(anilistToken = "recreated") } } }
3
Kotlin
0
34
c056cbf1614bacbf39bb518a89aa6813ea5ae18c
1,969
katana
Apache License 2.0
kotlin/sol06differenceOfSquares.kt
gilarc
714,972,898
false
{"Kotlin": 11650, "Lua": 942}
// MIT License // Copyright (c) 2023 Gillar Ajie Prasatya class Squares(private val n: Int) { // A class to perform calculations related to sums and squares fun sumOfSquares(): Int { // Calculate the sum of squares for the range [1, n] return (1..n).sumBy { it * it } } fun squareOfSum(): Int { // Calculate the square of the sum for the range [1, n] val sum = (1..n).sum() return sum * sum } fun difference(): Int { // Calculate the difference between squareOfSum and sumOfSquares return squareOfSum() - sumOfSquares() } } fun main() { val n = 10 // Replace with the appropriate value of N val squares = Squares(n) val result = squares.difference() println(result) }
0
Kotlin
0
0
23c2930abc6031e46c62ee37c96e623b1386859e
777
myExercismSolutions
MIT License
app/app/src/main/java/com/solutions/note_it/data/User.kt
biagioPiraino
839,976,127
false
{"Kotlin": 90243, "Vue": 52032, "Go": 41922, "TypeScript": 22926, "HCL": 12288, "HTML": 335, "SCSS": 207}
package com.solutions.note_it.data import com.google.gson.annotations.SerializedName data class User( val id: String = "", @field:SerializedName("name") val name: String = "", @field:SerializedName("email") val email: String = "", @field:SerializedName("nickname") val nickname: String = "", @field:SerializedName("connection") val connection: String = "Username-Password-Authentication" ) { }
0
Kotlin
0
0
06117965f19ba6a028d9ee144cdec76d7dba4b92
415
note-it
MIT License
app/src/main/java/com/spitchenko/photoeditor/feature/main/domain/usecase/setcontrollerimage/SetControllerImage.kt
Onotole1
183,995,071
false
null
package com.spitchenko.photoeditor.feature.main.domain.usecase.setcontrollerimage import com.spitchenko.photoeditor.feature.main.domain.entity.SetImageRequest import io.reactivex.Completable interface SetControllerImage { operator fun invoke(request: SetImageRequest): Completable }
0
Kotlin
0
0
b165e6fe95d6a2a71930d27cf4948c2d35d76727
289
Photo-Editor
Apache License 2.0
springboot/src/main/kotlin/com/labijie/infra/mqts/spring/configuration/MqtsAutoConfiguration.kt
hongque-pro
314,188,221
false
null
package com.labijie.infra.mqts.spring.configuration import com.labijie.infra.IIdGenerator import com.labijie.infra.mqts.MQTransactionManager import com.labijie.infra.mqts.abstractions.* import com.labijie.infra.mqts.configuration.MQTransactionConfig import com.labijie.infra.mqts.impl.DefaultTransactionHolder import com.labijie.infra.mqts.impl.JacksonDataSerializer import com.labijie.infra.mqts.spring.MQTransactionApplicationListener import com.labijie.infra.mqts.spring.SpringInstanceFactory import com.labijie.infra.mqts.spring.condition.ConditionalOnMqts import com.labijie.infra.mqts.spring.interceptor.Aspect.MQTransactionAspect import com.labijie.infra.mqts.spring.processor.MqtsAnnotationProcessor import com.labijie.infra.mqts.spring.startup.AckServerStartup import com.labijie.infra.mqts.spring.startup.AnnotationDiscoveryStartup import com.labijie.infra.mqts.spring.startup.RedoSupportedStartup import com.labijie.infra.mqts.spring.startup.TransactionRecoveryStartup import com.labijie.infra.spring.configuration.CommonsAutoConfiguration import com.labijie.infra.spring.configuration.NetworkConfig import org.springframework.beans.factory.config.BeanDefinition import org.springframework.boot.autoconfigure.AutoConfigureAfter import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Role @ConditionalOnMqts @AutoConfigureAfter(CommonsAutoConfiguration::class) @Configuration(proxyBeanMethods = false) class MqtsAutoConfiguration { @ConfigurationProperties("infra.mqts") @Bean fun mqTransactionConfig(): MQTransactionConfig{ return MQTransactionConfig() } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) @ConditionalOnMissingBean(IInstanceFactory::class) fun springInstanceFactory(): IInstanceFactory { return SpringInstanceFactory() } @Bean fun mqTransactionManager(config: MQTransactionConfig, idGenerator: IIdGenerator, dataSerializer: ITransactionDataSerializer, idempotence: IIdempotence, transactionAccessor: ITransactionHolder, instanceFactory: IInstanceFactory, queue: ITransactionQueue, repository: ITransactionRepository, networkConfig: NetworkConfig): MQTransactionManager { return MQTransactionManager(idempotence, repository, dataSerializer, idGenerator, config, instanceFactory, transactionAccessor, queue, networkConfig.getIPAddress()) } @Bean fun mqTransactionAspect(applicationContext: ApplicationContext): MQTransactionAspect { return MQTransactionAspect(applicationContext) } @Bean fun mqTransactionApplicationListener(mqTransactionManager: MQTransactionManager): MQTransactionApplicationListener { return MQTransactionApplicationListener(mqTransactionManager) } @Bean @ConditionalOnMissingBean(ITransactionDataSerializer::class) fun transactionDataSerializer(): ITransactionDataSerializer { return JacksonDataSerializer() } @Bean @ConditionalOnMissingBean(ITransactionHolder::class) fun transactionHolder(): ITransactionHolder { return DefaultTransactionHolder() } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) fun mqtsAnnotationProcessor(config: MQTransactionConfig): MqtsAnnotationProcessor { return MqtsAnnotationProcessor(config) } @Configuration(proxyBeanMethods = false) @AutoConfigureAfter(MqtsAutoConfiguration::class) protected class CoreStartupAutoConfiguration { @Bean fun annotationDiscoveryStartup(): AnnotationDiscoveryStartup { return AnnotationDiscoveryStartup() } @Bean fun transactionRecoveryStartup(): TransactionRecoveryStartup { return TransactionRecoveryStartup() } @Bean fun ackServerStartup(): AckServerStartup { return AckServerStartup() } @Bean fun redoSupportedStartup():RedoSupportedStartup{ return RedoSupportedStartup() } } }
0
Kotlin
0
1
40fe893cfc62ee2442851c2b4f81519ab6465129
4,620
infra-mqts
Apache License 2.0
app/src/main/java/online/z0lk1n/android/handnotes/ui/main/MainViewModel.kt
z0lk1n
172,971,912
false
null
package online.z0lk1n.android.handnotes.ui.main import android.support.annotation.VisibleForTesting import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch import online.z0lk1n.android.handnotes.data.NotesRepository import online.z0lk1n.android.handnotes.data.entity.Note import online.z0lk1n.android.handnotes.model.NoteResult import online.z0lk1n.android.handnotes.ui.base.BaseViewModel @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class MainViewModel(private val repository: NotesRepository) : BaseViewModel<List<Note>?>() { private val notesChannel = repository.getNotes() init { launch { notesChannel.consumeEach { when (it) { is NoteResult.Success<*> -> setData(it.data as? List<Note>) is NoteResult.Error -> setError(it.error) } } } } @VisibleForTesting public override fun onCleared() { notesChannel.cancel() super.onCleared() } }
0
Kotlin
0
0
f2fbfff9b61ab49cc91de455fcdcad28c68e13e1
1,128
HandNotes
Apache License 2.0
debugger/server/src/commonMain/kotlin/pro/respawn/flowmvi/debugger/server/navigation/destination/Destination.kt
respawn-app
477,143,989
false
{"Kotlin": 497111}
@file:UseSerializers(UUIDSerializer::class) package pro.respawn.flowmvi.debugger.server.navigation.destination import androidx.compose.runtime.Immutable import com.benasher44.uuid.Uuid import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import pro.respawn.flowmvi.debugger.serializers.UUIDSerializer @Serializable @Immutable sealed interface Destination { val topLevel: Boolean get() = false val singleTop: Boolean get() = topLevel infix fun detailsOf(other: Destination) = false @Serializable data object Timeline : Destination { override val topLevel: Boolean get() = true } @Serializable data object Connect : Destination { override val topLevel: Boolean get() = true } @Serializable data class StoreDetails(val storeId: Uuid) : Destination }
10
Kotlin
10
305
80ea0a5eedc948fe50d3f23ddce041d8144f0f23
846
FlowMVI
Apache License 2.0
app/src/main/java/com/obregon/registroventadeproducto/ProductosDao.kt
Excy1994
320,397,666
false
null
package com.obregon.registroventadeproducto import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query @Dao interface ProductosDao { @Insert fun Insert(producto: Productos) @get:Query("SELECT * FROM productos") val allProductoss: LiveData<List<Productos>> }
0
Kotlin
0
0
9a02ab95be1b3ae0ac95f2437a9082e4e09330bc
334
Aplicaci-n_Proyecto-Final_Matilda-y-Excy
Apache License 2.0
function/src/main/kotlin/dev/goobar/HttpRequestExtensions.kt
goobar-dev
763,820,898
false
{"Kotlin": 9172, "Makefile": 596}
package dev.goobar import com.google.cloud.functions.HttpRequest import dev.goobar.logging.Logger import dev.goobar.logging.buildTraceAttribute import dev.goobar.tracing.ProjectId import dev.goobar.tracing.TraceId import dev.goobar.tracing.getTraceId import kotlin.jvm.optionals.getOrNull fun HttpRequest.getLogger(name: String): Logger = HttpRequestLogger(name, this) /** * Attempts to parse a Google Cloud trace identifier in the format of projects/<gcp project id>/traces/<trace id> ex: * projects/dev/traces/bde90770a9af03d682d893e33004844d */ internal val HttpRequest?.cloudTraceId: TraceId? get() = when (this) { null -> null else -> { getFirstHeader("x-cloud-trace-context").getOrNull().getTraceId() } } internal fun HttpRequest.buildTraceAttribute(projectId: ProjectId = ProjectId()): Pair<String, String>? = cloudTraceId.buildTraceAttribute()
0
Kotlin
0
1
06557475965fd8e047a8f0b58d456f71be62f661
935
template-kotlin-cloud-function
Apache License 2.0
src/main/kotlin/org/move/ide/intentions/RemoveCurlyBracesIntention.kt
pontem-network
279,299,159
false
{"Kotlin": 2191000, "Move": 39421, "Lex": 5509, "HTML": 2114, "Java": 1275}
package org.move.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.move.lang.core.psi.MvUseSpeck import org.move.lang.core.psi.MvUseStmt import org.move.lang.core.psi.ext.ancestorStrict import org.move.lang.core.psi.ext.endOffset import org.move.lang.core.psi.ext.startOffset import org.move.lang.core.psi.psiFactory class RemoveCurlyBracesIntention: MvElementBaseIntentionAction<RemoveCurlyBracesIntention.Context>() { override fun getText(): String = "Remove curly braces" override fun getFamilyName(): String = text data class Context(val useSpeck: MvUseSpeck) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val useStmt = element.ancestorStrict<MvUseStmt>() ?: return null val useSpeck = useStmt.useSpeck ?: return null val useGroup = useSpeck.useGroup ?: return null if (useGroup.useSpeckList.size > 1) return null return Context(useSpeck) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val useSpeck = ctx.useSpeck // Save the cursor position, adjusting for curly brace removal val caret = editor.caretModel.offset val newOffset = when { caret < useSpeck.startOffset -> caret caret < useSpeck.endOffset -> caret - 1 else -> caret - 2 } useSpeck.removeCurlyBraces() editor.caretModel.moveToOffset(newOffset) } } private fun MvUseSpeck.removeCurlyBraces() { val psiFactory = this.project.psiFactory val useGroup = this.useGroup ?: return val itemUseSpeck = useGroup.useSpeckList.singleOrNull() ?: return val newPath = psiFactory.path("0x1::dummy::call") val itemIdentifier = itemUseSpeck.path.identifier ?: return // copy identifier newPath.identifier?.replace(itemIdentifier.copy()) // copy module path newPath.path?.replace(this.path.copy()) val dummyUseSpeck = psiFactory.useSpeck("0x1::dummy::call as mycall") dummyUseSpeck.path.replace(newPath) val useAlias = itemUseSpeck.useAlias if (useAlias != null) { dummyUseSpeck.useAlias?.replace(useAlias) } else { dummyUseSpeck.useAlias?.delete() } // val aliasName = itemUseSpeck.useAlias?.name // // var newText = refName // if (aliasName != null) { // newText += " as $aliasName" // } // val newItemUse = psiFactory.useSpeckForGroup(newText) this.replace(dummyUseSpeck) }
3
Kotlin
29
69
d090ecd542bb16f414cc1cf2dcbe096ca37536af
2,577
intellij-move
MIT License
Mushrooms/app/src/main/java/com/example/ntabu/mushrooms/ResultsActivity.kt
moevm
170,087,470
false
null
package com.example.ntabu.mushrooms import android.content.Intent import android.os.Bundle import kotlinx.android.synthetic.main.activity_results.* class ResultsActivity : MushroomsActivityBase() { private var dbHelper : DBHelper? = null private var details : MushroomDetails? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_results) setupActionBar() result1.setOnClickListener { val intent = Intent(this, DetailsActivity::class.java) if (details != null) intent.putExtra("details", details) startActivity(intent) } dbHelper = DBHelper(applicationContext) details = selectData() if (details != null) { result1.text = details!!.name if (details!!.pictureId == 2) result1.setBackgroundResource(R.drawable.fli_killer) else result1.setBackgroundResource(R.drawable.belyiy_grib_elovyiy) } } override fun onDestroy() { dbHelper?.close() super.onDestroy() } private fun selectData() : MushroomDetails? { var result : MushroomDetails? = null if (dbHelper != null) { val criteria = intent.extras.getParcelable<MushroomCriteria>("criteria")!! val db = dbHelper!!.writableDatabase var c = db.rawQuery( "SELECT * FROM mushrooms WHERE hat_color='${criteria.topColor}' AND hat_bottom='${criteria.roundKind}'", null ) if (c != null) { if (c.moveToFirst()) { val nameIndex = c.getColumnIndex("name") val descriptionIndex = c.getColumnIndex("description") val pictureIdIndex = c.getColumnIndex("picture_id") result = MushroomDetails(c.getString(nameIndex), c.getString(descriptionIndex), c.getInt(pictureIdIndex)) } c.close() } } return result } }
0
Kotlin
0
0
4a6fcecd1c44030213bfe2fa340db93b41297fdd
2,123
adfmp19-mushrooms
MIT License
app/src/main/java/com/kot/faro/myapplication/animaisportugues/PortuguesBearActivity.kt
andersonFaro9
78,895,223
false
null
package com.kot.faro.myapplication import Interfacesforportugues.ButtonsForAnimais import Interfacesforportugues.Players import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ImageButton import android.widget.Toast import com.kot.faro.myapplication.animaismath.MathTwoBearActivity import com.kot.faro.myapplication.fruitsmath.MathOrangeFourActivity import kotlinx.android.synthetic.main.activity_urso.* class PortuguesBearActivity : AppCompatActivity() , ButtonsForAnimais, Players { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_urso) getSupportActionBar()?.setDisplayHomeAsUpEnabled(true) goNumberOne() goNumberTwo() goNumberTree() } override fun goNumberTwo( ) { abc_aprender_number_2.setOnClickListener({ v -> v.setBackgroundResource(R.drawable.ic_check) toGetKeyForNumberOk() Toast.makeText(this, "parabéns, você acertou! ", Toast.LENGTH_SHORT).show() val buttonAvancar = findViewById(R.id.abc_botao_portugues_animais) as ImageButton buttonAvancar.visibility = View.VISIBLE buttonAvancar.setOnClickListener({ val intent = Intent(this, ZebraActivity::class.java) startActivity(intent) Toast.makeText(this, "parabéns, você acertou! ", Toast.LENGTH_SHORT).show() }) }) } override fun toGetKeyForNumberOk() { val prefs = getSharedPreferences("preferencias", Context.MODE_PRIVATE) val keys = prefs.getBoolean("chave", true) if(keys){ playSoundInButton() } } override fun toGetKeyForNumberError() { val prefs = getSharedPreferences("preferencias", Context.MODE_PRIVATE) val keys = prefs.getBoolean("chave", true) if(keys){ playSoundError() } } override fun goNumberOne() { abc_aprender_number_1.setOnClickListener({ toGetKeyForNumberError() }) } override fun goNumberTree() { abc_aprender_number_3.setOnClickListener({ toGetKeyForNumberError() }) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem) : Boolean { when (item.itemId) { R.id.letras_frutas -> { val intent = Intent(this@PortuguesBearActivity, GrapeActivity::class.java) startActivity(intent) return true } R.id.menu_inicial -> { val intent = Intent(this@PortuguesBearActivity, MenuActivity::class.java) startActivity (intent) return true } R.id.sobre -> { val intent = Intent(this@PortuguesBearActivity, SobreActivity::class.java) startActivity(intent) return true } R.id.letras_animais -> { val intent = Intent(this@PortuguesBearActivity, PortuguesBearActivity::class.java) startActivity(intent) return true } R.id.matematica_animais -> { val intent = Intent(this@PortuguesBearActivity, MathTwoBearActivity::class.java) startActivity(intent) return true } R.id.matematica_frutas -> { val intent = Intent(this@PortuguesBearActivity, MathOrangeFourActivity::class.java) startActivity(intent) return true } else -> return super.onOptionsItemSelected(item) } } }
1
Kotlin
0
14
c08f499c8435d651c5ca336b89d191e8e7aa3be0
4,048
AppAbcAprender
Apache License 2.0
src/main/kotlin/ch/compile/blitzremote/actions/ManageSSHTunnelsAction.kt
KeeTraxx
146,708,971
false
null
package ch.compile.blitzremote.actions import ch.compile.blitzremote.components.BlitzTerminal import ch.compile.blitzremote.components.SshTunnelEditor import java.awt.event.ActionEvent import javax.swing.AbstractAction class ManageSSHTunnelsAction(val blitzTerminal: BlitzTerminal) : AbstractAction("Manage SSH tunnels...") { override fun actionPerformed(e: ActionEvent?) { SshTunnelEditor(blitzTerminal).isVisible = true } }
0
Kotlin
0
2
36f6a1ea49fab225b392aab35f7c7d7d2353ac58
445
blitz-remote
MIT License
src/main/kotlin/com/github/carrot372/namlanforminecraft/item/ModMenu.kt
carrot372
491,486,114
false
null
/* * Copyright (c) 2022. carrot * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.carrot372.namlanforminecraft.item import com.github.carrot372.namlanforminecraft.MOD_ID import com.github.carrot372.namlanforminecraft.item.custom.DevTool import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder import net.minecraft.item.ItemGroup import net.minecraft.item.ItemStack import net.minecraft.util.Identifier object ModMenu { var NAMLANGROUP: ItemGroup = FabricItemGroupBuilder.build( Identifier(MOD_ID,"namlan") ) { ItemStack(DevTool.DEVTOOL) } }
0
Kotlin
0
0
4095c211d625c5639ffb43d024ee14b3161de3e3
1,103
Namlan-for-Minecraft
Apache License 2.0
src/main/kotlin/no/nav/syfo/client/SyfosmregisterStatusClient.kt
navikt
238,714,111
false
null
package no.nav.syfo.client import io.ktor.client.HttpClient import io.ktor.client.features.ClientRequestException import io.ktor.client.request.accept import io.ktor.client.request.get import io.ktor.client.request.headers import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import no.nav.syfo.log import no.nav.syfo.sykmeldingstatus.api.v1.SykmeldingStatusEventDTO class SyfosmregisterStatusClient(private val endpointUrl: String, private val httpClient: HttpClient) { suspend fun hentSykmeldingstatus(sykmeldingId: String, token: String): SykmeldingStatusEventDTO { try { val statusliste = httpClient.get<List<SykmeldingStatusEventDTO>>("$endpointUrl/sykmeldinger/$sykmeldingId/status?filter=LATEST") { accept(ContentType.Application.Json) headers { append("Authorization", token) append("Nav-CallId", sykmeldingId) } } log.info("Hentet status for sykmeldingId {}", sykmeldingId) return statusliste.first() } catch (e: Exception) { if (e is ClientRequestException && e.response.status == HttpStatusCode.Forbidden) { log.warn("Bruker har ikke tilgang til sykmelding med id $sykmeldingId") throw RuntimeException("Sykmeldingsregister svarte med feilmelding for $sykmeldingId") } else { log.error("Noe gikk galt ved sjekking av status eller tilgang for sykmeldingId {}", sykmeldingId) throw RuntimeException("Sykmeldingsregister svarte med feilmelding for $sykmeldingId") } } } }
0
Kotlin
0
0
76b5aa68d376b85cef31905bdffe41dd2e387c0d
1,665
sykmeldinger-backend
MIT License
main/src/main/kotlin/us/wedemy/eggeum/android/main/viewmodel/SettingViewModel.kt
Wedemy
615,061,021
false
{"Kotlin": 223534}
/* * Designed and developed by Wedemy 2023. * * Licensed under the MIT. * Please see full license: https://github.com/Wedemy/eggeum-android/blob/main/LICENSE */ package us.wedemy.eggeum.android.main.viewmodel import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class SettingViewModel @Inject constructor() : ViewModel()
13
Kotlin
0
7
5354e08dcb5ed5a0eb987cf159686ea4871637c9
405
eggeum-android
MIT License
src/main/kotlin/io/mustelidae/otter/neotropical/api/domain/payment/PayWayHandler.kt
otter-world
449,306,132
false
null
package io.mustelidae.otter.neotropical.api.domain.payment import io.mustelidae.otter.neotropical.api.domain.payment.client.billing.BillingPayClient import io.mustelidae.otter.neotropical.api.domain.payment.method.Voucher import io.mustelidae.otter.neotropical.api.domain.payment.voucher.client.VoucherClient import org.springframework.stereotype.Service @Service class PayWayHandler( private val voucherClient: VoucherClient, private val billingPayClient: BillingPayClient ) { fun getPayWayOfPrePayBook(userId: Long, amountOfPay: Long, voucher: Voucher?): PayWay { if (voucher != null) return VoucherPayWay(userId, amountOfPay, voucherClient, voucher) if (amountOfPay == 0L) return FreePayWay(userId, amountOfPay) return BillingPrePayWay(userId, amountOfPay, billingPayClient) } fun getPayWayOfPostPayBook(userId: Long, amountOfPay: Long, voucher: Voucher?): PayWay { if (voucher != null) return VoucherPayWay(userId, amountOfPay, voucherClient, voucher) if (amountOfPay == 0L) return FreePayWay(userId, amountOfPay) return BillingPostPayWay(userId, amountOfPay, billingPayClient) } fun getPayWayOfPostPayBook(payment: Payment, amountOfPay: Long? = null, voucher: Voucher?): PayWay { if (voucher != null) return VoucherPayWay(payment, voucherClient, voucher) val amount = amountOfPay ?: payment.priceOfOrder if (amount == 0L) return FreePayWay(payment) return BillingPostPayWay(payment, billingPayClient) } fun getPayWay(payment: Payment): PayWay { return when (payment.payType) { PayWay.Type.POST_PAY -> BillingPostPayWay(payment, billingPayClient) PayWay.Type.PRE_PAY -> BillingPrePayWay(payment, billingPayClient) PayWay.Type.FREE -> FreePayWay(payment) PayWay.Type.VOUCHER -> VoucherPayWay(payment, voucherClient) } } }
0
Kotlin
0
0
01cd8ce9277d532ab2e50c24e749607da8c3854c
1,992
neotropical-otter
MIT License
modules/hir/src/main/kotlin/org/acornlang/hir/HirVisitor.kt
mworzala
506,414,489
false
null
package org.acornlang.hir interface HirVisitor<P, R> { val default: R fun visit(node: HirNode?, p: P): R = node?.accept(this, p) ?: default // SECTION: Module // =============== fun visitModule(module: HirModule, p: P): R { for (decl in module.decls) visit(decl, p) return default } // SECTION: Declaration // ==================== fun visitConstDecl(constDecl: HirConstDecl, p: P): R { visit(constDecl.type, p) visit(constDecl.init, p) return default } // SECTION: Statement // ================== fun visitExprStmt(exprStmt: HirExprStmt, p: P): R { return visit(exprStmt.expr, p) } fun visitVarDecl(varDecl: HirVarDecl, p: P): R { visit(varDecl.type, p) visit(varDecl.init, p) return default } fun visitReturn(returnStmt: HirReturn, p: P): R { visit(returnStmt.expr, p) return default } fun visitBreak(breakStmt: HirBreak, p: P): R { return default } fun visitContinue(continueStmt: HirContinue, p: P): R { return default } // SECTION: Expression // =================== fun visitIntLiteral(intLiteral: HirIntLiteral, p: P): R { return default } fun visitBoolLiteral(boolLiteral: HirBoolLiteral, p: P): R { return default } fun visitStringLiteral(stringLiteral: HirStringLiteral, p: P): R { return default } fun visitVarRef(varRef: HirVarRef, p: P): R { return default } fun visitIntrinsicRef(intrinsicRef: HirIntrinsicRef, p: P): R { return default } fun visitReference(reference: HirReference, p: P): R { visit(reference.expr, p) return default } fun visitBinary(binary: HirBinary, p: P): R { visit(binary.lhs, p) visit(binary.rhs, p) return default } fun visitUnary(unary: HirUnary, p: P): R { visit(unary.operand, p) return default } fun visitTypeUnion(typeUnion: HirTypeUnion, p: P): R { visit(typeUnion.lhs, p) visit(typeUnion.rhs, p) return default } fun visitAssign(assign: HirAssign, p: P): R { visit(assign.target, p) visit(assign.value, p) return default } fun visitMemberAccess(memberAccess: HirMemberAccess, p: P): R { visit(memberAccess.target, p) return default } fun visitIndex(index: HirIndex, p: P): R { visit(index.target, p) visit(index.value, p) return default } fun visitArrayLiteral(arrayLiteral: HirArrayLiteral, p: P): R { for (expr in arrayLiteral.values) visit(expr, p) return default } fun visitTupleLiteral(tupleLiteral: HirTupleLiteral, p: P): R { for (expr in tupleLiteral.values) visit(expr, p) return default } fun visitBlock(block: HirBlock, p: P): R { for (stmt in block.stmts) visit(stmt, p) return default } fun visitImplicitReturn(implicitReturn: HirImplicitReturn, p: P): R { visit(implicitReturn.expr, p) return default } fun visitConstruct(construct: HirConstruct, p: P): R { visit(construct.target, p) for (arg in construct.args) visit(arg, p) return default } fun visitConstructArg(constructArg: HirConstructArg, p: P): R { visit(constructArg.value, p) return default } fun visitCall(call: HirCall, p: P): R { visit(call.target, p) for (arg in call.args) visit(arg, p) return default } fun visitIf(ifStmt: HirIf, p: P): R { visit(ifStmt.cond, p) visit(ifStmt.thenBranch, p) visit(ifStmt.elseBranch, p) return default } fun visitWhile(whileStmt: HirWhile, p: P): R { visit(whileStmt.cond, p) visit(whileStmt.body, p) return default } fun visitFnDecl(fnDecl: HirFnDecl, p: P): R { for (param in fnDecl.params) visit(param, p) visit(fnDecl.returnType, p) visit(fnDecl.body, p) return default } fun visitFnType(fnType: HirFnType, p: P): R { for (param in fnType.params) visit(param, p) visit(fnType.returnType, p) return default } fun visitFnParam(fnParam: HirFnParam, p: P): R { visit(fnParam.type, p) return default } fun visitEnumDecl(enumDecl: HirEnumDecl, p: P): R { for (case in enumDecl.cases) visit(case, p) return default } fun visitEnumCase(enumCase: HirEnumCase, p: P): R { return default } fun visitStructDecl(structDecl: HirStructDecl, p: P): R { for (field in structDecl.fields) visit(field, p) for (decl in structDecl.decls) visit(decl, p) return default } fun visitStructField(structField: HirStructField, p: P): R { visit(structField.type, p) return default } fun visitUnionDecl(unionDecl: HirUnionDecl, p: P): R { for (field in unionDecl.members) visit(field, p) for (decl in unionDecl.decls) visit(decl, p) return default } fun visitUnionMember(unionMember: HirUnionMember, p: P): R { visit(unionMember.type, p) return default } fun visitSpecDecl(specDecl: HirSpecDecl, p: P): R { for (decl in specDecl.members) visit(decl, p) return default } }
1
Kotlin
0
0
f1b2565aa7c3f0d17f516ce594f96c3eb27a7407
5,607
acorn-interpreter
Apache License 2.0
app/src/main/java/com/zaki/mvvm_base/apis/Apis.kt
iammohdzaki
245,803,859
false
null
package com.zaki.mvvm_base.apis /** * Developer : <NAME> * Created On : 08-03-2020 */ interface Apis { }
0
Kotlin
0
0
67ffc7f5f785ae98f2396c3d98576174c84b2c22
109
MVVM-Base
MIT License
app/src/main/java/com/zaki/mvvm_base/apis/Apis.kt
iammohdzaki
245,803,859
false
null
package com.zaki.mvvm_base.apis /** * Developer : <NAME> * Created On : 08-03-2020 */ interface Apis { }
0
Kotlin
0
0
67ffc7f5f785ae98f2396c3d98576174c84b2c22
109
MVVM-Base
MIT License
src/main/kotlin/br/com/jiratorio/repository/ImpedimentHistoryRepository.kt
andrelugomes
230,294,644
true
{"Kotlin": 541514, "PLSQL": 366, "Dockerfile": 315, "TSQL": 269}
package br.com.jiratorio.repository import br.com.jiratorio.domain.entity.ImpedimentHistory import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface ImpedimentHistoryRepository : CrudRepository<ImpedimentHistory, Long>
0
null
0
1
168de10e5e53f31734937816811ac9dae6940202
293
jirareport
MIT License
compiler/testData/codegen/box/valueClasses/kt62455.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// WITH_STDLIB // LANGUAGE: +ValueClasses // TARGET_BACKEND: JVM_IR // MODULE: lib // FILE: Sentence.kt @JvmInline value class Sentence(private val wholeText: String, internal val basis: Set<String>, public val x: Int, protected val y: Long) { fun op() = Sentence(wholeText, basis, -x, -y) } @JvmInline value class NestedSentence( private val sentence1: Sentence, internal val sentence2: Sentence, public val sentence3: Sentence, protected val sentence4: Sentence ) { fun op() = NestedSentence(sentence1.op(), sentence2.op(), sentence3.op(), sentence4.op()) } @JvmInline value class NestedNestedSentence( private val sentence1: NestedSentence, internal val sentence2: NestedSentence, public val sentence3: NestedSentence, protected val sentence4: NestedSentence ) data class MutableSentence( private var sentence1: NestedSentence, internal var sentence2: NestedSentence, public var sentence3: NestedSentence, protected var sentence4: NestedSentence ) // MODULE: main(lib) // FILE: main.kt fun box(): String { val sentence = Sentence("file", setOf("package"), 2, 3L) if (sentence.toString() != "Sentence(wholeText=file, basis=[package], x=2, y=3)") { return sentence.toString() } if (sentence.x != 2) return sentence.x.toString() val nestedSentence = NestedSentence(sentence, sentence, sentence, sentence) if (nestedSentence.toString() != "NestedSentence(sentence1=$sentence, sentence2=$sentence, sentence3=$sentence, sentence4=$sentence)") { return nestedSentence.toString() } if (nestedSentence.sentence3 != sentence) return nestedSentence.sentence3.toString() if (nestedSentence.sentence3.x != sentence.x) return nestedSentence.sentence3.x.toString() val nestedNestedSentence = NestedNestedSentence(nestedSentence, nestedSentence, nestedSentence, nestedSentence) if (nestedNestedSentence.toString() != "NestedNestedSentence(sentence1=$nestedSentence, sentence2=$nestedSentence, sentence3=$nestedSentence, sentence4=$nestedSentence)") { return nestedNestedSentence.toString() } if (nestedNestedSentence.sentence3 != nestedSentence) return nestedNestedSentence.sentence3.toString() if (nestedNestedSentence.sentence3.sentence3 != sentence) return nestedNestedSentence.sentence3.sentence3.toString() if (nestedNestedSentence.sentence3.sentence3.x != sentence.x) return nestedNestedSentence.sentence3.sentence3.x.toString() val mutable = MutableSentence(nestedSentence, nestedSentence, nestedSentence, nestedSentence) if (mutable.toString() != "MutableSentence(sentence1=$nestedSentence, sentence2=$nestedSentence, sentence3=$nestedSentence, sentence4=$nestedSentence)") { return mutable.toString() } if (mutable.sentence3 != nestedSentence) return mutable.sentence3.toString() if (mutable.sentence3.sentence3 != sentence) return mutable.sentence3.sentence3.toString() if (mutable.sentence3.sentence3.x != sentence.x) return mutable.sentence3.sentence3.x.toString() mutable.sentence3 = mutable.sentence3.op() if (mutable == MutableSentence(nestedSentence, nestedSentence, nestedSentence, nestedSentence)) return mutable.toString() if (mutable.toString() == "MutableSentence(sentence1=$nestedSentence, sentence2=$nestedSentence, sentence3=$nestedSentence, sentence4=$nestedSentence)") { return mutable.toString() } if (mutable.sentence3 == nestedSentence) return mutable.sentence3.toString() if (mutable.sentence3.sentence3 == sentence) return mutable.sentence3.sentence3.toString() if (mutable.sentence3.sentence3.x == sentence.x) return mutable.sentence3.sentence3.x.toString() if (mutable.toString().replace("-", "") != "MutableSentence(sentence1=$nestedSentence, sentence2=$nestedSentence, sentence3=$nestedSentence, sentence4=$nestedSentence)") { return mutable.toString() } if (mutable.sentence3 != nestedSentence.op()) return mutable.sentence3.toString() if (mutable.sentence3.sentence3 != sentence.op()) return mutable.sentence3.sentence3.toString() if (mutable.sentence3.sentence3.x != -sentence.x) return mutable.sentence3.sentence3.x.toString() return "OK" }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
4,212
kotlin
Apache License 2.0
src/jvmMain/kotlin/team/mke/utils/bg/BaseBackgroundProcess.kt
MKE-overseas
825,773,910
false
{"Kotlin": 79901}
package team.mke.utils.bg import kotlinx.coroutines.* import org.slf4j.Logger import org.slf4j.LoggerFactory import ru.raysmith.utils.uuid import team.mke.utils.crashinterceptor.CrashInterceptor import team.mke.utils.logging.LoggableCoroutineName /** * Базовая обертка для фонового процесса * * @param name Имя процесса * @param id уникальный идентификатор * */ abstract class BaseBackgroundProcess( final override val name: String, val crashInterceptor: CrashInterceptor<*>, override val logger: Logger = LoggerFactory.getLogger("bg"), override val id: String = uuid(), val autoStarted: Boolean = true ) : BackgroundProcess { protected var job: Job? = null override val isActive get() = job?.isActive == true protected open var isReadyToRestart = !autoStarted protected var restartOnFinish = false var iterations = 0 protected set abstract val mutex: Any val coroutineName = LoggableCoroutineName(name, threadName = "bg") val handler = CoroutineExceptionHandler { _, throwable -> crashInterceptor.intercept( throwable, logger, "Error in background process '$name' [$id]. Process stopped." ) Background.removeProcess(id) } suspend fun join() { job?.join() } override fun cancel(cause: CancellationException?) { job?.cancel(cause) } suspend fun cancelAndJoin() { job?.cancelAndJoin() } fun start() = start(true) override fun start(throwOnRegistered: Boolean) { Background.registered(this, throwOnRegistered) synchronized(mutex) { isReadyToRestart = false } logger.debug("Background process '$name' [$id] started...") job = Background.scope.launch(handler + coroutineName) { try { run() logger.debug("Background process '$name' [$id] completed") } catch (e: Exception) { crashInterceptor.intercept(e, logger, "Не удалось запустить фоновый процесс '$name' [$id]") } finally { synchronized(mutex) { if (restartOnFinish) { restart() } else { isReadyToRestart = true } } if (iterations == 0) iterations++ } } } override fun restart() = synchronized(mutex) { if (isReadyToRestart) { isReadyToRestart = false restartOnFinish = false super.restart() return@synchronized true } else { restartOnFinish = true return@synchronized false } } }
0
Kotlin
0
0
cc6186361576ac18428150cfcc2565ffe4e25746
2,733
mke-utils
Apache License 2.0