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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zoomimage-core/src/jsCommonTest/kotlin/com/github/panpf/zoomimage/core/jscommon/test/util/CoroutinesJsCommonTest.kt
|
panpf
| 647,222,866 | false |
{"Kotlin": 2667251, "Shell": 650}
|
package com.github.panpf.zoomimage.core.jscommon.test.util
import kotlin.test.Test
class CoroutinesJsCommonTest {
@Test
fun testIoCoroutineDispatcher() {
// TODO test
}
}
| 3 |
Kotlin
|
10
| 216 |
3dad6e01c7f92248ef3cf1f969620b89c497211c
| 193 |
zoomimage
|
Apache License 2.0
|
ModuleDroid/src/main/java/software/galaniberico/moduledroid/facade/Facade.kt
|
agp221-ua
| 753,141,684 | false |
{"Kotlin": 92557}
|
package software.galaniberico.moduledroid.facade
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import software.galaniberico.moduledroid.subcomponents.intentmanager.LocalIntentManager
import software.galaniberico.moduledroid.subcomponents.preferencesmanager.PreferencesManager
object Facade {
// ### ACTIVITY LIFECYCLE ###
fun getCurrentActivity(): Activity? {
return FacadeActivityLifecycle.getCurrentActivity()
}
fun getCurrentActivityOrFail(): Activity {
return FacadeActivityLifecycle.getCurrentActivityOrFail()
}
fun getPreferredActivity(): Activity? {
return FacadeActivityLifecycle.getPreferredActivity()
}
fun getPreferredActivityOrFail(): Activity {
return FacadeActivityLifecycle.getPreferredActivityOrFail()
}
fun getCreatingActivity(): Activity? {
return FacadeActivityLifecycle.getCreatingActivity()
}
fun getCreatingActivityOrFail(): Activity {
return FacadeActivityLifecycle.getCreatingActivityOrFail()
}
fun getStartingActivity(): Activity? {
return FacadeActivityLifecycle.getStartingActivity()
}
fun getStartingActivityOrFail(): Activity {
return FacadeActivityLifecycle.getStartingActivityOrFail()
}
fun getResumingActivity(): Activity? {
return FacadeActivityLifecycle.getResumingActivity()
}
fun getResumingActivityOrFail(): Activity {
return FacadeActivityLifecycle.getResumingActivityOrFail()
}
fun addOnRestartSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnRestartSubscription(subscription)
}
fun addOnPreCreateSubscription(subscription: (Activity, Bundle?) -> Unit) {
FacadeActivityLifecycle.addOnPreCreateSubscription(subscription)
}
fun addOnPreStartSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPreStartSubscription(subscription)
}
fun addOnPreResumeSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPreResumeSubscription(subscription)
}
fun addOnPrePauseSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPrePauseSubscription(subscription)
}
fun addOnPreStopSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPreStopSubscription(subscription)
}
fun addOnPreDestroySubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPreDestroySubscription(subscription)
}
fun addOnPostCreateSubscription(subscription: (Activity, Bundle?) -> Unit) {
FacadeActivityLifecycle.addOnPostCreateSubscription(subscription)
}
fun addOnPostStartSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostStartSubscription(subscription)
}
fun addOnPostResumeSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostResumeSubscription(subscription)
}
fun addOnPostPauseSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostPauseSubscription(subscription)
}
fun addOnPostStopSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostStopSubscription(subscription)
}
fun addOnPostDestroySubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostDestroySubscription(subscription)
}
fun addOnCreateSubscription(subscription: (Activity, Bundle?) -> Unit) {
FacadeActivityLifecycle.addOnCreateSubscription(subscription)
}
fun addOnStartSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnStartSubscription(subscription)
}
fun addOnResumeSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnResumeSubscription(subscription)
}
fun addOnPauseSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPauseSubscription(subscription)
}
fun addOnStopSubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnStopSubscription(subscription)
}
fun addOnDestroySubscription(subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnDestroySubscription(subscription)
}
fun addOnSaveInstanceStateSubscription(subscription: (Activity, Bundle) -> Unit) {
FacadeActivityLifecycle.addOnSaveInstanceStateSubscription(subscription)
}
fun addOnRestartSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnRestartSubscription(id, subscription)
}
fun addOnCreateSubscription(id: String, subscription: (Activity, Bundle?) -> Unit) {
FacadeActivityLifecycle.addOnCreateSubscription(id, subscription)
}
fun addOnStartSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnStartSubscription(id, subscription)
}
fun addOnResumeSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnResumeSubscription(id, subscription)
}
fun addOnPauseSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPauseSubscription(id, subscription)
}
fun addOnStopSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnStopSubscription(id, subscription)
}
fun addOnDestroySubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnDestroySubscription(id, subscription)
}
fun addOnPreCreateSubscription(id: String, subscription: (Activity, Bundle?) -> Unit) {
FacadeActivityLifecycle.addOnPreCreateSubscription(id, subscription)
}
fun addOnPreStartSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPreStartSubscription(id, subscription)
}
fun addOnPreResumeSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPreResumeSubscription(id, subscription)
}
fun addOnPrePauseSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPrePauseSubscription(id, subscription)
}
fun addOnPreStopSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPreStopSubscription(id, subscription)
}
fun addOnPreDestroySubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPreDestroySubscription(id, subscription)
}
fun addOnPostCreateSubscription(id: String, subscription: (Activity, Bundle?) -> Unit) {
FacadeActivityLifecycle.addOnPostCreateSubscription(id, subscription)
}
fun addOnPostStartSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostStartSubscription(id, subscription)
}
fun addOnPostResumeSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostResumeSubscription(id, subscription)
}
fun addOnPostPauseSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostPauseSubscription(id, subscription)
}
fun addOnPostStopSubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostStopSubscription(id, subscription)
}
fun addOnPostDestroySubscription(id: String, subscription: (Activity) -> Unit) {
FacadeActivityLifecycle.addOnPostDestroySubscription(id, subscription)
}
fun addOnSaveInstanceStateSubscription(id: String, subscription: (Activity, Bundle) -> Unit) {
FacadeActivityLifecycle.addOnSaveInstanceStateSubscription(id, subscription)
}
fun addOnRestartSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnRestartSubscription(activityClass, subscription)
}
fun addOnCreateSubscription(
activityClass: Class<out Activity>,
subscription: (Activity, Bundle?) -> Unit
) {
FacadeActivityLifecycle.addOnCreateSubscription(activityClass, subscription)
}
fun addOnStartSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnStartSubscription(activityClass, subscription)
}
fun addOnResumeSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnResumeSubscription(activityClass, subscription)
}
fun addOnPauseSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPauseSubscription(activityClass, subscription)
}
fun addOnStopSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnStopSubscription(activityClass, subscription)
}
fun addOnDestroySubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnDestroySubscription(activityClass, subscription)
}
fun addOnPreCreateSubscription(
activityClass: Class<out Activity>,
subscription: (Activity, Bundle?) -> Unit
) {
FacadeActivityLifecycle.addOnPreCreateSubscription(activityClass, subscription)
}
fun addOnPreStartSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPreStartSubscription(activityClass, subscription)
}
fun addOnPreResumeSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPreResumeSubscription(activityClass, subscription)
}
fun addOnPrePauseSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPrePauseSubscription(activityClass, subscription)
}
fun addOnPreStopSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPreStopSubscription(activityClass, subscription)
}
fun addOnPreDestroySubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPreDestroySubscription(activityClass, subscription)
}
fun addOnPostCreateSubscription(
activityClass: Class<out Activity>,
subscription: (Activity, Bundle?) -> Unit
) {
FacadeActivityLifecycle.addOnPostCreateSubscription(activityClass, subscription)
}
fun addOnPostStartSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostStartSubscription(activityClass, subscription)
}
fun addOnPostResumeSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostResumeSubscription(activityClass, subscription)
}
fun addOnPostPauseSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostPauseSubscription(activityClass, subscription)
}
fun addOnPostStopSubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostStopSubscription(activityClass, subscription)
}
fun addOnPostDestroySubscription(
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostDestroySubscription(activityClass, subscription)
}
fun addOnSaveInstanceStateSubscription(
activityClass: Class<out Activity>,
subscription: (Activity, Bundle) -> Unit
) {
FacadeActivityLifecycle.addOnSaveInstanceStateSubscription(activityClass, subscription)
}
fun addOnRestartSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnRestartSubscription(id, activityClass, subscription)
}
fun addOnCreateSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity, Bundle?) -> Unit
) {
FacadeActivityLifecycle.addOnCreateSubscription(id, activityClass, subscription)
}
fun addOnStartSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnStartSubscription(id, activityClass, subscription)
}
fun addOnResumeSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnResumeSubscription(id, activityClass, subscription)
}
fun addOnPauseSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPauseSubscription(id, activityClass, subscription)
}
fun addOnStopSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnStopSubscription(id, activityClass, subscription)
}
fun addOnDestroySubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnDestroySubscription(id, activityClass, subscription)
}
fun addOnPreCreateSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity, Bundle?) -> Unit
) {
FacadeActivityLifecycle.addOnPreCreateSubscription(id, activityClass, subscription)
}
fun addOnPreStartSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPreStartSubscription(id, activityClass, subscription)
}
fun addOnPreResumeSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPreResumeSubscription(id, activityClass, subscription)
}
fun addOnPrePauseSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPrePauseSubscription(id, activityClass, subscription)
}
fun addOnPreStopSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPreStopSubscription(id, activityClass, subscription)
}
fun addOnPreDestroySubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPreDestroySubscription(id, activityClass, subscription)
}
fun addOnPostCreateSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity, Bundle?) -> Unit
) {
FacadeActivityLifecycle.addOnPostCreateSubscription(id, activityClass, subscription)
}
fun addOnPostStartSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostStartSubscription(id, activityClass, subscription)
}
fun addOnPostResumeSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostResumeSubscription(id, activityClass, subscription)
}
fun addOnPostPauseSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostPauseSubscription(id, activityClass, subscription)
}
fun addOnPostStopSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostStopSubscription(id, activityClass, subscription)
}
fun addOnPostDestroySubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity) -> Unit
) {
FacadeActivityLifecycle.addOnPostDestroySubscription(id, activityClass, subscription)
}
fun addOnSaveInstanceStateSubscription(
id: String,
activityClass: Class<out Activity>,
subscription: (Activity, Bundle) -> Unit
) {
FacadeActivityLifecycle.addOnSaveInstanceStateSubscription(id, activityClass, subscription)
}
// ### INTENT MANAGER ###
fun startActivity(
target: Class<out Activity>,
id: String? = null,
preaction: (intent: Intent, id: String, internalId: String) -> Unit = { _, _, _ -> }
): String {
return FacadeIntentManager.startActivity(target, id, preaction)
}
fun startActivityForResult(
target: Class<out Activity>,
requestCode: Int? = null,
id: String? = null,
preaction: (intent: Intent, id: String, internalId: String) -> Unit = { _, _, _ -> }
): Pair<String, Int> {
return FacadeIntentManager.startActivityForResult(target, id, requestCode, preaction)
}
fun startActivity(
activity: Activity,
target: Class<out Activity>,
id: String? = null,
preaction: (intent: Intent, id: String, internalId: String) -> Unit = { _, _, _ -> }
): String {
return FacadeIntentManager.startActivity(activity, target, id, preaction)
}
fun startActivityForResult(
activity: Activity,
target: Class<out Activity>,
requestCode: Int? = null,
id: String? = null,
preaction: (intent: Intent, id: String, internalId: String) -> Unit = { _, _, _ -> }
): Pair<String, Int> {
return FacadeIntentManager.startActivityForResult(
activity,
target,
id,
requestCode,
preaction
)
}
fun provideId(activity: Activity): String {
return FacadeIntentManager.provideId(activity)
}
fun getId(activity: Activity): String? {
return FacadeIntentManager.getId(activity)
}
fun getInternalId(activity: Activity): String {
return FacadeIntentManager.getInternalId(activity)
}
fun getIdOrProvideOne(activity: Activity): String {
return FacadeIntentManager.getIdOrProvideOne(activity)
}
// ### PREFERENCES MANAGER ###
fun get(key: String, defaultValue: String): String {
return FacadePreferencesManager.get(key, defaultValue)
}
fun get(key: String, defaultValue: Int): Int {
return FacadePreferencesManager.get(key, defaultValue)
}
fun get(key: String, defaultValue: Long): Long {
return FacadePreferencesManager.get(key, defaultValue)
}
fun get(key: String, defaultValue: Float): Float {
return FacadePreferencesManager.get(key, defaultValue)
}
fun get(key: String, defaultValue: Boolean): Boolean {
return FacadePreferencesManager.get(key, defaultValue)
}
fun get(key: String, defaultValue: Set<String>): Set<String> {
return FacadePreferencesManager.get(key, defaultValue)
}
fun set(key: String, value: String) {
FacadePreferencesManager.set(key, value)
}
fun set(key: String, value: Int) {
FacadePreferencesManager.set(key, value)
}
fun set(key: String, value: Long) {
FacadePreferencesManager.set(key, value)
}
fun set(key: String, value: Float) {
FacadePreferencesManager.set(key, value)
}
fun set(key: String, value: Boolean) {
FacadePreferencesManager.set(key, value)
}
fun set(key: String, value: Set<String>) {
FacadePreferencesManager.set(key, value)
}
fun clear(){
FacadePreferencesManager.clear()
}
fun clearForce(){
FacadePreferencesManager.clearForce()
}
fun addSubscription(lambda:(SharedPreferences, String?) -> Unit){
FacadePreferencesManager.addSubscription(lambda)
}
fun removeSubscription(lambda:(SharedPreferences, String?) -> Unit){
FacadePreferencesManager.removeSubscription(lambda)
}
}
| 2 |
Kotlin
|
0
| 0 |
56d1eeeffb000e155fcf155e74be246283fc0d77
| 21,091 |
ModuleDroid
|
Apache License 2.0
|
src/main/kotlin/com/germanno/view/MainController.kt
|
gdomingues
| 123,050,708 | false | null |
package com.germanno.view
import com.germanno.app.isValidIpAddress
import com.germanno.app.kodein
import com.germanno.client.EnvironmentManager
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.value.ChangeListener
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.concurrent.Task
import javafx.scene.control.ListView
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
import javafx.stage.DirectoryChooser
import javafx.stage.FileChooser
import javafx.stage.Window
import javafx.util.Duration
import tornadofx.*
import java.io.File
import java.io.IOException
import java.net.InetAddress
import java.net.UnknownHostException
/**
* @author <NAME> - <EMAIL>
* @since 2/20/18 1:47 AM
*/
class MainController : Controller() {
private val environmentManager: EnvironmentManager by kodein()
private var connectivityMonitorTask: Task<Boolean>? = null
private var startMonitoringDelayedTask: FXTimerTask? = null
private var listener: ChangeListener<Boolean>? = null
val connectionStatusColor = SimpleObjectProperty<Paint>()
val connectionStatusText = SimpleObjectProperty<String>()
val invalidIpAddress = SimpleBooleanProperty()
val files: ObservableList<String> = FXCollections.observableArrayList<String>(
environmentManager.listSharedFiles().map { it.canonicalPath }
)
fun addFolderClicked(window: Window?) {
DirectoryChooser()
.apply { title = "Select a folder" }
.showDialog(window)
.handleDialogReturn()
}
fun addFileClicked(window: Window?) {
FileChooser()
.apply { title = "Select a file" }
.showOpenDialog(window)
.handleDialogReturn()
}
private fun File?.handleDialogReturn() {
this?.let { newFile ->
environmentManager.shareFile(newFile)
updateFileList()
}
}
fun deleteFileClicked(it: KeyEvent) {
when (it.code) {
KeyCode.BACK_SPACE, KeyCode.DELETE -> {
@Suppress("UNCHECKED_CAST")
with(it.source as ListView<String>) {
environmentManager.unshareFile(File(selectedItem))
updateFileList()
}
}
else -> {
}
}
}
private fun updateFileList() {
files.apply {
clear()
addAll(environmentManager.listSharedFiles().map { it.canonicalPath })
}
}
fun handleIpChanged(ipAddress: String) {
val isValid = isValidIpAddress(ipAddress)
invalidIpAddress.set(!isValid)
startMonitoringDelayedTask?.cancel()
stopMonitoringConnectivity()
if (isValid) {
startMonitoringDelayedTask = runLater(Duration.seconds(1.0)) {
startMonitoringConnectivity(ipAddress)
}
}
}
fun stopMonitoringConnectivity() {
connectivityMonitorTask?.run {
valueProperty().removeListener(listener)
cancel()
}
}
private fun startMonitoringConnectivity(ipAddress: String) {
val hostAddress = try {
InetAddress.getByName(ipAddress)
} catch (ex: UnknownHostException) {
return
}
connectivityMonitorTask = runAsync {
while (true) {
val isReachable = try {
environmentManager.checkConnection(hostAddress)
} catch (ex: IOException) {
false
}
value(isReachable)
try {
Thread.sleep(1000)
} catch (ex: InterruptedException) {
// The check for cancelled is below
}
if (isCancelled) {
stopClient()
break
}
}
true
}.apply {
listener = createConnectivityListener(hostAddress)
valueProperty().addListener(listener)
}
}
private fun createConnectivityListener(hostAddress: InetAddress): ChangeListener<Boolean> {
return ChangeListener { _, wasReachable, isReachable ->
when {
wasReachable != false && !isReachable -> stopClient()
wasReachable != true && isReachable -> startClient(hostAddress)
}
}
}
private fun stopClient() {
runLater {
connectionStatusColor.set(Color.RED)
connectionStatusText.set("PlayStation 2 is not reachable")
}
environmentManager.killClient()
}
private fun startClient(hostAddress: InetAddress) {
connectionStatusColor.set(Color.DARKGREEN)
connectionStatusText.set("PlayStation 2 is reachable")
runAsync {
with(environmentManager) {
prepare(resources)
startClient(hostAddress)
}
}
}
}
| 3 |
Kotlin
|
0
| 9 |
47326a9956dd0a4d5595062441830edc9480b335
| 5,213 |
ps2-klient
|
MIT License
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/gallery/fungus_fighter/FungusFighterTrainingInfoNotify.kt
|
Anime-Game-Servers
| 642,871,918 | false |
{"Kotlin": 1651536}
|
package org.anime_game_servers.multi_proto.gi.data.gallery.fungus_fighter
import org.anime_game_servers.core.base.Version.GI_3_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_3_2_0)
@ProtoCommand(NOTIFY)
internal interface FungusFighterTrainingInfoNotify {
var buffId: Int
var buffLastTime: Int
var buffStartTime: Int
var killedMonsterCount: Int
var maxMonsterCount: Int
var maxSkillCount: Int
var restSkillCount: Int
}
| 0 |
Kotlin
|
2
| 6 |
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
| 621 |
anime-game-multi-proto
|
MIT License
|
mobile/src/main/kotlin/com/boswelja/smartwatchextensions/main/ui/MainViewModel.kt
|
boswelja
| 103,805,743 | false |
{"Kotlin": 496889}
|
package com.boswelja.smartwatchextensions.main.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.boswelja.smartwatchextensions.core.watches.selected.SelectedWatchController
import kotlinx.coroutines.launch
/**
* A ViewModel for providing data to [MainActivity].
*/
class MainViewModel(
private val selectedWatchController: SelectedWatchController
) : ViewModel() {
/**
* Select a watch by it's ID.
*/
fun selectWatchById(watchId: String) {
viewModelScope.launch {
selectedWatchController.selectWatch(watchId)
}
}
}
| 11 |
Kotlin
|
0
| 25 |
ec7e9ad4c98e18a9a4b5c07f1d39f6c0b1fbfd65
| 615 |
SmartwatchExtensions
|
Apache License 2.0
|
compiler/testData/codegen/box/involvesIrInterpreter/complexBooleanConstant.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}
|
// DONT_TARGET_EXACT_BACKEND: JVM
const val BOOL = <!EVALUATED("true")!>true<!>
const val BOOL_OR = <!EVALUATED("false")!>false && BOOL<!>
const val BOOL_AND = <!EVALUATED("true")!>true || BOOL<!>
const val BOOL_AND_OR = <!EVALUATED("true")!>true || false && BOOL<!>
fun box() = "OK"
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 285 |
kotlin
|
Apache License 2.0
|
domain/src/main/java/com/example/domain/entity/AnimeEntity.kt
|
sahinkaradeniz
| 617,395,151 | false | null |
package com.example.domain.entity
data class AnimeEntity(
var malId: Int,
var images: String?=null,
var titleEnglish: String,
var rating: String,
var score: Double,
var rank: Int,
var popularity: Int,
var year: Int,
)
| 0 |
Kotlin
|
0
| 2 |
bad099567bff40f1cd08976bfa2794d8c358c17c
| 252 |
AnimeApp
|
Apache License 2.0
|
app/src/main/java/com/pramonow/gittracker/activity/InputUserActivity.kt
|
pramonow
| 161,920,733 | false | null |
package com.pramonow.gittracker.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.pramonow.gittracker.R
import com.pramonow.gittracker.contract.InputUserContract
import com.pramonow.gittracker.model.UserDetail
import com.pramonow.gittracker.presenter.InputUserPresenter
import android.view.Menu
import android.view.MenuItem
import android.widget.*
import com.pramonow.gittracker.model.User
import com.pramonow.gittracker.util.USERLIST_INTENT
import com.pramonow.gittracker.util.USERNAME_INTENT
import com.pramonow.gittracker.util.USER_INTENT
import android.view.inputmethod.InputMethodManager
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import android.widget.EditText
class InputUserActivity : AppCompatActivity(), InputUserContract.Activity {
val inputUserPresenter:InputUserContract.Presenter = InputUserPresenter(this)
lateinit var inputText:EditText
lateinit var confirmButton: Button
lateinit var loadingLayout: FrameLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_input_user)
inputText = findViewById(R.id.input_edit_text)
confirmButton = findViewById(R.id.confirm_button)
loadingLayout = findViewById(R.id.loading_layout)
inputText.highlightColor = resources.getColor(R.color.colorLightGray)
confirmButton.setOnClickListener { v -> hideFocus(v); inputUserPresenter.fetchUserList(inputText.text.toString()) }
inputText.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
confirmButton.performClick()
return@OnEditorActionListener true
}
false
})
}
override fun onBackPressed() {
inputUserPresenter.cancelRetrofitCall()
super.onBackPressed()
}
// create an action bar button
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val menuItem = menuInflater.inflate(R.menu.action_bar_menu, menu)
return super.onCreateOptionsMenu(menu)
}
// handle button activities
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.about -> {
startActivity(Intent(this,AboutActivity::class.java))
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
// handle keyboard and focus hiding when user is querying
private fun hideFocus(view:View) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0)
}
/*
Contract Functions block
*/
override fun showLoading(show: Boolean) {
if(show)
loadingLayout.visibility = View.VISIBLE
else
loadingLayout.visibility = View.INVISIBLE
}
override fun navigateToUserActivity(userDetail: UserDetail) {
val intent = Intent(this,UserProfileActivity::class.java)
intent.putExtra(USER_INTENT,userDetail)
startActivity(intent)
}
override fun navigateToUserListActivity(userList: List<User>, username:String) {
val intent = Intent(this,UserListActivity::class.java)
intent.putExtra(USERLIST_INTENT,userList as ArrayList<User>)
intent.putExtra(USERNAME_INTENT,username)
startActivity(intent)
}
override fun showToast(message: String) {
Toast.makeText(this,message,Toast.LENGTH_SHORT).show()
}
override fun showToast(message: Int) {
Toast.makeText(this,getString(message),Toast.LENGTH_SHORT).show()
}
}
| 0 |
Kotlin
|
0
| 1 |
e4f45992b345ebee504668afd787de7bdc3a43a1
| 3,901 |
GitTracker
|
Apache License 2.0
|
banana/src/main/java/me/wcy/banana/Banana.kt
|
wangchenyan
| 523,655,597 | false |
{"Kotlin": 23974}
|
package me.wcy.banana
import me.wcy.apple.api.IApple
import me.wcy.serviceloader.api.ServiceLoader
/**
* Created by wangchenyan.top on 2022/8/11.
*/
object Banana {
fun getApples(): List<IApple> {
return ServiceLoader.loadAll(IApple::class)
}
}
| 0 |
Kotlin
|
0
| 1 |
c7b88a38e46a1d3be2d3ab41b191116a64233e84
| 265 |
service-loader
|
Apache License 2.0
|
app/src/main/java/com/tjclawson/mvvm_practice/data/repository/ForecastRepositoryImpl.kt
|
tjclawson
| 255,468,963 | false | null |
package com.tjclawson.mvvm_practice.data.repository
import androidx.lifecycle.LiveData
import com.tjclawson.mvvm_practice.data.db.CurrentWeatherDao
import com.tjclawson.mvvm_practice.data.db.entity.CurrentWeatherEntry
import com.tjclawson.mvvm_practice.data.network.WeatherNetworkDataSource
import com.tjclawson.mvvm_practice.data.network.response.CurrentWeatherResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.threeten.bp.ZonedDateTime
class ForecastRepositoryImpl(
private val currentWeatherDao: CurrentWeatherDao,
private val weatherNetworkDataSource: WeatherNetworkDataSource
) : ForecastRepository {
init {
weatherNetworkDataSource.downloadedCurrentWeather.observeForever {newCurrentWeather ->
persistFetchedCurrentWeather(newCurrentWeather)
}
}
override suspend fun getCurrentWeather(): LiveData<CurrentWeatherEntry> {
return withContext(Dispatchers.IO) {
initWeatherData()
return@withContext currentWeatherDao.getWeather()
}
}
private fun persistFetchedCurrentWeather(fetchedWeather: CurrentWeatherResponse) {
GlobalScope.launch(Dispatchers.IO) {
currentWeatherDao.upsert(fetchedWeather.currentWeatherEntry)
}
}
private suspend fun initWeatherData() {
if (isFeatchCurrentNeeded(ZonedDateTime.now().minusHours(1)))
fetchCurrentWeather()
}
private suspend fun fetchCurrentWeather() {
weatherNetworkDataSource.fetchCurrentWeather(
"New York"
)
}
private fun isFeatchCurrentNeeded(lastFetchTime: ZonedDateTime): Boolean {
val thirtyMinutesAgo = ZonedDateTime.now().minusMinutes(30)
return lastFetchTime.isBefore(thirtyMinutesAgo)
}
}
| 0 |
Kotlin
|
0
| 0 |
e0696df24d60c01634135a3a12f4831867d3c1d9
| 1,877 |
mvvm_practice
|
MIT License
|
src/chapter1/section3/ex41_CopyQueue.kt
|
w1374720640
| 265,536,015 | false |
{"Kotlin": 1373556}
|
package chapter1.section3
import edu.princeton.cs.algs4.Queue
import extensions.inputPrompt
import extensions.readAllStrings
/**
* ๅคๅถ้ๅ
* ็ผๅไธไธชๆฐ็ๆ้ ๅฝๆฐ๏ผไฝฟไปฅไธไปฃ็
* Queue<Item> r = new Queue<Item>(q);
* ๅพๅฐ็rๆๅ้ๅq็ไธไธชๆฐ็็ฌ็ซ็ๅฏๆฌใ
* ๅฏไปฅๅฏนqๆr่ฟ่กไปปๆๅ
ฅๅๆๅบๅๆไฝไฝๅฎไปฌไธไผ็ธไบๅฝฑๅใ
* ๆ็คบ๏ผไปqไธญๅป้คๆๆๅ
็ด ๅๅฐๅฎไปฌๆๅ
ฅqๅr
*
* ่งฃ๏ผไฝฟ็จๆฉๅฑๅฝๆฐๆจกๆๆฐ็ๆ้ ๅฝๆฐ
*/
fun <T> Queue<T>.copy(): Queue<T> {
val copyQueue = Queue<T>()
val size = size()
//่ฟ้ๅฐๅ้ๅๅ
ๅบๅ๏ผๅๅๅซๅ
ฅๅๅฐไธคไธช้ๅไธญ๏ผ
//ไนๅฏไปฅ็จ่ฟญไปฃๅจ่ฎฟ้ฎ๏ผๅช้่ฆๅ
ฅๅไธๆฌก
repeat(size) {
val value = dequeue()
enqueue(value)
copyQueue.enqueue(value)
}
return copyQueue
}
fun main() {
inputPrompt()
val array = readAllStrings()
val originQueue = Queue<String>()
array.forEach {
originQueue.enqueue(it)
}
val copyQueue = originQueue.copy()
if (!originQueue.isEmpty) {
originQueue.dequeue()
}
println("origin queue = ${originQueue.joinToString()}")
println("copy queue = ${copyQueue.joinToString()}")
}
| 0 |
Kotlin
|
1
| 6 |
879885b82ef51d58efe578c9391f04bc54c2531d
| 966 |
Algorithms-4th-Edition-in-Kotlin
|
MIT License
|
android/src/main/kotlin/com/shahxad/flutter_background_location/FlutterBackgroundLocationPlugin.kt
|
marengga
| 227,843,095 | true |
{"Kotlin": 14525, "Dart": 7672, "Ruby": 3165, "Swift": 3059, "Shell": 431, "Objective-C": 422}
|
package com.almoullim.background_location
import android.Manifest
import android.app.Activity
import android.content.*
import android.content.pm.PackageManager
import android.location.Location
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.almoullim.background_location.Utils
import com.almoullim.background_location.LocationUpdatesService
import com.almoullim.background_location.R
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.Registrar
class BackgroundLocationPlugin() : MethodCallHandler, PluginRegistry.RequestPermissionsResultListener {
private lateinit var activity: Activity
private lateinit var channel: MethodChannel
private var myReceiver: MyReceiver? = null
private var mService: LocationUpdatesService? = null
private var mBound: Boolean = false
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "almoullim.com/background_location")
channel.setMethodCallHandler(BackgroundLocationPlugin(registrar.activity(), channel))
}
private const val TAG = "com.almoullim.Log.Tag"
private const val REQUEST_PERMISSIONS_REQUEST_CODE = 34
}
constructor(activity: Activity, channel: MethodChannel) : this() {
this.activity = activity
this.channel = channel
myReceiver = MyReceiver()
if (Utils.requestingLocationUpdates(activity)) {
if (!checkPermissions()) {
requestPermissions()
}
}
LocalBroadcastManager.getInstance(activity).registerReceiver(myReceiver!!,
IntentFilter(LocationUpdatesService.ACTION_BROADCAST))
}
override fun onMethodCall(call: MethodCall, result: Result) {
when {
call.method == "stop_location_service" -> {
mService?.removeLocationUpdates()
LocalBroadcastManager.getInstance(activity).unregisterReceiver(myReceiver!!)
if (mBound) {
activity.unbindService(mServiceConnection)
mBound = false
}
}
call.method == "start_location_service" -> {
LocalBroadcastManager.getInstance(activity).registerReceiver(myReceiver!!,
IntentFilter(LocationUpdatesService.ACTION_BROADCAST))
if (!mBound) {
activity.bindService(Intent(activity, LocationUpdatesService::class.java), mServiceConnection, Context.BIND_AUTO_CREATE)
}
/*
if (mService != null) {
requestLocation()
}*/
}
else -> result.notImplemented()
}
}
private val mServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
mBound = true
val binder = service as LocationUpdatesService.LocalBinder
mService = binder.service
requestLocation()
}
override fun onServiceDisconnected(name: ComponentName) {
mService = null
}
}
private fun requestLocation() {
if (!checkPermissions()) {
requestPermissions()
} else {
mService!!.requestLocationUpdates()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray?): Boolean {
Log.i(TAG, "onRequestPermissionResult")
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
when {
grantResults!!.isEmpty() -> Log.i(TAG, "User interaction was cancelled.")
grantResults[0] == PackageManager.PERMISSION_GRANTED -> mService!!.requestLocationUpdates()
else -> Toast.makeText(activity, R.string.permission_denied_explanation, Toast.LENGTH_LONG).show()
}
}
return true
}
private inner class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val location = intent.getParcelableExtra<Location>(LocationUpdatesService.EXTRA_LOCATION)
if (location != null) {
val locationMap = HashMap<String, Double>()
locationMap["latitude"] = location.latitude
locationMap["longitude"] = location.longitude
locationMap["altitude"] = location.altitude
locationMap["accuracy"] = location.accuracy.toDouble()
locationMap["bearing"] = location.bearing.toDouble()
locationMap["speed"] = location.speed.toDouble()
channel.invokeMethod("location", locationMap, null)
}
}
}
private fun checkPermissions(): Boolean {
return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION)
}
private fun requestPermissions() {
val shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.ACCESS_FINE_LOCATION)
if (shouldProvideRationale) {
Log.i(TAG, "Displaying permission rationale to provide additional context.")
Toast.makeText(activity, R.string.permission_rationale, Toast.LENGTH_LONG).show()
} else {
Log.i(TAG, "Requesting permission")
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_PERMISSIONS_REQUEST_CODE)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
e819c91e5b78992b4109fd71f814cfbbc94b8512
| 6,106 |
flutter_background_location
|
Apache License 2.0
|
app/src/main/java/ohior/app/mediarock/model/RichTextModel.kt
|
Ohior
| 829,822,046 | false |
{"Kotlin": 120548}
|
package ohior.app.mediarock.model
import androidx.compose.ui.text.SpanStyle
data class RichTextModel(val text: String, val spanStyle: SpanStyle = SpanStyle())
| 0 |
Kotlin
|
0
| 0 |
92af83bb2787ec815ce93c774922449cb2df9ebe
| 161 |
MediaRick
|
MIT License
|
product/core/featuretoggle/src/main/java/com/yugyd/quiz/featuretoggle/di/FeatureToggleModule.kt
|
Yugyd
| 685,349,849 | false |
{"Kotlin": 729102, "FreeMarker": 22877, "Fluent": 18}
|
/*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yugyd.quiz.featuretoggle.di
import com.yugyd.quiz.remoteconfig.api.RemoteConfig
import com.yugyd.quiz.featuretoggle.data.RemoteConfigImpl
import com.yugyd.quiz.featuretoggle.data.RemoteConfigRepositoryImpl
import com.yugyd.quiz.featuretoggle.domain.FeatureManager
import com.yugyd.quiz.featuretoggle.domain.FeatureManagerImpl
import com.yugyd.quiz.featuretoggle.domain.RemoteConfigRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface FeatureToggleModule {
@Binds
fun bindRemoteConfig(impl: RemoteConfigImpl): RemoteConfig
@Binds
fun bindRemoteConfigRepository(impl: RemoteConfigRepositoryImpl): RemoteConfigRepository
@Binds
fun bindFeatureManager(impl: FeatureManagerImpl): FeatureManager
}
| 0 |
Kotlin
|
1
| 3 |
8225814583906ac877b19f21bc25b51f542f75ac
| 1,487 |
quiz-platform
|
Apache License 2.0
|
app/src/main/java/com/breezefsmaddischemicocorporation/features/login/model/alarmconfigmodel/AlarmConfigResponseModel.kt
|
DebashisINT
| 641,390,752 | false | null |
package com.breezefsmaddischemicocorporation.features.login.model.alarmconfigmodel
import com.breezefsmaddischemicocorporation.base.BaseResponse
/**
* Created by Saikat on 19-02-2019.
*/
class AlarmConfigResponseModel : BaseResponse() {
var alarm_settings_list: ArrayList<AlarmConfigDataModel>? = null
}
| 0 |
Kotlin
|
0
| 0 |
c08eaf8cb0a1f3ade4f1762526afe1fa3976690d
| 311 |
AddisChemicoCorporation
|
Apache License 2.0
|
kmongo-shared/src/main/kotlin/org/litote/kmongo/jackson/JacksonCodec.kt
|
mhlz
| 69,674,695 | true |
{"Kotlin": 236875}
|
/*
* Copyright (C) 2016 Litote
*
* 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.litote.kmongo.jackson
import com.fasterxml.jackson.databind.ObjectMapper
import org.bson.BsonReader
import org.bson.BsonValue
import org.bson.BsonWriter
import org.bson.RawBsonDocument
import org.bson.codecs.Codec
import org.bson.codecs.CollectibleCodec
import org.bson.codecs.DecoderContext
import org.bson.codecs.EncoderContext
import org.bson.codecs.configuration.CodecRegistry
import org.bson.types.ObjectId
import org.litote.kmongo.util.MongoIdUtil
import java.io.IOException
import java.io.UncheckedIOException
import kotlin.reflect.defaultType
import kotlin.reflect.jvm.javaField
/**
*
*/
internal class JacksonCodec<T : Any>(val bsonObjectMapper: ObjectMapper,
val codecRegistry: CodecRegistry,
val type: Class<T>) : Codec<T>, CollectibleCodec<T> {
private val rawBsonDocumentCodec: Codec<RawBsonDocument>
init {
this.rawBsonDocumentCodec = codecRegistry.get(RawBsonDocument::class.java)
}
override fun decode(reader: BsonReader, decoderContext: DecoderContext): T {
try {
return bsonObjectMapper.readValue(rawBsonDocumentCodec.decode(reader, decoderContext).byteBuffer.array(), type)
} catch (e: IOException) {
throw UncheckedIOException(e)
}
}
override fun encode(writer: BsonWriter, value: T, encoderContext: EncoderContext) {
try {
val e = bsonObjectMapper.writeValueAsBytes(value)
rawBsonDocumentCodec.encode(writer, RawBsonDocument(e), encoderContext)
} catch (e: IOException) {
throw UncheckedIOException(e)
}
}
override fun getEncoderClass(): Class<T> {
return this.type
}
override fun getDocumentId(document: T): BsonValue {
val idProperty = MongoIdUtil.findIdProperty(document.javaClass.kotlin)
if (idProperty == null) {
throw IllegalStateException("$type has no id field")
} else {
val idValue = MongoIdUtil.getIdBsonValue(idProperty, document)
return idValue ?: throw IllegalStateException("$type has null id")
}
}
override fun documentHasId(document: T): Boolean
= MongoIdUtil.findIdProperty(document.javaClass.kotlin) != null
override fun generateIdIfAbsentFromDocument(document: T): T {
val idProperty = MongoIdUtil.findIdProperty(document.javaClass.kotlin)
if (idProperty != null) {
val idValue = MongoIdUtil.getIdValue(idProperty, document)
if (idValue == null) {
val toString = idProperty.returnType.toString()
val javaField = idProperty.javaField
javaField!!.isAccessible = true
if (toString.startsWith(ObjectId::class.defaultType.toString())) {
javaField.set(document, ObjectId.get())
} else if (toString.startsWith(String::class.defaultType.toString())) {
javaField.set(document, ObjectId.get().toString())
} else {
throw IllegalArgumentException("generation for id property type not supported : $idProperty")
}
}
}
return document
}
}
| 0 |
Kotlin
|
0
| 0 |
4969befd9b37643c0949d44092e4e58c942a05eb
| 3,855 |
kmongo
|
Apache License 2.0
|
solar/src/main/java/com/chiksmedina/solar/outline/arrowsaction/MaximizeSquare2.kt
|
CMFerrer
| 689,442,321 | false |
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.outline.arrowsaction
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.outline.ArrowsActionGroup
val ArrowsActionGroup.MaximizeSquare2: ImageVector
get() {
if (_maximizeSquare2 != null) {
return _maximizeSquare2!!
}
_maximizeSquare2 = Builder(
name = "MaximizeSquare2", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(14.0f, 7.75f)
curveTo(13.5858f, 7.75f, 13.25f, 7.4142f, 13.25f, 7.0f)
curveTo(13.25f, 6.5858f, 13.5858f, 6.25f, 14.0f, 6.25f)
horizontalLineTo(17.0f)
curveTo(17.4142f, 6.25f, 17.75f, 6.5858f, 17.75f, 7.0f)
verticalLineTo(10.0f)
curveTo(17.75f, 10.4142f, 17.4142f, 10.75f, 17.0f, 10.75f)
curveTo(16.5858f, 10.75f, 16.25f, 10.4142f, 16.25f, 10.0f)
verticalLineTo(8.8107f)
lineTo(14.0303f, 11.0303f)
curveTo(13.7374f, 11.3232f, 13.2626f, 11.3232f, 12.9697f, 11.0303f)
curveTo(12.6768f, 10.7374f, 12.6768f, 10.2626f, 12.9697f, 9.9697f)
lineTo(15.1893f, 7.75f)
horizontalLineTo(14.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(11.0303f, 12.9697f)
curveTo(11.3232f, 13.2626f, 11.3232f, 13.7374f, 11.0303f, 14.0303f)
lineTo(8.8107f, 16.25f)
horizontalLineTo(10.0f)
curveTo(10.4142f, 16.25f, 10.75f, 16.5858f, 10.75f, 17.0f)
curveTo(10.75f, 17.4142f, 10.4142f, 17.75f, 10.0f, 17.75f)
horizontalLineTo(7.0f)
curveTo(6.5858f, 17.75f, 6.25f, 17.4142f, 6.25f, 17.0f)
verticalLineTo(14.0f)
curveTo(6.25f, 13.5858f, 6.5858f, 13.25f, 7.0f, 13.25f)
curveTo(7.4142f, 13.25f, 7.75f, 13.5858f, 7.75f, 14.0f)
verticalLineTo(15.1893f)
lineTo(9.9697f, 12.9697f)
curveTo(10.2626f, 12.6768f, 10.7374f, 12.6768f, 11.0303f, 12.9697f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(10.0f, 7.75f)
curveTo(10.4142f, 7.75f, 10.75f, 7.4142f, 10.75f, 7.0f)
curveTo(10.75f, 6.5858f, 10.4142f, 6.25f, 10.0f, 6.25f)
horizontalLineTo(7.0f)
curveTo(6.5858f, 6.25f, 6.25f, 6.5858f, 6.25f, 7.0f)
verticalLineTo(10.0f)
curveTo(6.25f, 10.4142f, 6.5858f, 10.75f, 7.0f, 10.75f)
curveTo(7.4142f, 10.75f, 7.75f, 10.4142f, 7.75f, 10.0f)
verticalLineTo(8.8107f)
lineTo(9.9697f, 11.0303f)
curveTo(10.2626f, 11.3232f, 10.7374f, 11.3232f, 11.0303f, 11.0303f)
curveTo(11.3232f, 10.7374f, 11.3232f, 10.2626f, 11.0303f, 9.9697f)
lineTo(8.8107f, 7.75f)
horizontalLineTo(10.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(12.9697f, 12.9697f)
curveTo(12.6768f, 13.2626f, 12.6768f, 13.7374f, 12.9697f, 14.0303f)
lineTo(15.1893f, 16.25f)
horizontalLineTo(14.0f)
curveTo(13.5858f, 16.25f, 13.25f, 16.5858f, 13.25f, 17.0f)
curveTo(13.25f, 17.4142f, 13.5858f, 17.75f, 14.0f, 17.75f)
horizontalLineTo(17.0f)
curveTo(17.4142f, 17.75f, 17.75f, 17.4142f, 17.75f, 17.0f)
verticalLineTo(14.0f)
curveTo(17.75f, 13.5858f, 17.4142f, 13.25f, 17.0f, 13.25f)
curveTo(16.5858f, 13.25f, 16.25f, 13.5858f, 16.25f, 14.0f)
verticalLineTo(15.1893f)
lineTo(14.0303f, 12.9697f)
curveTo(13.7374f, 12.6768f, 13.2626f, 12.6768f, 12.9697f, 12.9697f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(11.9426f, 1.25f)
curveTo(9.6342f, 1.25f, 7.8252f, 1.25f, 6.4137f, 1.4397f)
curveTo(4.969f, 1.634f, 3.8289f, 2.0393f, 2.9341f, 2.9341f)
curveTo(2.0393f, 3.8289f, 1.634f, 4.969f, 1.4397f, 6.4137f)
curveTo(1.25f, 7.8252f, 1.25f, 9.6342f, 1.25f, 11.9426f)
verticalLineTo(12.0574f)
curveTo(1.25f, 14.3658f, 1.25f, 16.1748f, 1.4397f, 17.5863f)
curveTo(1.634f, 19.031f, 2.0393f, 20.1711f, 2.9341f, 21.0659f)
curveTo(3.8289f, 21.9607f, 4.969f, 22.366f, 6.4137f, 22.5603f)
curveTo(7.8252f, 22.75f, 9.6342f, 22.75f, 11.9426f, 22.75f)
horizontalLineTo(12.0574f)
curveTo(14.3658f, 22.75f, 16.1748f, 22.75f, 17.5863f, 22.5603f)
curveTo(19.031f, 22.366f, 20.1711f, 21.9607f, 21.0659f, 21.0659f)
curveTo(21.9607f, 20.1711f, 22.366f, 19.031f, 22.5603f, 17.5863f)
curveTo(22.75f, 16.1748f, 22.75f, 14.3658f, 22.75f, 12.0574f)
verticalLineTo(11.9426f)
curveTo(22.75f, 9.6342f, 22.75f, 7.8252f, 22.5603f, 6.4137f)
curveTo(22.366f, 4.969f, 21.9607f, 3.8289f, 21.0659f, 2.9341f)
curveTo(20.1711f, 2.0393f, 19.031f, 1.634f, 17.5863f, 1.4397f)
curveTo(16.1748f, 1.25f, 14.3658f, 1.25f, 12.0574f, 1.25f)
horizontalLineTo(11.9426f)
close()
moveTo(3.9948f, 3.9948f)
curveTo(4.5644f, 3.4251f, 5.3352f, 3.0982f, 6.6136f, 2.9264f)
curveTo(7.9136f, 2.7516f, 9.6218f, 2.75f, 12.0f, 2.75f)
curveTo(14.3782f, 2.75f, 16.0864f, 2.7516f, 17.3864f, 2.9264f)
curveTo(18.6648f, 3.0982f, 19.4355f, 3.4251f, 20.0052f, 3.9948f)
curveTo(20.5749f, 4.5644f, 20.9018f, 5.3352f, 21.0736f, 6.6136f)
curveTo(21.2484f, 7.9136f, 21.25f, 9.6218f, 21.25f, 12.0f)
curveTo(21.25f, 14.3782f, 21.2484f, 16.0864f, 21.0736f, 17.3864f)
curveTo(20.9018f, 18.6648f, 20.5749f, 19.4355f, 20.0052f, 20.0052f)
curveTo(19.4355f, 20.5749f, 18.6648f, 20.9018f, 17.3864f, 21.0736f)
curveTo(16.0864f, 21.2484f, 14.3782f, 21.25f, 12.0f, 21.25f)
curveTo(9.6218f, 21.25f, 7.9136f, 21.2484f, 6.6136f, 21.0736f)
curveTo(5.3352f, 20.9018f, 4.5644f, 20.5749f, 3.9948f, 20.0052f)
curveTo(3.4251f, 19.4355f, 3.0982f, 18.6648f, 2.9264f, 17.3864f)
curveTo(2.7516f, 16.0864f, 2.75f, 14.3782f, 2.75f, 12.0f)
curveTo(2.75f, 9.6218f, 2.7516f, 7.9136f, 2.9264f, 6.6136f)
curveTo(3.0982f, 5.3352f, 3.4251f, 4.5644f, 3.9948f, 3.9948f)
close()
}
}
.build()
return _maximizeSquare2!!
}
private var _maximizeSquare2: ImageVector? = null
| 0 |
Kotlin
|
0
| 0 |
3414a20650d644afac2581ad87a8525971222678
| 8,611 |
SolarIconSetAndroid
|
MIT License
|
app/src/main/java/com/nb/retrofitx/extensions/GlobalScopeExt.kt
|
bhoominn
| 220,747,266 | false | null |
package com.nb.retrofitx.extensions
import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
class GlobalScopeExt<T>(context: T, coroutineScope:suspend CoroutineScope.() -> Unit = {}) : LifecycleObserver where T : Context, T : LifecycleOwner {
var myJob: Job= Job()
private val coroutineContext : CoroutineContext get() = myJob + Dispatchers.Default
private val scope = CoroutineScope(coroutineContext)
init {
context.lifecycle.addObserver(this)
scope.launch {
coroutineScope.invoke(scope)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun stop() = myJob.cancel()
}
| 0 |
Kotlin
|
0
| 1 |
1ad6b1da49490a55d3fee3a99c6a76783dd788be
| 845 |
RetrofitMeetsCoroutine
|
MIT License
|
app/src/main/java/com/byteteam/bluesense/core/presentation/views/notification/NotificationViewModel.kt
|
BlueSense-by-ByteTeam
| 738,355,445 | false |
{"Kotlin": 412626}
|
package com.byteteam.bluesense.core.presentation.views.notification
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.byteteam.bluesense.core.data.common.Resource
import com.byteteam.bluesense.core.data.source.local.room.model.NotificationEntity
import com.byteteam.bluesense.core.domain.repositories.NotificationRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class NotificationViewModel @Inject constructor(
private val notificationRepository: NotificationRepository
) : ViewModel() {
private var _notifications: MutableStateFlow<Resource<List<NotificationEntity>>> = MutableStateFlow(Resource.Loading())
val notifications: StateFlow<Resource<List<NotificationEntity>>> = _notifications
private var _isDeleteModalOpen: MutableStateFlow<Boolean> = MutableStateFlow(false)
val isDeleteModalOpen: StateFlow<Boolean> = _isDeleteModalOpen
private var _onDelete: MutableStateFlow<Boolean> = MutableStateFlow(false)
val onDelete: StateFlow<Boolean> = _onDelete
fun openDeleteModal(){
_isDeleteModalOpen.value = true
}
fun closeDeleteModal(){
_isDeleteModalOpen.value = false
}
fun getNotificationsCurrentUser(){
Log.d("TAG", "getNotificationsCurrentUser: ")
_notifications.value = Resource.Loading()
viewModelScope.launch(Dispatchers.IO) {
try {
notificationRepository.getNotificationsFromCurrentUser().catch {
_notifications.value = Resource.Error(it.message ?: "Error saat mengambil data notifikasi")
}.collect{
_notifications.value = Resource.Success(it)
}
}catch (e: Exception){
_notifications.value = Resource.Error(e.message ?: "Error saat mengambil data notifikasi")
}
}
}
fun deleteNotificationsCurrentUser(){
_onDelete.value = true
viewModelScope.launch(Dispatchers.IO) {
_notifications.value = Resource.Loading()
delay(200)
try {
notificationRepository.deleteNotificationFromCurrentUser()
}catch (e: Exception){
_notifications.value = Resource.Error(e.message ?: "Error saat mengambil data notifikasi")
}finally {
_onDelete.value = false
closeDeleteModal()
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
6efb7dfb300f9acaa07bb77f973907de57d490b7
| 2,730 |
bluesense-android
|
Apache License 2.0
|
multi-library/src/main/kotlin/com/welooky/library/ExtFun.kt
|
ilooky
| 363,075,224 | false | null |
package com.welooky.library
inline fun <reified T : Any> cls() = T::class.java
| 0 |
Kotlin
|
0
| 0 |
d86552dd22d440ceefe77814a843b2f69537ab91
| 79 |
multi-module
|
MIT License
|
roboquant/src/main/kotlin/org/roboquant/feeds/csv/CSVConfig.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.feeds.csv
import org.roboquant.common.*
import org.roboquant.feeds.PriceBar
import org.roboquant.feeds.util.AutoDetectTimeParser
import org.roboquant.feeds.util.TimeParser
import java.io.File
import java.nio.file.Path
import java.util.*
import java.util.regex.Pattern
import kotlin.io.path.div
/**
* Define the configuration to use when parsing CSV files. There three levels of configuration:
*
* 1) Default config that will be applied if nothing else is provided
* 2) The config.properties that will be added and override the default config
* 3) The config provided as a parameter to the Feed constructor that will add/override the previous step
*
* @property fileExtension file extensions to parse, default is '.csv'
* @property filePattern file patterns to take into considerations
* @property fileSkip list of files to skip
* @property parsePattern what do the columns present, if empty columns will be determined based on their name
* @property priceAdjust should the price be adjusted using a volume adjusted column
* @property template The template to use in the default [assetBuilder]
* @property hasHeader do the CSV files have a header, default is true
* @property separator the field separator character, default is ',' (comma)
* @constructor Create new CSV config
*/
data class CSVConfig(
var fileExtension: String = ".csv",
var filePattern: String = ".*",
var fileSkip: List<String> = emptyList(),
var parsePattern: String = "",
var priceAdjust: Boolean = false,
var template: Asset = Asset("TEMPLATE"),
var hasHeader: Boolean = true,
var separator: Char = ','
) {
/**
* Asset builder allows to create assets based on more than just the symbol name. The input is the file that will
* be parsed and the returned value is a valid Asset.
*
* The default implementation will process the following steps:
*
* 1. Take the file name part of the file as the symbol name
* 2 Remove the [fileExtension] part
* 3. Convert to symbol name to uppercase
* 4. Use the [template] to create the actual asset, with only the symbol name variable
*/
var assetBuilder: (File) -> Asset = { file ->
defaultBuilder(file)
}
private val timeParser: TimeParser = AutoDetectTimeParser()
private val info = ColumnInfo()
private val pattern by lazy { Pattern.compile(filePattern) }
private var hasColumnsDefined = false
/**
* default builder takes the file name, removes the file extension and uses that the symbol name
*/
private fun defaultBuilder(file: File): Asset {
val symbol = file.name.removeSuffix(fileExtension).uppercase()
return template.copy(symbol = symbol)
}
init {
require(parsePattern.isEmpty() || parsePattern.length > 5)
}
/**
* @suppress
*/
internal companion object {
private const val configFileName = "config.properties"
private val logger = Logging.getLogger(CSVConfig::class)
/**
* Read a CSV configuration from a [path]. It will use the standard config as base and merge all the
* additional settings found in the config file (if any).
*/
internal fun fromFile(path: Path): CSVConfig {
val result = CSVConfig()
val cfg = readConfigFile(path)
result.merge(cfg)
return result
}
/**
* Read properties from config file [path] is it exist.
*/
private fun readConfigFile(path: Path): Map<String, String> {
val filePath = path / configFileName
val file = filePath.toFile()
val prop = Properties()
if (file.exists()) {
logger.debug { "Found configuration file $file" }
prop.load(file.inputStream())
logger.trace { prop.toString() }
}
return prop.map { it.key.toString() to it.value.toString() }.toMap()
}
}
/**
* Should the provided [file] be parsed or skipped all together, true is parsed
*/
internal fun shouldParse(file: File): Boolean {
val name = file.name
return file.isFile && name.endsWith(fileExtension) && pattern.matcher(name).matches() && name !in fileSkip
}
private fun getAssetTemplate(config: Map<String, String>): Asset {
return Asset(
symbol = config.getOrDefault("symbol", "TEMPLATE"),
type = AssetType.valueOf(config.getOrDefault("type", "STOCK")),
currencyCode = config.getOrDefault("currency", "USD"),
exchangeCode = config.getOrDefault("exchange", ""),
multiplier = config.getOrDefault("multiplier", "1.0").toDouble()
)
}
/**
* Merge a config map into this CSV config
*
* @param config
*/
fun merge(config: Map<String, String>) {
val assetConfig = config.filter { it.key.startsWith("asset.") }.mapKeys { it.key.substring(6) }
template = getAssetTemplate(assetConfig)
for ((key, value) in config) {
logger.debug { "Found property key=$key value=$value" }
when (key) {
"file.extension" -> fileExtension = value
"file.pattern" -> filePattern = value
"file.skip" -> fileSkip = value.split(",")
"price.adjust" -> priceAdjust = value.toBoolean()
"parse.pattern" -> parsePattern = value
}
}
}
/**
* Process a single line and return a PriceEntry (if the line could be parsed). Otherwise, an exception will
* be thrown.
*
* @param asset
* @param line
* @return
*/
internal fun processLine(asset: Asset, line: List<String>): PriceEntry {
val now = timeParser.parse(line[info.time], asset.exchange)
val volume = if (info.hasVolume) line[info.volume].toDouble() else Double.NaN
val action = PriceBar(
asset,
line[info.open].toDouble(),
line[info.high].toDouble(),
line[info.low].toDouble(),
line[info.close].toDouble(),
volume
)
if (priceAdjust) action.adjustClose(line[info.adjustedClose].toDouble())
return PriceEntry(now, action)
}
/**
* Detect columns in a CSV file. Either by a pre-defined parsePattern or else automatically based on the header
* names provided
*
* @param headers
*/
@Synchronized
fun detectColumns(headers: List<String>) {
if (hasColumnsDefined) return
if (parsePattern.isNotEmpty()) info.define(parsePattern)
else info.detectColumns(headers)
hasColumnsDefined = true
if (priceAdjust) require(info.adjustedClose != -1) { "No adjusted close prices found" }
}
}
| 15 |
Kotlin
|
28
| 186 |
31eabb76e4c04f5efa121adb27a6851043495a6d
| 7,480 |
roboquant
|
Apache License 2.0
|
simple/src/main/java/com/foundation/app/simple/demo/base/BaseApiResponse.kt
|
Western-parotia
| 619,378,938 | false |
{"Kotlin": 104968, "Java": 5599}
|
package com.foundation.app.simple.demo.base
/**
* create by zhusw on 5/20/21 14:20
*/
class BaseApiResponse<T> {
object Code {
const val CODE_NORMAL = -123456
const val CODE_SUCCESS = 0
}
/* {
"data": ...,
"errorCode": 0,
"errorMsg": ""
}*/
val data: T? = null
val errorCode: Int = Code.CODE_NORMAL
val errorMsg: String = ""
}
| 0 |
Kotlin
|
2
| 5 |
accd3487856a723cd6698129971936966795a84e
| 418 |
Net
|
MIT License
|
src/test/kotlin/Day1SonarSweepTest.kt
|
NicoMincuzzi
| 435,492,958 | false | null |
import com.github.nicomincuzzi.Day1SonarSweep
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class Day1SonarSweepTest {
@Test
fun checkNumberOfTimesDepthMeasurementIncreases() {
val measurement = listOf(199, 200, 208, 210, 200, 207, 240, 269, 260, 263)
val result = Day1SonarSweep().sonarSweep(measurement)
assertEquals(7, result)
}
@Test
fun checkNumberOfTimesDepthMeasurementIncreases_Answer() {
val measurement = retrieveInput()
val result = Day1SonarSweep().sonarSweep(measurement)
assertEquals(1301, result)
}
@Test
fun checkNumberOfTimesDepthMeasurementIncreasesPartTwo() {
val measurement = listOf(607, 618, 618, 617, 647, 716, 769, 792)
val result = Day1SonarSweep().sonarSweepPartTwo(measurement)
assertEquals(5, result)
}
@Test
fun checkNumberOfTimesDepthMeasurementIncreasesPartTwo_Answer() {
val measurement = retrieveInput()
val result = Day1SonarSweep().sonarSweepPartTwo(measurement)
assertEquals(1346, result)
}
private fun retrieveInput(): List<Int> {
val rows = Day1SonarSweepTest::class.java.getResource("/day1.txt").readText()
return rows.split("\n").filter { x -> x.isNotBlank() }.map(String::toInt)
}
}
| 0 |
Kotlin
|
0
| 0 |
345b69cc4f995f369c1dc509ccfd3db8336d3dd8
| 1,340 |
adventofcode-2021
|
Apache License 2.0
|
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/lumbridge/objs/windmill/lumbridge_windmill_ladders.plugin.kts
|
Gallus-RSPS
| 456,055,680 | true |
{"Kotlin": 3579366, "Dockerfile": 1354}
|
package gg.rsmod.plugins.content.areas.lumbridge.objs.windmill
on_obj_option(12964, "Climb-up") {//ground floor
player.climbUp()
}
on_obj_option(12966, "Climb-down") {//top floor
player.climbDown()
}
on_obj_option(12965, "Climb-up") {//2nd floor
player.climbUp()
}
on_obj_option(12965, "Climb-down") {//2nd floor
player.climbDown()
}
on_obj_option(12965, "Climb") {//2nd floor
player.queue {
dialog(this)
}
}
suspend fun dialog(it: QueueTask) {
when (options(it)) {
1 -> it.player.climbUp()
2 -> it.player.climbDown()
}
}
suspend fun options(it: QueueTask): Int = it.options("Climb up.", "Climb down.")
fun Player.climbDown() {
queue {
player.animate(827)
wait(2)
player.moveTo(player.tile.x, player.tile.z, player.tile.height - 1)
}
}
fun Player.climbUp() {
queue {
player.animate(828)
wait(2)
player.moveTo(player.tile.x, player.tile.z, player.tile.height + 1)
}
}
| 0 |
Kotlin
|
0
| 0 |
d0500a8dcd49c128221a9b19c47c5e636d91f26f
| 990 |
rsmod
|
Apache License 2.0
|
features/details/src/main/java/com/fappslab/features/details/presentation/DetailsActivity.kt
|
F4bioo
| 693,834,465 | false |
{"Kotlin": 401014, "Python": 2583, "Shell": 900}
|
package com.fappslab.features.details.presentation
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.commit
import com.fappslab.features.common.navigation.DetailsArgs
import com.fappslab.seedcake.features.details.R
import com.fappslab.seedcake.features.details.databinding.DetailsActivityBinding
import com.fappslab.seedcake.libraries.design.viewbinding.viewBinding
import com.fappslab.seedcake.libraries.extension.args.putArgs
import com.fappslab.seedcake.libraries.extension.args.toIntent
import com.fappslab.seedcake.libraries.extension.args.viewArgs
class DetailsActivity : AppCompatActivity(R.layout.details_activity) {
private val binding: DetailsActivityBinding by viewBinding(R.id.details_root)
private val args: DetailsArgs by viewArgs()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupFragment()
}
private fun setupFragment() {
supportFragmentManager.commit {
replace(binding.fragmentContainer.id, DetailsFragment.createFragment(args))
}
}
companion object {
fun createIntent(context: Context, args: DetailsArgs): Intent =
context.toIntent<DetailsActivity> { putArgs(args) }
}
}
| 0 |
Kotlin
|
0
| 1 |
b126728e15261c877943736d592d7d269618a114
| 1,349 |
Seedcake
|
MIT License
|
core/src/main/java/com/chooongg/form/FormCreateItemExt.kt
|
Chooongg
| 706,083,573 | false |
{"Kotlin": 372453}
|
package com.chooongg.form
import com.chooongg.form.data.IFormCreator
import com.chooongg.form.item.FormButton
import com.chooongg.form.item.FormCheckBox
import com.chooongg.form.item.FormDivider
import com.chooongg.form.item.FormInput
import com.chooongg.form.item.FormInputFilled
import com.chooongg.form.item.FormInputOutlined
import com.chooongg.form.item.FormLabel
import com.chooongg.form.item.FormMenu
import com.chooongg.form.item.FormRadioButton
import com.chooongg.form.item.FormRating
import com.chooongg.form.item.FormSelector
import com.chooongg.form.item.FormSlider
import com.chooongg.form.item.FormSliderRange
import com.chooongg.form.item.FormSwitch
import com.chooongg.form.item.FormText
import com.chooongg.form.item.FormTime
import com.chooongg.form.item.FormTip
import com.chooongg.form.item.MultiColumnForm
import com.chooongg.form.item.SingleLineForm
fun IFormCreator.singleLine(block: SingleLineForm.() -> Unit) =
addItem(SingleLineForm().apply(block))
fun IFormCreator.multiColumn(block: MultiColumnForm.() -> Unit) =
addItem(MultiColumnForm().apply(block))
fun IFormCreator.addButton(
name: Any?, field: String? = null, block: (FormButton.() -> Unit)? = null
) = addItem(FormButton(name, field).apply { block?.invoke(this) })
fun IFormCreator.addCheckBox(
name: Any?, field: String? = null, block: (FormCheckBox.() -> Unit)? = null
) = addItem(FormCheckBox(name, field).apply { block?.invoke(this) })
fun IFormCreator.addDivider(
block: (FormDivider.() -> Unit)? = null
) = addItem(FormDivider().apply { block?.invoke(this) })
fun IFormCreator.addInput(
name: Any?, field: String? = null, block: (FormInput.() -> Unit)? = null
) = addItem(FormInput(name, field).apply { block?.invoke(this) })
fun IFormCreator.addInputFilled(
name: Any?, field: String? = null, block: (FormInputFilled.() -> Unit)? = null
) = addItem(FormInputFilled(name, field).apply { block?.invoke(this) })
fun IFormCreator.addInputOutlined(
name: Any?, field: String? = null, block: (FormInputOutlined.() -> Unit)? = null
) = addItem(FormInputOutlined(name, field).apply { block?.invoke(this) })
fun IFormCreator.addLabel(
name: Any?, field: String? = null, block: (FormLabel.() -> Unit)? = null
) = addItem(FormLabel(name, field).apply { block?.invoke(this) })
fun IFormCreator.addMenu(
name: Any?, field: String? = null, block: (FormMenu.() -> Unit)? = null
) = addItem(FormMenu(name, field).apply { block?.invoke(this) })
fun IFormCreator.addRadioButton(
name: Any?, field: String? = null, block: (FormRadioButton.() -> Unit)? = null
) = addItem(FormRadioButton(name, field).apply { block?.invoke(this) })
fun IFormCreator.addRating(
name: Any?, field: String? = null, block: (FormRating.() -> Unit)? = null
) = addItem(FormRating(name, field).apply { block?.invoke(this) })
fun IFormCreator.addSelector(
name: Any?, field: String? = null, block: (FormSelector.() -> Unit)? = null
) = addItem(FormSelector(name, field).apply { block?.invoke(this) })
fun IFormCreator.addSlider(
name: Any?, field: String? = null, block: (FormSlider.() -> Unit)? = null
) = addItem(FormSlider(name, field).apply { block?.invoke(this) })
fun IFormCreator.addSliderRange(
name: Any?, field: String? = null, block: (FormSliderRange.() -> Unit)? = null
) = addItem(FormSliderRange(name, field).apply { block?.invoke(this) })
fun IFormCreator.addSwitch(
name: Any?, field: String? = null, block: (FormSwitch.() -> Unit)? = null
) = addItem(FormSwitch(name, field).apply { block?.invoke(this) })
fun IFormCreator.addText(
name: Any?, field: String? = null, block: (FormText.() -> Unit)? = null
) = addItem(FormText(name, field).apply { block?.invoke(this) })
fun IFormCreator.addTime(
name: Any?, field: String? = null, block: (FormTime.() -> Unit)? = null
) = addItem(FormTime(name, field).apply { block?.invoke(this) })
fun IFormCreator.addTip(
name: Any?, field: String? = null, block: (FormTip.() -> Unit)? = null
) = addItem(FormTip(name, field).apply { block?.invoke(this) })
| 0 |
Kotlin
|
0
| 0 |
1f1de9c2807cf3cbe06f9676e619478d1808ff2e
| 4,052 |
FormAdapter
|
Apache License 2.0
|
src/main/kotlin/example/examplemod/Events.kt
|
fuma-nama
| 537,793,028 | false |
{"Kotlin": 99524}
|
package example.examplemod
import example.examplemod.screen.ExampleGUI
import net.minecraft.client.KeyMapping
import net.minecraft.client.Minecraft
import net.minecraft.network.chat.Component
import net.minecraftforge.event.TickEvent
import net.minecraftforge.eventbus.api.SubscribeEvent
import org.lwjgl.glfw.GLFW
object Events {
val open = KeyMapping("key.hud.desc", GLFW.GLFW_KEY_N, "key.magicbeans.category")
@SubscribeEvent
fun onClientTick(e: TickEvent.ClientTickEvent) {
if (open.isDown && e.phase == TickEvent.Phase.START) {
println("Open Screen")
Minecraft.getInstance().setScreen(ExampleGUI(Component.empty()))
}
}
}
| 0 |
Kotlin
|
0
| 1 |
28c0b2fadbda25cf7d042b42ed6a4883e2392e35
| 687 |
mine-ui
|
MIT License
|
gaia/src/main/kotlin/dev/pooq/ichor/gaia/entity/player/UserProfile.kt
|
kxmpxtxnt
| 586,376,008 | false | null |
package dev.pooq.ichor.gaia.entity.player
import dev.pooq.ichor.gaia.extensions.serializers.OldUUIDSerializer
import kotlinx.serialization.Serializable
import java.util.*
@Serializable
data class UserProfile(
val id: @Serializable(with = OldUUIDSerializer::class) UUID,
val name: String,
val properties: List<Property>
)
@Serializable
data class Property(val name: String, val value: String, val signature: String)
| 0 |
Kotlin
|
0
| 3 |
1451ae9c7d1a67d2b85d013aa1dec72cfce7e045
| 424 |
ichor
|
Apache License 2.0
|
gaia/src/main/kotlin/dev/pooq/ichor/gaia/entity/player/UserProfile.kt
|
kxmpxtxnt
| 586,376,008 | false | null |
package dev.pooq.ichor.gaia.entity.player
import dev.pooq.ichor.gaia.extensions.serializers.OldUUIDSerializer
import kotlinx.serialization.Serializable
import java.util.*
@Serializable
data class UserProfile(
val id: @Serializable(with = OldUUIDSerializer::class) UUID,
val name: String,
val properties: List<Property>
)
@Serializable
data class Property(val name: String, val value: String, val signature: String)
| 0 |
Kotlin
|
0
| 3 |
1451ae9c7d1a67d2b85d013aa1dec72cfce7e045
| 424 |
ichor
|
Apache License 2.0
|
kio-core/src/main/kotlin/ru/chermenin/kio/Kio.kt
|
chermenin
| 281,045,133 | false | null |
/*
* Copyright 2020 Alex Chermenin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.chermenin.kio
import java.lang.IllegalStateException
import java.util.*
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.PipelineResult
import org.apache.beam.sdk.coders.Coder
import org.apache.beam.sdk.io.FileSystems
import org.apache.beam.sdk.options.PipelineOptions
import org.apache.beam.sdk.transforms.Create
import org.apache.beam.sdk.values.PCollection
import org.joda.time.Duration
import ru.chermenin.kio.arguments.Arguments
import ru.chermenin.kio.coders.DataCoder
import ru.chermenin.kio.coders.PairCoder
import ru.chermenin.kio.io.Reader
import ru.chermenin.kio.options.KioOptions
import ru.chermenin.kio.utils.hashWithName
/**
* Common context class.
*
* @property pipeline current pipeline definition
* @property arguments additional arguments
*/
class Kio private constructor(private val pipeline: Pipeline, val arguments: Arguments = Arguments(mapOf())) {
companion object {
/**
* Create a context with default settings.
*
* @return context object
*/
fun create(): Kio {
val (options, _) = Arguments.parse(emptyArray())
enrichKioOptions(options)
return Kio(Pipeline.create(options))
}
/**
* Create a context with settings from arguments.
*
* @param args arguments array
* @return context object
*/
fun fromArguments(args: Array<String>): Kio {
val (options, arguments) = Arguments.parse(args)
enrichKioOptions(options)
return Kio(Pipeline.create(options), arguments)
}
/**
* Create a context with the defined pipeline.
*
* @param pipeline original pipeline
* @return context object
*/
fun fromPipeline(pipeline: Pipeline): Kio {
enrichKioOptions(pipeline.options)
return Kio(pipeline)
}
private fun enrichKioOptions(options: PipelineOptions) {
if (options is KioOptions) {
val properties = Properties()
properties.load(this::class.java.classLoader.getResourceAsStream("version.properties"))
options.kioVersion = properties.getProperty("kio.version")
options.kotlinVersion = KotlinVersion.CURRENT.toString()
}
}
}
init {
FileSystems.setDefaultPipelineOptions(pipeline.options)
pipeline.coderRegistry.let {
it.registerCoderProvider(PairCoder.Provider())
it.registerCoderProvider(DataCoder.Provider())
}
}
/**
* Current pipeline options.
*/
val options: PipelineOptions = pipeline.options
/**
* Create collection from iterable of some elements.
*
* @param elements iterable of elements
* @param name operator name (optional)
* @param coder coder for elements (optional)
* @return collection of the elements
*/
fun <T> parallelize(elements: Iterable<T>, name: String = "", coder: Coder<T>? = null): PCollection<T> {
val generator = Create.of(elements).let {
if (coder != null) it.withCoder(coder) else it
}
return pipeline.apply(if (name.isEmpty()) generator.hashWithName("parallelize") else name, generator)
}
/**
* Get reader object to get data collections from other sources.
*/
fun read(): Reader {
return Reader(pipeline)
}
/**
* Execute the job.
*
* @return execution context
*/
fun execute(): ExecutionContext {
return ExecutionContext(pipeline.run())
}
/**
* Defines execution context.
*/
class ExecutionContext(private val pipelineResult: PipelineResult) {
fun isCompleted(): Boolean = pipelineResult.state.isTerminal
fun getState(): PipelineResult.State = pipelineResult.state ?: PipelineResult.State.UNKNOWN
fun waitUntilFinish(duration: Duration = Duration.ZERO): PipelineResult.State {
try {
pipelineResult.waitUntilFinish(org.joda.time.Duration(duration.millis))
return getState()
} catch (e: InterruptedException) {
pipelineResult.cancel()
throw InterruptedException("Job cancelled after exceeding timeout value $duration")
}
}
fun waitUntilDone(duration: Duration = Duration.ZERO) {
val state = waitUntilFinish(duration)
if (state != PipelineResult.State.DONE) {
throw Pipeline.PipelineExecutionException(IllegalStateException("Job finished with state $state"))
}
}
}
}
| 1 |
Kotlin
|
2
| 8 |
e6acc2fb61dbb77314c33fc9b5e2d66f14578fe1
| 5,299 |
kio
|
Apache License 2.0
|
MaWPhotos/src/main/java/us/mikeandwan/photos/api/ApiCollection.kt
|
AerisG222
| 59,966,716 | false |
{"Kotlin": 260116, "Shell": 1268}
|
package us.mikeandwan.photos.api
import com.fasterxml.jackson.annotation.JsonProperty
class ApiCollection<T> {
@JsonProperty("count") var count: Long = 0
@JsonProperty("items") var items: List<T> = ArrayList()
}
| 0 |
Kotlin
|
0
| 0 |
1e51844439da188ce1858014bba17c1410bf0876
| 221 |
maw_photos_android
|
MIT License
|
authlib/src/main/java/dev/maxsiomin/authlib/security/StringHasher.kt
|
MaxSiominDev
| 782,187,914 | false |
{"Kotlin": 295287}
|
package dev.maxsiomin.authlib.security
import java.security.MessageDigest
internal object StringHasher {
fun hashString(input: String, algorithm: String = "SHA-256"): String {
// Get an instance of the specified algorithm
val digest = MessageDigest.getInstance(algorithm)
// Perform the hash
val hashBytes = digest.digest(input.toByteArray(Charsets.UTF_8))
// Convert the byte array to a hexadecimal string
return hashBytes.joinToString("") { "%02x".format(it) }
}
}
| 0 |
Kotlin
|
0
| 1 |
4d714c0d36cf94414a77256d23a50e45ceecdb9f
| 526 |
LifestyleHUB
|
MIT License
|
utbot-framework-test/src/test/kotlin/org/utbot/examples/controlflow/ConditionsTest.kt
|
UnitTestBot
| 480,810,501 | false | null |
package org.utbot.examples.controlflow
import org.junit.jupiter.api.Test
import org.utbot.testcheckers.eq
import org.utbot.testing.UtValueTestCaseChecker
import org.utbot.testing.ignoreExecutionsNumber
internal class ConditionsTest : UtValueTestCaseChecker(testClass = Conditions::class) {
@Test
fun testSimpleCondition() {
check(
Conditions::simpleCondition,
eq(2),
{ condition, r -> !condition && r == 0 },
{ condition, r -> condition && r == 1 }
)
}
@Test
fun testIfLastStatement() {
checkWithException(
Conditions::emptyBranches,
ignoreExecutionsNumber,
)
}
}
| 396 |
Kotlin
|
31
| 91 |
ca7df7c1665cdab2a5d8bc2619611e02e761a228
| 695 |
UTBotJava
|
Apache License 2.0
|
src/providers/gemini/src/commonMain/kotlin/community/flock/aigentic/gemini/model/GeminiModel.kt
|
flock-community
| 791,132,993 | false |
{"Kotlin": 185337, "Shell": 630}
|
package community.flock.aigentic.gemini.model
import community.flock.aigentic.core.message.Message
import community.flock.aigentic.core.model.Authentication
import community.flock.aigentic.core.model.Model
import community.flock.aigentic.core.model.ModelIdentifier
import community.flock.aigentic.core.model.ModelResponse
import community.flock.aigentic.core.tool.ToolDescription
import community.flock.aigentic.gemini.client.GeminiClient
import community.flock.aigentic.gemini.client.config.GeminiApiConfig
import community.flock.aigentic.gemini.client.ratelimit.RateLimitBucket
import community.flock.aigentic.gemini.mapper.createGenerateContentRequest
import community.flock.aigentic.gemini.mapper.toModelResponse
@Suppress("ktlint:standard:class-naming")
sealed class GeminiModelIdentifier(
val stringValue: String,
) : ModelIdentifier {
data object GeminiPro : GeminiModelIdentifier("gemini-pro")
data object GeminiProVision : GeminiModelIdentifier("gemini-pro-vision")
data object Gemini1_5ProLatest : GeminiModelIdentifier("gemini-1.5-pro-latest")
data object Gemini1_5FlashLatest : GeminiModelIdentifier("gemini-1.5-flash-latest")
}
class GeminiModel(
override val authentication: Authentication.APIKey,
override val modelIdentifier: GeminiModelIdentifier,
private val geminiClient: GeminiClient = defaultGeminiClient(authentication),
) : Model {
override suspend fun sendRequest(
messages: List<Message>,
tools: List<ToolDescription>,
): ModelResponse {
val request = createGenerateContentRequest(messages, tools)
return geminiClient
.generateContent(request, modelIdentifier)
.toModelResponse()
}
companion object {
fun defaultGeminiClient(
apiKeyAuthentication: Authentication.APIKey,
requestsPerMinute: Int = 5,
): GeminiClient =
GeminiClient(
config = GeminiApiConfig(apiKeyAuthentication),
rateLimiter = RateLimitBucket(requestsPerMinute),
)
}
}
| 1 |
Kotlin
|
0
| 1 |
fdddcbdc034429e9ad5c0965b12ac735d5a0418d
| 2,068 |
aigentic
|
MIT License
|
app/src/main/java/com/example/alarmko/feature_alarmClock/presentation/addEditAlarm/components/ListWeeksDialog.kt
|
MahdiJamali2004
| 848,197,045 | false |
{"Kotlin": 168883}
|
package com.example.alarmko.feature_alarmClock.presentation.addEditAlarm.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.example.compose.cinzelFontFamily
@Composable
fun ListWeeksDialog(
modifier: Modifier = Modifier,
weekDays: List<String>,
onDismissRequest: () -> Unit,
onCancelClick: () -> Unit,
onOkClick: (List<String>) -> Unit
) {
val listDays = listOf(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
)
var weekDayState by remember {
mutableStateOf(weekDays)
}
Dialog(
onDismissRequest = onDismissRequest,
properties = DialogProperties(
)
) {
Column(
modifier = modifier
.background(MaterialTheme.colorScheme.surfaceContainer, RoundedCornerShape(16.dp))
.padding(16.dp)
) {
Text(
modifier = Modifier
.padding(horizontal = 8.dp, vertical = 16.dp),
text = "Repeat",
fontFamily = cinzelFontFamily,
fontWeight = FontWeight.Bold,
fontSize = MaterialTheme.typography.titleLarge.fontSize
)
listDays.forEach { day ->
ListWeekItem(
day = day,
isChecked = weekDayState.contains(day),
onCheckClick = { _ ->
weekDayState = if (weekDayState.contains(day)) {
weekDayState.toMutableList().apply {
remove(day)
}.toList()
} else {
weekDayState.toMutableList().apply {
add(day)
}.toList()
}
}
)
if (day != listDays[6])
HorizontalDivider(modifier = Modifier.padding(horizontal = 8.dp))
}
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
TextButton(modifier = Modifier.weight(1f), onClick = onCancelClick) {
Text(
text = "CANCEL",
fontFamily = cinzelFontFamily,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.secondary
)
}
VerticalDivider(modifier = Modifier
.height(32.dp)
.padding(horizontal = 8.dp))
TextButton(
modifier = Modifier.weight(1f),
onClick = {
onOkClick(weekDayState)
}
) {
Text(
text = "OK",
fontFamily = cinzelFontFamily,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.secondary
)
}
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
89353dfe0564ea85d89702afd2f15978ccb7cf65
| 4,484 |
CleanArchitectureAlarmApp
|
MIT License
|
app/src/main/kotlin/org/hertsig/commander/App.kt
|
jorn86
| 481,216,861 | false |
{"Kotlin": 41958}
|
package org.hertsig.commander
import androidx.compose.ui.window.application
import org.hertsig.commander.ui.ApplicationWindow
import org.hertsig.compose.registerExceptionHandler
import org.slf4j.LoggerFactory
object App {
private val log = LoggerFactory.getLogger(App::class.java)
fun run() {
registerExceptionHandler()
application { ApplicationWindow() }
}
}
fun main() = App.run()
| 0 |
Kotlin
|
0
| 0 |
7bd4922a9cdb9054982984336c225efef174637b
| 415 |
commander
|
MIT License
|
buildSrc/src/main/kotlin/Versions.kt
|
Lysoun
| 351,224,145 | false | null |
object Versions {
const val junit = "5.7.0"
const val strikt = "0.21.0"
const val kotlin = "1.4.10"
}
| 0 |
Kotlin
|
0
| 0 |
98d39fcab3c8898bfdc2c6875006edcf759feddd
| 113 |
google-code-jam-2021
|
MIT License
|
jstruct_processor/src/main/kotlin/com/lingyun/lib/jstrcut/annotation/processor/StringUtil.kt
|
lingyun-x
| 352,528,086 | false | null |
package com.lingyun.lib.jstrcut.annotation.processor
/*
* Created by mc_luo on 2021/3/31 .
* Copyright (c) 2021 The LingYun Authors. 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.
*/
object StringUtil {
val UP_START = 'A'
val UP_END = 'Z'
val LOW_START = 'a'
val LOW_END = 'z'
@ExperimentalStdlibApi
fun replaceFirstCharToLow(letter: String): String {
if (letter.isEmpty()) {
throw IllegalAccessError("string is empty")
}
if (letter[0] in UP_START..UP_END) {
val firstChar: Char = (letter[0].toInt() + LOW_START.toInt() - UP_START.toInt()).toChar()
return letter.replaceFirstChar {
firstChar
}
} else if (letter[0] in LOW_START..LOW_END) {
return letter
}
throw IllegalAccessError("string is first char is not in[A-Z] or not in [a-z]")
}
@ExperimentalStdlibApi
fun replaceFirstCharToUp(letter: String): String {
if (letter.isEmpty()) {
throw IllegalAccessError("string is empty")
}
if (letter[0] in UP_START..UP_END) {
return letter
} else if (letter[0] in LOW_START..LOW_END) {
val firstChar: Char = (letter[0].toInt() - LOW_START.toInt() + UP_START.toInt()).toChar()
return letter.replaceFirstChar {
firstChar
}
}
throw IllegalAccessError("string is first char is not in[A-Z] or not in [a-z]")
}
}
| 0 |
Kotlin
|
0
| 0 |
0530c8bf93259b556b8b65e92d400611a03efae1
| 2,015 |
jstruct_annotation_processer
|
Apache License 2.0
|
messaging/src/main/kotlin/studio/lunabee/onesafe/messaging/writemessage/screen/WriteMessageUiState.kt
|
LunabeeStudio
| 624,544,471 | false |
{"Kotlin": 2178068, "Java": 11977, "Python": 2057}
|
/*
* Copyright (c) 2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 5/29/2023 - for the oneSafe6 SDK.
* Last modified 5/29/23, 4:51 PM
*/
package studio.lunabee.onesafe.messaging.writemessage.screen
import androidx.compose.runtime.Stable
import studio.lunabee.onesafe.bubbles.ui.model.UIBubblesContactInfo
// TODO bubbles real UiState
// โข currentContact must not be null
// โข error state (no contact found on deeplink for example)
// โข initializing state ?
// โข remove default values
@Stable
data class WriteMessageUiState(
val currentContact: UIBubblesContactInfo? = null,
val plainMessage: String = "",
val encryptedPreview: String = "",
val isUsingDeepLink: Boolean = false,
val isConversationReady: Boolean = true,
)
| 0 |
Kotlin
|
0
| 1 |
d84b9c01b000a5fa69bc90f7b8dfa98206aefa5b
| 1,321 |
oneSafe6_SDK_Android
|
Apache License 2.0
|
decoder/wasm/src/commonMain/kotlin/io/github/charlietap/chasm/decoder/section/code/CodeSectionDecoder.kt
|
CharlieTap
| 743,980,037 | false |
{"Kotlin": 898736, "WebAssembly": 7119}
|
package io.github.charlietap.chasm.decoder.section.code
import com.github.michaelbull.result.Result
import io.github.charlietap.chasm.error.WasmDecodeError
import io.github.charlietap.chasm.reader.WasmBinaryReader
import io.github.charlietap.chasm.section.CodeSection
import io.github.charlietap.chasm.section.SectionSize
fun interface CodeSectionDecoder : (WasmBinaryReader, SectionSize) -> Result<CodeSection, WasmDecodeError>
| 2 |
Kotlin
|
1
| 16 |
1566c1b504b4e0a31ae5008f5ada463c47de71c5
| 431 |
chasm
|
Apache License 2.0
|
app/src/main/java/com/wcsm/healthyfinance/ui/components/AppTitle.kt
|
WallaceMartinsTI
| 812,450,106 | false |
{"Kotlin": 235401}
|
package com.wcsm.healthyfinance.ui.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.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.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.wcsm.healthyfinance.ui.theme.HealthyFinanceTheme
import com.wcsm.healthyfinance.ui.theme.Primary
@Composable
fun AppTitle() {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "HEALTHY FINANCE",
fontSize = 32.sp,
color = Primary,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Default
)
Spacer(modifier = Modifier.height(12.dp))
Text(
text = "CONTROLE SUAS FINANรAS",
color = Color.White
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "COM FACILIDADE",
color = Color.White
)
Spacer(modifier = Modifier.height(24.dp))
}
}
@Preview(showBackground = true, backgroundColor = 0xFF252525)
@Composable
fun AppTitlePreview() {
HealthyFinanceTheme {
AppTitle()
}
}
| 0 |
Kotlin
|
0
| 1 |
64d7d5318750f62f613c20f00606b47e62912f32
| 1,756 |
HealthyFinance
|
MIT License
|
app/src/main/java/com/example/kotlincodingtest/baekjoon/class3/์ฌ์ด_์ต๋จ๊ฑฐ๋ฆฌ.kt
|
ichanguk
| 788,416,368 | false |
{"Kotlin": 312866}
|
package com.example.kotlincodingtest.baekjoon.class3
import java.io.BufferedReader
import java.io.BufferedWriter
import java.util.StringTokenizer
fun main() = with(BufferedReader(System.`in`.bufferedReader())) {
val (N, M) = readLine().split(' ').map { it.toInt() }
val m = MutableList(N) { MutableList(M) { 0 } }
var st: StringTokenizer
val q = ArrayDeque<Triple<Int, Int, Int>>()
val isVisit = MutableList(N) { MutableList(M) { false } }
for (i in 0 until N) {
st = StringTokenizer(readLine())
for (j in 0 until M) {
m[i][j] = st.nextToken().toInt()
if (m[i][j] == 2) {
m[i][j] = 0
q.addFirst(Triple(i, j, 0))
}
if (m[i][j] == 0) {
isVisit[i][j] = true
}
}
}
val dx = listOf(-1, 0, 1, 0)
val dy = listOf(0, 1, 0, -1)
var nx: Int
var ny: Int
while (q.isNotEmpty()) {
val cur = q.removeFirst()
for (i in 0 until 4) {
nx = cur.first + dx[i]
ny = cur.second + dy[i]
if (nx in 0 until N && ny in 0 until M && !isVisit[nx][ny]) {
isVisit[nx][ny] = true
q.addLast(Triple(nx, ny, cur.third + 1))
m[nx][ny] = cur.third + 1
}
}
}
val bw = BufferedWriter(System.out.bufferedWriter())
for (i in 0 until N) {
for (j in 0 until M) {
if(!isVisit[i][j]) {
m[i][j] = -1
}
}
}
m.forEach {
it.forEach {
bw.write("$it ")
}
bw.newLine()
}
bw.flush()
bw.close()
}
| 0 |
Kotlin
|
0
| 0 |
1b992955ef805a4f779bcebfd8385146bb045122
| 1,677 |
KotlinCodingTest
|
MIT License
|
screenrecorder/src/main/java/io/github/japskiddin/screenrecorder/contract/RecordVideo.kt
|
Japskiddin
| 643,089,658 | false |
{"Kotlin": 24137}
|
package io.github.japskiddin.screenrecorder.contract
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.activity.result.contract.ActivityResultContract
import io.github.japskiddin.screenrecorder.model.RecordVideoResult
import io.github.japskiddin.screenrecorder.service.ScreenRecorderService.Companion.EXTRA_RECORDER_DATA
class RecordVideo : ActivityResultContract<Intent, RecordVideoResult>() {
override fun createIntent(context: Context, input: Intent): Intent {
val intent: Intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
input.getParcelableExtra(EXTRA_RECORDER_DATA, Intent::class.java)!!
} else {
@Suppress("DEPRECATION")
input.getParcelableExtra(EXTRA_RECORDER_DATA)!!
}
return intent
}
override fun parseResult(resultCode: Int, intent: Intent?): RecordVideoResult {
return RecordVideoResult(resultCode, intent)
}
}
| 0 |
Kotlin
|
0
| 0 |
934307e79ea09a051fc08976b4596a174d22ace0
| 988 |
ScreenRecorder
|
Apache License 2.0
|
newsApp/app/src/main/java/com/example/newsapp/app/resources/news/data/dao/NewsDao.kt
|
Triunvir4to
| 829,130,872 | false |
{"Kotlin": 121321}
|
package com.example.newsapp.app.resources.news.data.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import com.example.newsapp.app.resources.news.data.model.News
import kotlinx.coroutines.flow.Flow
@Dao
interface NewsDao {
@Query("SELECT * FROM news")
fun getNews(): Flow<List<News>>
@Insert
suspend fun addNews(news: News)
@Delete
suspend fun deleteNews(news: News)
}
| 0 |
Kotlin
|
0
| 0 |
d794ec96b889f1dde8bcfd76aa779d72aabf9c7c
| 462 |
Android
|
MIT License
|
app/src/main/java/com/martinszuc/phising_emails_detection/data/EmailRepository.kt
|
martinszuc
| 698,968,668 | false |
{"Kotlin": 17590}
|
package com.martinszuc.phising_emails_detection.data
import android.content.Context
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.martinszuc.phising_emails_detection.network.GmailApiService
class EmailRepository(context: Context, account: GoogleSignInAccount) {
private val apiService = GmailApiService(context, account)
suspend fun fetchEmails() = apiService.getEmails()
}
| 0 |
Kotlin
|
0
| 0 |
7a3a797701a4598043d53ac000d83297e612856f
| 417 |
phishing-emails-detection
|
MIT License
|
buildSrc/src/main/kotlin/Libs.kt
|
sensorberg
| 255,345,915 | false | null |
import kotlin.String
/**
* Generated by https://github.com/jmfayard/buildSrcVersions
*
* Update this file with
* `$ ./gradlew buildSrcVersions`
*/
object Libs {
/**
* https://developer.android.com/topic/libraries/architecture/index.html
*/
const val core_testing: String = "androidx.arch.core:core-testing:" + Versions.core_testing
/**
* https://developer.android.com/jetpack/androidx
*/
const val core_ktx: String = "androidx.core:core-ktx:" + Versions.core_ktx
/**
* https://developer.android.com/topic/libraries/architecture/index.html
*/
const val navigation_fragment_ktx: String = "androidx.navigation:navigation-fragment-ktx:" +
Versions.navigation_fragment_ktx
/**
* https://developer.android.com/testing
*/
const val espresso_core: String = "androidx.test.espresso:espresso-core:" + Versions.espresso_core
/**
* https://developer.android.com/testing
*/
const val androidx_test_ext_junit: String = "androidx.test.ext:junit:" +
Versions.androidx_test_ext_junit
/**
* https://developer.android.com/studio
*/
const val aapt2: String = "com.android.tools.build:aapt2:" + Versions.aapt2
/**
* https://developer.android.com/studio
*/
const val com_android_tools_build_gradle: String = "com.android.tools.build:gradle:" +
Versions.com_android_tools_build_gradle
/**
* https://developer.android.com/studio
*/
const val lint_gradle: String = "com.android.tools.lint:lint-gradle:" + Versions.lint_gradle
/**
* https://github.com/JakeWharton/timber
*/
const val timber: String = "com.jakewharton.timber:timber:" + Versions.timber
/**
* https://github.com/sensorberg-dev/event
*/
const val event: String = "com.sensorberg.libs:event:" + Versions.event
/**
* https://github.com/vanniktech/gradle-maven-publish-plugin/
*/
const val gradle_maven_publish_plugin: String = "com.vanniktech:gradle-maven-publish-plugin:" +
Versions.gradle_maven_publish_plugin
const val de_fayard_buildsrcversions_gradle_plugin: String =
"de.fayard.buildSrcVersions:de.fayard.buildSrcVersions.gradle.plugin:" +
Versions.de_fayard_buildsrcversions_gradle_plugin
/**
* https://arturbosch.github.io/detekt
*/
const val detekt_cli: String = "io.gitlab.arturbosch.detekt:detekt-cli:" +
Versions.io_gitlab_arturbosch_detekt
/**
* https://arturbosch.github.io/detekt
*/
const val detekt_formatting: String = "io.gitlab.arturbosch.detekt:detekt-formatting:" +
Versions.io_gitlab_arturbosch_detekt
/**
* https://arturbosch.github.io/detekt
*/
const val detekt_gradle_plugin: String = "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:" +
Versions.io_gitlab_arturbosch_detekt
/**
* http://mockk.io
*/
const val mockk: String = "io.mockk:mockk:" + Versions.mockk
/**
* http://junit.org
*/
const val junit_junit: String = "junit:junit:" + Versions.junit_junit
/**
* http://assertj.org
*/
const val assertj_core: String = "org.assertj:assertj-core:" + Versions.assertj_core
/**
* https://kotlinlang.org/
*/
const val kotlin_android_extensions_runtime: String =
"org.jetbrains.kotlin:kotlin-android-extensions-runtime:" + Versions.org_jetbrains_kotlin
/**
* https://kotlinlang.org/
*/
const val kotlin_android_extensions: String = "org.jetbrains.kotlin:kotlin-android-extensions:" +
Versions.org_jetbrains_kotlin
/**
* https://kotlinlang.org/
*/
const val kotlin_gradle_plugin: String = "org.jetbrains.kotlin:kotlin-gradle-plugin:" +
Versions.org_jetbrains_kotlin
/**
* https://kotlinlang.org/
*/
const val kotlin_stdlib_jdk7: String = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:" +
Versions.org_jetbrains_kotlin
}
| 1 |
Kotlin
|
1
| 2 |
408eb81b218702040c626088d0b1436468a5d867
| 3,789 |
android-navigation
|
MIT License
|
core/src/commonMain/kotlin/tech/antibytes/kfixture/generator/primitive/ByteGenerator.kt
|
bitPogo
| 471,069,650 | false | null |
/*
* Copyright (c) 2022 <NAME> (bitPogo) / All rights reserved.
*
* Use of this source code is governed by Apache v2.0
*/
package tech.antibytes.kfixture.generator.primitive
import kotlin.Byte.Companion.MAX_VALUE
import kotlin.Byte.Companion.MIN_VALUE
import kotlin.random.Random
import tech.antibytes.kfixture.PublicApi
internal class ByteGenerator(
private val random: Random,
) : PublicApi.SignedNumberGenerator<Byte, Byte>, Generator<Byte>() {
override fun generate(): Byte = generate(MIN_VALUE, MAX_VALUE)
override fun generate(
predicate: (Byte?) -> Boolean,
): Byte = returnFilteredValue(predicate, ::generate)
override fun generate(
from: Byte,
to: Byte,
predicate: (Byte?) -> Boolean,
): Byte = returnFilteredValue(predicate) {
random.nextInt(
from = from.toInt(),
until = to.toInt() + 1,
).toByte()
}
private fun resolveBoundary(sign: PublicApi.Sign): Pair<Byte, Byte> {
return if (sign == PublicApi.Sign.POSITIVE) {
ZERO to MAX_VALUE
} else {
MIN_VALUE to ZERO
}
}
override fun generate(
sign: PublicApi.Sign,
predicate: (Byte?) -> Boolean,
): Byte {
val (from, to) = resolveBoundary(sign)
return generate(from, to, predicate)
}
private companion object {
const val ZERO = 0.toByte()
}
}
| 0 | null |
1
| 12 |
52ccc8a29b0429fc07335cd4926169d254a78551
| 1,427 |
kfixture
|
Apache License 2.0
|
app/src/main/java/com/androidapp/navweiandroidv2/util/ext/ViewExt.kt
|
serifenuruysal
| 239,270,875 | false |
{"Kotlin": 410694, "Java": 337878, "Shell": 731, "Batchfile": 633}
|
package com.androidapp.navweiandroidv2.util.ext
import android.view.View
/**
* Created by <NAME> on 2019-12-25.
*/
fun View.visible(){
this.visibility=View.VISIBLE
}
fun View.gone(){
this.visibility=View.GONE
}
| 0 |
Kotlin
|
0
| 1 |
2547885c8349302617e219077a3ea0a8c4041601
| 223 |
Navwei-Android-App
|
MIT License
|
src/main/kotlin/com/vanniktech/dependency/graph/generator/extensions.kt
|
vanniktech
| 123,641,451 | false | null |
package com.vanniktech.dependency.graph.generator
import org.gradle.api.Project
private val whitespaceRegex = Regex("\\s")
internal val String.dotIdentifier get() = replace("-", "")
.replace(".", "")
.replace(whitespaceRegex, "")
internal fun String.nonEmptyPrepend(prepend: String) =
if (isNotEmpty()) prepend + this else this
internal fun String.toHyphenCase(): String {
if (isBlank()) return this
return this[0].toLowerCase().toString() + toCharArray()
.map { it.toString() }
.drop(1)
.joinToString(separator = "") { if (it[0].isUpperCase()) "-${it[0].toLowerCase()}" else it }
}
internal val Project.dotIdentifier get() = "$group$name".dotIdentifier
fun Project.isJavaProject() = listOf("java-library", "java", "java-gradle-plugin").any { plugins.hasPlugin(it) }
fun Project.isKotlinProject() = listOf("kotlin", "kotlin-android", "kotlin-platform-jvm").any { plugins.hasPlugin(it) }
fun Project.isAndroidProject() = listOf("com.android.library", "com.android.application", "com.android.test", "com.android.feature", "com.android.instantapp").any { plugins.hasPlugin(it) }
fun Project.isJsProject() = plugins.hasPlugin("kotlin2js")
fun Project.isCommonsProject() = plugins.hasPlugin("org.jetbrains.kotlin.platform.common")
| 11 |
Kotlin
|
77
| 1,110 |
903771ccf64436590c74f6ebd4abb26d516cd1d4
| 1,272 |
gradle-dependency-graph-generator-plugin
|
Apache License 2.0
|
app/src/main/java/com/herdal/moviehouse/ui/movie_details/MovieDetailsViewModel.kt
|
herdal06
| 579,902,398 | false |
{"Kotlin": 167133}
|
package com.herdal.moviehouse.ui.movie_details
import androidx.lifecycle.*
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.herdal.moviehouse.common.Resource
import com.herdal.moviehouse.domain.uimodel.movie_detail.MovieDetailUiModel
import com.herdal.moviehouse.domain.uimodel.movie.MovieUiModel
import com.herdal.moviehouse.domain.use_case.movie.GetMovieDetailsUseCase
import com.herdal.moviehouse.domain.use_case.movie.GetRecommendedMoviesUseCase
import com.herdal.moviehouse.domain.use_case.movie.GetSimilarMoviesUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import timber.log.Timber
import javax.inject.Inject
@HiltViewModel
class MovieDetailsViewModel @Inject constructor(
private val getMovieDetailsUseCase: GetMovieDetailsUseCase,
private val getSimilarMoviesUseCase: GetSimilarMoviesUseCase,
private val getRecommendedMoviesUseCase: GetRecommendedMoviesUseCase
) : ViewModel() {
private val _movieDetail =
MutableStateFlow<Resource<MovieDetailUiModel>>(Resource.Loading())
val movieDetail: StateFlow<Resource<MovieDetailUiModel>> = _movieDetail
private val _similarMovies =
MutableLiveData<PagingData<MovieUiModel>>()
private val _recommendedMovies =
MutableLiveData<PagingData<MovieUiModel>>()
fun getMovieDetails(id: Int) {
getMovieDetailsUseCase.invoke(id)
.onEach { resource ->
when (resource) {
is Resource.Loading -> {
_movieDetail.value = Resource.Loading()
}
is Resource.Success -> {
if (resource.data != null) {
_movieDetail.value = Resource.Success(resource.data)
}
}
is Resource.Error -> {
_movieDetail.value = Resource.Error(resource.message)
}
}
}.launchIn(viewModelScope)
}
fun getSimilarMovies(movieId: Int): LiveData<PagingData<MovieUiModel>> {
val response = getSimilarMoviesUseCase.invoke(movieId).cachedIn(viewModelScope).asLiveData()
_similarMovies.value = response.value
Timber.d("$response")
return response
}
fun getRecommendedMovies(movieId: Int): LiveData<PagingData<MovieUiModel>> {
val response =
getRecommendedMoviesUseCase.invoke(movieId).cachedIn(viewModelScope).asLiveData()
_recommendedMovies.value = response.value
Timber.d("$response")
return response
}
}
| 0 |
Kotlin
|
0
| 5 |
24211bea52cd378353be854bbd78eed1c86b879d
| 2,774 |
HekMovie
|
Apache License 2.0
|
src/test/kotlin/no/nav/sifinnsynapi/sts/STSClientTest.kt
|
navikt
| 267,829,664 | false | null |
package no.nav.sifinnsynapi.sts
import assertk.assertThat
import assertk.assertions.isNotEqualTo
import assertk.assertions.isNotNull
import no.nav.security.token.support.spring.test.EnableMockOAuth2Server
import no.nav.sifinnsynapi.utils.stubStsToken
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock
import org.springframework.context.annotation.Import
import org.springframework.http.HttpStatus
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit.jupiter.SpringExtension
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension::class)
@ActiveProfiles("test")
@AutoConfigureWireMock
@EnableMockOAuth2Server // Tilgjengliggjรธr en oicd-provider for test. Se application-test.yml -> no.nav.security.jwt.issuer.selvbetjening for konfigurasjon
internal class STSClientTest {
@Autowired
lateinit var stsClient: STSClient
@Test
fun `Forvent รฅ hente oicd-token`() {
stubStsToken(forventetStatus = HttpStatus.OK, utgรฅrOm = 3600)
val forventetToken = stsClient.oicdToken()
forventetToken.ikkeErNull()
}
@Test
fun `Gitt at token er hentet allerede, forvent at den er cachet`() {
stubStsToken(forventetStatus = HttpStatus.OK, utgรฅrOm = 3600)
val forventetToken = stsClient.oicdToken()
val cachedToken = stsClient.oicdToken()
cachedToken
.ikkeErNull()
.erLik(forventetToken)
}
private fun String.erLik(token: String): String {
Assertions.assertEquals(token, this)
return this
}
private fun String.ikkeErLik(token: String): String {
assertThat(this).isNotEqualTo(token)
return this
}
private fun String.ikkeErNull(): String {
assertThat { this }.isNotNull()
return this
}
}
| 6 |
Kotlin
|
1
| 1 |
03a8648a054da323a28f847b9c367917acdbe76d
| 2,129 |
sif-innsyn-api
|
MIT License
|
teapot/src/main/java/dev/teapot/sub/Sub.kt
|
sgrekov
| 144,774,391 | false |
{"Kotlin": 138941}
|
package dev.teapot.sub
import dev.teapot.contract.State
import dev.teapot.program.MessageConsumer
interface Sub<S : State> {
fun setMessageConsumer(mc : MessageConsumer)
fun subscribe(state: S)
fun dispose()
}
| 0 |
Kotlin
|
2
| 30 |
01724b845aacf0ec0085b47906ceb4041f74b6d9
| 226 |
Teapot
|
Apache License 2.0
|
App/Study_Demo/GoodExample/app/src/main/java/com/goodexample/MainActivity.kt
|
TIMAVICIIX
| 608,668,001 | false |
{"Kotlin": 64286, "Classic ASP": 59330, "Java": 41104, "Python": 35687, "C#": 34974, "C": 25644, "HTML": 22409, "C++": 16172, "JavaScript": 7629, "CSS": 4407}
|
package com.goodexample
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
class MainActivity : AppCompatActivity() {
private lateinit var bottomFragment: Fragment
private lateinit var centerFragment: Fragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
init()
}
private fun init() {
bottomFragment = supportFragmentManager.findFragmentById(R.id.bottomFragment)!!
centerFragment = supportFragmentManager.findFragmentById(R.id.centerFragment)!!
bottomFragment=BottomGuide()
centerFragment=Center()
}
}
| 0 |
Kotlin
|
0
| 1 |
3be9fa9b2b9a0baa1342324122274328f3666a90
| 734 |
TimData
|
MIT License
|
ktor-incontrol/src/main/kotlin/com/skosc/incontrol/handler/parameter/ControllerHandlerParameter.kt
|
SkoSC
| 326,718,598 | false | null |
package com.skosc.incontrol.handler.parameter
import com.skosc.incontrol.controller.Controller
import com.skosc.incontrol.handler.parameter.ParameterType
import kotlin.reflect.KParameter
import kotlin.reflect.KType
/**
* Class wrapping [KParameter] describing [Controller]s handler methods parameter
*
* @author a.yakovlev
* @since indev
*/
internal data class ControllerHandlerParameter(
val kParameter: KParameter,
val type: ParameterType,
val name: String,
) {
val kType: KType = kParameter.type
val isOptional: Boolean = kParameter.isOptional
val isNullable: Boolean = kType.isMarkedNullable
override fun toString(): String {
return "$name: $kType"
}
}
| 0 |
Kotlin
|
0
| 8 |
c1fbcdfde588321ab6c18e1f2bf5caec665e2fff
| 706 |
ktor-incontrol
|
Apache License 2.0
|
android/quash-sdk-core/src/main/java/com/quash/bugs/core/data/dto/QuashBugListModels.kt
|
Oscorp-HQ
| 816,823,332 | false |
{"TypeScript": 500449, "Kotlin": 458549, "Java": 363078, "CSS": 86401, "HTML": 18908, "Shell": 3999, "JavaScript": 3387, "Dockerfile": 584}
|
/*
* Copyright (c) 2024 Quash.
*
* Licensed under the MIT License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* 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.quash.bugs.core.data.dto
import android.os.Parcelable
import androidx.annotation.Keep
import kotlinx.parcelize.Parcelize
/**
* Represents the response received when retrieving a list of bug reports.
* @property success Indicates whether the request was successful.
* @property message A message describing the response status.
* @property data The list of bug reports and associated metadata.
*/
@Keep
data class BugListResponse(
val success: Boolean,
val message: String,
val data: BugReportList
)
/**
* Represents a list of bug reports and associated metadata.
* @property reports The list of bug reports.
* @property meta Metadata associated with the bug report list.
*/
@Keep
data class BugReportList(
val reports: List<Report>,
val meta: Meta
)
/**
* Represents a single bug report.
* @property id The unique identifier of the bug report.
* @property title The title of the bug report.
* @property description The description of the bug report.
* @property reportedBy The user who reported the bug.
* @property type The type of the bug report.
* @property priority The priority of the bug report.
* @property source The source of the bug report.
* @property status The status of the bug report.
* @property createdAt The timestamp when the bug report was created.
* @property listOfMedia The list of media attachments associated with the bug report.
* @property crashLog2 The crash log associated with the bug report.
* @property appId The ID of the application associated with the bug report.
* @property exportedOn The timestamp when the bug report was exported.
* @property updatedAt The timestamp when the bug report was last updated.
*/
@Keep
@Parcelize
data class Report(
val id: String,
val title: String? = null,
val description: String? = null,
val reportedBy: Reporter,
val type: String? = null,
val priority: String? = null,
val source: String? = null,
val status: String? = null,
val createdAt: String? = null,
val listOfMedia: List<Media>?,
val crashLog2: CrashLog?,
val appId: String? = null,
val exportedOn: String? = null,
val updatedAt: String? = null
) : Parcelable
/**
* Represents the user who reported a bug.
* @property id The unique identifier of the user.
* @property fullName The full name of the user.
* @property workEmail The work email of the user.
* @property password The password of the user.
* @property profileImage The URL of the user's profile image.
* @property coverImage The URL of the user's cover image.
* @property emailVerified Indicates whether the user's email is verified.
* @property verificationToken The verification token for the user.
* @property tokenExpiration The timestamp when the user's token expires.
* @property createdAt The timestamp when the user was created.
* @property shouldNavigateToDashboard Indicates whether the user should navigate to the dashboard.
* @property userOrganisationRole The role of the user in the organization.
* @property signUpType The type of sign-up for the user.
* @property enabled Indicates whether the user is enabled.
* @property authorities The list of authorities associated with the user.
* @property accountNonExpired Indicates whether the user's account is not expired.
* @property accountNonLocked Indicates whether the user's account is not locked.
* @property credentialsNonExpired Indicates whether the user's credentials are not expired.
*/
@Keep
@Parcelize
data class Reporter(
val id: String? = null,
val fullName: String? = null,
val workEmail: String? = null,
val password: String? = null,
val profileImage: String? = null,
val coverImage: String? = null,
val emailVerified: Boolean,
val verificationToken: String? = null,
val tokenExpiration: String? = null,
val createdAt: String? = null,
val shouldNavigateToDashboard: Boolean,
val userOrganisationRole: String? = null,
val signUpType: String? = null,
val enabled: Boolean,
val authorities: List<String>?,
val accountNonExpired: Boolean,
val accountNonLocked: Boolean,
val credentialsNonExpired: Boolean
) : Parcelable
/**
* Represents a media attachment associated with a bug report.
* @property id The unique identifier of the media attachment.
* @property bugId The ID of the bug report associated with the media attachment.
* @property mediaUrl The URL of the media attachment.
* @property createdAt The timestamp when the media attachment was created.
* @property mediaType The type of the media attachment.
*/
@Keep
@Parcelize
data class Media(
val id: String,
val bugId: String? = null,
val mediaUrl: String,
val createdAt: String? = null,
val mediaType: String
) : Parcelable
/**
* Represents a crash log associated with a bug report.
* @property id The unique identifier of the crash log.
* @property logUrl The URL of the crash log.
* @property bugId The ID of the bug report associated with the crash log.
* @property createdAt The timestamp when the crash log was created.
*/
@Keep
@Parcelize
data class CrashLog(
val id: String,
val logUrl: String,
val bugId: String? = null,
val createdAt: String? = null
) : Parcelable
/**
* Represents metadata associated with a list of bug reports.
* @property currentPage The current page number of the bug report list.
* @property totalPages The total number of pages in the bug report list.
* @property totalRecords The total number of records in the bug report list.
* @property perPage The number of records per page in the bug report list.
*/
@Keep
@Parcelize
data class Meta(
val currentPage: Int,
val totalPages: Int,
val totalRecords: Int,
val perPage: Int
) : Parcelable
/**
* An object that holds a reference to a single bug report.
*/
object QuashBugConstant {
var report: Report? = null
}
| 22 |
TypeScript
|
6
| 22 |
6367e1a04d0b3e0c03c9bedec71a9da2067dbd4e
| 6,463 |
quash-max
|
MIT License
|
server/src/main/kotlin/com/takaotech/dashboard/route/login/SessionRoute.kt
|
TakaoTech
| 761,297,714 | false |
{"Kotlin": 301488, "Swift": 594, "HTML": 369, "Dockerfile": 348}
|
package com.takaotech.dashboard.route.login
import io.ktor.resources.*
@Resource("/session")
class SessionRoute {
@Resource("login")
class Login(val parent: SessionRoute = SessionRoute())
@Resource("signup")
class Signup(val parent: SessionRoute = SessionRoute())
@Resource("refresh")
class Refresh(val parent: SessionRoute = SessionRoute())
}
| 6 |
Kotlin
|
0
| 2 |
10b1c4559d059234e968543dd5d975ee9b795107
| 371 |
TTD
|
Apache License 2.0
|
app/src/main/java/com/balocco/androidcomponents/feature/toprated/domain/LoadTopRatedMoviesUseCase.kt
|
AlexBalo
| 285,021,731 | false | null |
package com.balocco.androidcomponents.feature.toprated.domain
import com.balocco.androidcomponents.data.MoviesRepository
import com.balocco.androidcomponents.data.model.Movie
import io.reactivex.rxjava3.core.Flowable
import javax.inject.Inject
class LoadTopRatedMoviesUseCase @Inject constructor(
private val repository: MoviesRepository
) {
operator fun invoke(): Flowable<List<Movie>> = repository.loadTopRatedMovies()
}
| 0 |
Kotlin
|
0
| 0 |
8c6909841af60db6d3370793a4383d6bdacf2d42
| 433 |
AndroidComponents
|
Apache License 2.0
|
app/src/main/java/com/example/test_app/ui/search/SortButton.kt
|
tmaciulis22
| 422,973,530 | false |
{"Kotlin": 86619}
|
package com.example.test_app.ui.search
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.example.test_app.R
@Composable
fun SortButton(
isSorted: Boolean = false,
onClick: () -> Unit = {}
) {
IconButton(
modifier = Modifier
.background(
if (isSorted) MaterialTheme.colors.primary else MaterialTheme.colors.background,
CircleShape
)
.size(dimensionResource(R.dimen.grid_unit_27x)),
onClick = onClick
) {
Icon(
painterResource(R.drawable.ic_sort),
stringResource(R.string.content_description_sort_icon),
tint = if (isSorted) Color.White else MaterialTheme.colors.onSurface
)
}
}
@Preview
@Composable
fun SortButtonPreview() {
SortButton()
}
| 0 |
Kotlin
|
0
| 0 |
75f85de3f1ecd5074ed9bd3cf1046c4813431de2
| 1,351 |
compose-news-app
|
MIT License
|
app/src/main/java/markod/irails/allstations/AllStationsContract.kt
|
markic22
| 181,779,098 | false | null |
package markod.irails.allstations
import markod.irails.mvp.MvpPresenter
import markod.irails.mvp.MvpView
class AllStationsContract{
interface View: MvpView {
fun showStations(stations: List<Station>)
fun showError(error: String)
}
interface Presenter: MvpPresenter<View> {
fun loadStations()
}
}
| 0 |
Kotlin
|
0
| 0 |
4d83916cf052cc43e0d9ffd2fa4c572fcd4d3d80
| 340 |
iRailsNew
|
Apache License 2.0
|
fdatasync.kt
|
datkt
| 157,414,511 | false | null |
package datkt.fs
import kotlinx.cinterop.staticCFunction
import kotlinx.cinterop.CPointer
import datkt.uv.uv_fs_fdatasync
import datkt.uv.uv_fs_t
import datkt.fs.EmptyCallback as Callback
fun fdatasync(fd: Int, callback: Callback) {
val req = uv.init<Callback>(callback)
uv_fs_fdatasync(
datkt.fs.loop.default,
uv.toCValuesRef<uv_fs_t>(req),
fd,
staticCFunction(::onfdatasync))
}
private fun onfdatasync(req: CPointer<uv_fs_t>?) {
uv.request<Callback>(req) { err, uv ->
uv.done(err)
uv.cleanup()
}
}
| 0 |
Kotlin
|
1
| 3 |
11e6b8d809950d23fe48a07510fb5c34ae83c0b8
| 537 |
fs
|
MIT License
|
core-v2/core-v2-train/src/main/java/com/github/teracy/odpt/core/v2/train/TrainDataPointApiClient.kt
|
teracy
| 193,032,147 | false | null |
package com.github.teracy.odpt.core.v2.train
import com.github.teracy.odpt.core.v2.train.request.*
import com.github.teracy.odpt.core.v2.train.response.*
import com.github.teracy.odpt.model.ApiClient
/**
* v2็ใใผใฟๅๅพใปๆค็ดขAPIใๅฉ็จใใ้้ๆ
ๅ ฑใฏใฉใคใขใณใ
*/
interface TrainDataPointApiClient : ApiClient {
/**
* v2็้้ใใผใฟๅๅพใปๆค็ดขAPIๆฅ็ถใตใผใในใฎใคใณในใฟใณใน
*/
fun trainDataPointApiService(): TrainDataPointApiService
/**
* ้ง
ๆๅป่กจๆ
ๅ ฑๅๅพ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param sameAs ๅบๆ่ญๅฅๅญ๏ผ้ง
ๆๅป่กจๆ
ๅ ฑID๏ผ
* @param station ้ง
ID
* @param railway ่ทฏ็ทID
* @param operator ้่กไผ็คพใฎไบๆฅญ่
ID
* @param railDirection ้้ๆน้ขID
* @return ้ง
ๆๅป่กจๆ
ๅ ฑใชในใ
*/
suspend fun getStationTimetable(
id: String? = null,
sameAs: String? = null,
station: String? = null,
railway: String? = null,
operator: String? = null,
railDirection: String? = null
): List<OdptStationTimetable> {
return trainDataPointApiService().getStationTimetableAsync(
consumerKey = consumerKey(),
id = id,
sameAs = sameAs,
station = station,
railway = railway,
operator = operator,
railDirection = railDirection
).await()
}
/**
* ๅ่ป้่กๆ
ๅ ฑๅๅพ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param operator ้่กไผ็คพใฎไบๆฅญ่
ID
* @param railway ่ทฏ็ทID
* @param trainInformationStatus ้่ก็ถๆณในใใผใฟใน
* @return ๅ่ป้่กๆ
ๅ ฑใชในใ
*/
suspend fun getTrainInformation(
id: String? = null,
operator: String? = null,
railway: String? = null,
trainInformationStatus: String? = null
): List<OdptTrainInformation> {
return trainDataPointApiService().getTrainInformationAsync(
consumerKey = consumerKey(),
id = id,
operator = operator,
railway = railway,
trainInformationStatus = trainInformationStatus
).await()
}
/**
* ๅ่ปใญใฑใผใทใงใณๆ
ๅ ฑๅๅพ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param sameAs ๅบๆ่ญๅฅๅญ๏ผๅ่ปID๏ผ
* @param trainNumber ๅ่ป็ชๅท
* @param trainType ๅ่ป็จฎๅฅID
* @param railway ้้่ทฏ็ทID
* @param trainOwner ๅ่ปๆๅฑไผ็คพID
* @param railDirection ้้ๆน้ขID
* @param delay ้
ๅปถๆ้๏ผ็ง๏ผ
* @param startingStation ๅ่ปใฎๅง็บ้ง
ใฎ้ง
ID
* @param terminalStation ๅ่ปใฎ็ต็้ง
ใฎ้ง
ID
* @param fromStation ๅ่ปใๅบ็บใใ้ง
ใฎ้ง
ID
* @param toStation ๅ่ปใๅใใฃใฆใใ้ง
ใฎ้ง
ID
* @return ๅ่ปใญใฑใผใทใงใณๆ
ๅ ฑใชในใ
*/
suspend fun getTrain(
id: String? = null,
sameAs: String? = null,
trainNumber: String? = null,
trainType: String? = null,
railway: String? = null,
trainOwner: String? = null,
railDirection: String? = null,
delay: Int? = null,
startingStation: String? = null,
terminalStation: String? = null,
fromStation: String? = null,
toStation: String? = null
): List<OdptTrain> {
return trainDataPointApiService().getTrainAsync(
consumerKey = consumerKey(),
id = id,
sameAs = sameAs,
trainNumber = trainNumber,
trainType = trainType,
railway = railway,
trainOwner = trainOwner,
railDirection = railDirection,
delay = delay,
startingStation = startingStation,
terminalStation = terminalStation,
fromStation = fromStation,
toStation = toStation
).await()
}
/**
* ้ง
ๆ
ๅ ฑๅๅพ๏ผใใผใฟๆค็ดขAPIๅฉ็จ๏ผ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param sameAs ๅบๆ่ญๅฅๅญ๏ผ้ง
ID๏ผ
* @param title ้ง
ๅ๏ผ้จๅไธ่ดใไพใใฐใ้ๅบงใใงๆค็ดขใใใจ้ๅบง็ทใปไธธใๅ
็ทใปๆฅๆฏ่ฐท็ทใฎใ้ๅบงใใๆฅๆฏ่ฐท็ทใฎใๆฑ้ๅบงใใๆๆฅฝ็บ็ทใฎใ้ๅบงไธไธ็ฎใใ่ฉฒๅฝใใ๏ผ
* @param operator ้่กไผ็คพใฎไบๆฅญ่
ID
* @param railway ่ทฏ็ทID
* @param stationCode ้ง
ใณใผใ๏ผๅๆนไธ่ดใไพใใฐใGใใงๆค็ดขใใใจ้ๅบง็ทใฎๅ
จ้ง
ใใใG0ใใงๆค็ดขใใใจใG01๏ผ้ๅบง็ทๆธ่ฐท๏ผใ๏ฝใG09๏ผ้ๅบง็ท้ๅบง๏ผใใ่ฉฒๅฝใใ๏ผ
* @return ้ง
ๆ
ๅ ฑใชในใ
*/
suspend fun getStation(
id: String? = null,
sameAs: String? = null,
title: String? = null,
operator: String? = null,
railway: String? = null,
stationCode: String? = null
): List<OdptStation> {
return trainDataPointApiService().getStationAsync(
consumerKey = consumerKey(),
id = id,
sameAs = sameAs,
title = title,
operator = operator,
railway = railway,
stationCode = stationCode
).await()
}
/**
* ้ง
ๆฝ่จญๆ
ๅ ฑๅๅพ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param sameAs ๅบๆ่ญๅฅๅญ๏ผ้ง
ๆฝ่จญๆ
ๅ ฑID๏ผ
* @return ้ง
ๆฝ่จญๆ
ๅ ฑใชในใ
*/
suspend fun getStationFacility(
id: String? = null,
sameAs: String? = null
): List<OdptStationFacility> {
return trainDataPointApiService().getStationFacilityAsync(
consumerKey = consumerKey(),
id = id,
sameAs = sameAs
).await()
}
/**
* ้ง
ไน้ไบบๅกๆฐๆ
ๅ ฑๅๅพ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param sameAs ๅบๆ่ญๅฅๅญ๏ผ้ง
ไน้ไบบๅกๆฐๆ
ๅ ฑID๏ผ
* @param operator ้่กไผ็คพใฎไบๆฅญ่
ID
* @param surveyYear ่ชฟๆปๅนดๅบฆ
* @return ้ง
ไน้ไบบๅกๆฐๆ
ๅ ฑใชในใ
*/
suspend fun getPassengerSurvey(
id: String? = null,
sameAs: String? = null,
operator: String? = null,
surveyYear: String? = null
): List<OdptPassengerSurvey> {
return trainDataPointApiService().getPassengerSurveyAsync(
consumerKey = consumerKey(),
id = id,
sameAs = sameAs,
operator = operator,
surveyYear = surveyYear
).await()
}
/**
* ้้่ทฏ็ทๆ
ๅ ฑๅๅพ๏ผใใผใฟๆค็ดขAPIๅฉ็จ๏ผ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param sameAs ๅบๆ่ญๅฅๅญ๏ผ้้่ทฏ็ทID๏ผ
* @param title ้่ก็ณป็ตฑๅ๏ผใ็ทใใๅซใพใชใ้จๅไธ่ดใไพใใฐใๆฅฝใใงๆค็ดขใใใจๆๆฅฝ็บ็ทใ่ฉฒๅฝใใใใใๆๆฅฝ็บ็ทใใงใฏ่ฉฒๅฝใใ่ทฏ็ทใฏใชใ๏ผ
* @param operator ้่กไผ็คพใฎไบๆฅญ่
ID
* @param lineCode ่ทฏ็ทใณใผใ๏ผ้จๅไธ่ดใๅคงๆๅญๅฐๆๅญใๅบๅฅใใชใใไพใใฐใmใใงๆค็ดขใใใจใM๏ผไธธใๅ
็ท๏ผใใจใMb๏ผไธธใๅ
ๆฏ็ท๏ผใใใใBใใงๆค็ดขใใใจใMb๏ผไธธใๅ
ๆฏ็ท๏ผใใ่ฉฒๅฝใใ๏ผ
* @return ้้่ทฏ็ทๆ
ๅ ฑใชในใ
*/
suspend fun getRailway(
id: String? = null,
sameAs: String? = null,
title: String? = null,
operator: String? = null,
lineCode: String? = null
): List<OdptRailway> {
return trainDataPointApiService().getRailwayAsync(
consumerKey = consumerKey(),
id = id,
sameAs = sameAs,
title = title,
operator = operator,
lineCode = lineCode
).await()
}
/**
* ้่ณๆ
ๅ ฑๅๅพ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param sameAs ๅบๆ่ญๅฅๅญ๏ผ้่ณๆ
ๅ ฑID๏ผ
* @param operator ้่กไผ็คพใฎไบๆฅญ่
ID
* @param fromStation ้ง
้ใฎๅง็น้ง
ใฎ้ง
ID
* @param toStation ้ง
้ใฎ็ต็น้ง
ใฎ้ง
ID
* @param ticketFare ๅ็ฌฆๅฉ็จๆใฎ้่ณ
* @param childTicketFare ๅ็ฌฆๅฉ็จๆใฎๅญไพ้่ณ
* @param icCardFare ICใซใผใๅฉ็จๆใฎ้่ณ
* @param childIcCardFare ICใซใผใๅฉ็จๆใฎๅญไพ้่ณ
* @return ้่ณๆ
ๅ ฑใชในใ
*/
suspend fun getRailwayFare(
id: String? = null,
sameAs: String? = null,
operator: String? = null,
fromStation: String? = null,
toStation: String? = null,
ticketFare: Int? = null,
childTicketFare: Int? = null,
icCardFare: Int? = null,
childIcCardFare: Int? = null
): List<OdptRailwayFare> {
return trainDataPointApiService().getRailwayFareAsync(
consumerKey = consumerKey(),
id = id,
sameAs = sameAs,
operator = operator,
fromStation = fromStation,
toStation = toStation,
ticketFare = ticketFare,
childTicketFare = childTicketFare,
icCardFare = icCardFare,
childIcCardFare = childIcCardFare
).await()
}
/**
* ๅ่ปๆๅป่กจๆ
ๅ ฑๅๅพ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param sameAs ๅบๆ่ญๅฅๅญ๏ผๅ่ปๆๅป่กจๆ
ๅ ฑID๏ผ
* @param trainNumber ๅ่ป็ชๅท
* @param railway ่ทฏ็ทID
* @param operator ้่กไผ็คพใฎไบๆฅญ่
ID
* @param trainType ๅ่ป็จฎๅฅID
* @param railDirection ้้ๆน้ขID
* @param startingStation ๅ่ปใฎๅง็บ้ง
ใฎ้ง
ID
* @param terminalStation ๅ่ปใฎ็ต็้ง
ใฎ้ง
ID
* @param trainOwner ่ปไธกใฎๆๅฑไผ็คพใฎID
* @param train ๅ่ปID
* @return ๅ่ปๆๅป่กจๆ
ๅ ฑใชในใ
*/
suspend fun getTrainTimetable(
id: String? = null,
sameAs: String? = null,
trainNumber: String? = null,
railway: String? = null,
operator: String? = null,
trainType: String? = null,
railDirection: String? = null,
startingStation: String? = null,
terminalStation: String? = null,
trainOwner: String? = null,
train: String? = null
): List<OdptTrainTimetable> {
return trainDataPointApiService().getTrainTimetableAsync(
consumerKey = consumerKey(),
id = id,
sameAs = sameAs,
trainNumber = trainNumber,
railway = railway,
operator = operator,
trainType = trainType,
railDirection = railDirection,
startingStation = startingStation,
terminalStation = terminalStation,
trainOwner = trainOwner,
train = train
).await()
}
/**
* ้ง
ๆๅป่กจๆ
ๅ ฑๅๅพ
*
* @param argument ๆค็ดขๅผๆฐ
* @return ้ง
ๆๅป่กจๆ
ๅ ฑใชในใ
*/
suspend fun getStationTimetable(argument: StationTimetableArgument): List<OdptStationTimetable> {
return getStationTimetable(
id = argument.id,
sameAs = argument.sameAs,
station = argument.station,
railway = argument.railway,
operator = argument.operator,
railDirection = argument.railDirection
)
}
/**
* ๅ่ป้่กๆ
ๅ ฑๅๅพ
*
* @param argument ๆค็ดขๅผๆฐ
* @return ๅ่ป้่กๆ
ๅ ฑใชในใ
*/
suspend fun getTrainInformation(argument: TrainInformationArgument): List<OdptTrainInformation> {
return getTrainInformation(
id = argument.id,
operator = argument.operator,
railway = argument.railway
)
}
/**
* ๅ่ปใญใฑใผใทใงใณๆ
ๅ ฑๅๅพ
*
* @param argument ๆค็ดขๅผๆฐ
* @param delay ้
ๅปถๆ้๏ผไปปๆใๅไฝใฏ็งใ5ๅไปฅๅ
ใฎ้
ใใฏๅใๆจใฆ๏ผ
* @return ๅ่ปใญใฑใผใทใงใณๆ
ๅ ฑใชในใ
*/
suspend fun getTrain(argument: TrainArgument, delay: Int? = null): List<OdptTrain> {
return getTrain(
id = argument.id,
sameAs = argument.sameAs,
trainNumber = argument.trainNumber,
trainType = argument.trainType,
railway = argument.railway,
trainOwner = argument.trainOwner,
railDirection = argument.railDirection,
delay = delay,
startingStation = argument.startingStation,
terminalStation = argument.terminalStation,
fromStation = argument.fromStation,
toStation = argument.toStation
)
}
/**
* ้ง
ๆ
ๅ ฑๅๅพ
*
* @param argument ๆค็ดขๅผๆฐ
* @return ้ง
ๆ
ๅ ฑใชในใ
*/
suspend fun getStation(argument: StationArgument): List<OdptStation> {
return getStation(
id = argument.id,
sameAs = argument.sameAs,
title = argument.title,
operator = argument.operator,
railway = argument.railway,
stationCode = argument.stationCode
)
}
/**
* ้ง
ๆฝ่จญๆ
ๅ ฑๅๅพ
*
* @param argument ๆค็ดขๅผๆฐ
* @return ้ง
ๆฝ่จญๆ
ๅ ฑใชในใ
*/
suspend fun getStationFacility(argument: StationFacilityArgument): List<OdptStationFacility> {
return getStationFacility(
id = argument.id,
sameAs = argument.sameAs
)
}
/**
* ้ง
ไน้ไบบๅกๆฐๆ
ๅ ฑๅๅพ
*
* @param argument ๆค็ดขๅผๆฐ
* @return ้ง
ไน้ไบบๅกๆฐๆ
ๅ ฑใชในใ
*/
suspend fun getPassengerSurvey(argument: PassengerSurveyArgument): List<OdptPassengerSurvey> {
return getPassengerSurvey(
id = argument.id,
sameAs = argument.sameAs,
operator = argument.operator,
surveyYear = argument.surveyYear
)
}
/**
* ้้่ทฏ็ทๆ
ๅ ฑๅๅพ๏ผใใผใฟๆค็ดขAPIๅฉ็จ๏ผ
*
* @param argument ๆค็ดขๅผๆฐ
* @return ้้่ทฏ็ทๆ
ๅ ฑใชในใ
*/
suspend fun getRailway(argument: RailwayArgument): List<OdptRailway> {
return getRailway(
id = argument.id,
sameAs = argument.sameAs,
title = argument.title,
operator = argument.operator,
lineCode = argument.lineCode
)
}
/**
* ้่ณๆ
ๅ ฑๅๅพ
*
* @param argument ๆค็ดขๅผๆฐ
* @return ้่ณๆ
ๅ ฑใชในใ
*/
suspend fun getRailwayFare(argument: RailwayFareArgument): List<OdptRailwayFare> {
return getRailwayFare(
id = argument.id,
sameAs = argument.sameAs,
operator = argument.operator,
fromStation = argument.fromStation,
toStation = argument.toStation
)
}
/**
* ๅ่ปๆๅป่กจๆ
ๅ ฑๅๅพ
*
* @param argument ๆค็ดขๅผๆฐ
* @return ๅ่ปๆๅป่กจๆ
ๅ ฑใชในใ
*/
suspend fun getTrainTimetable(argument: TrainTimetableArgument): List<OdptTrainTimetable> {
return getTrainTimetable(
id = argument.id,
sameAs = argument.sameAs,
trainNumber = argument.trainNumber,
railway = argument.railway,
operator = argument.operator,
trainType = argument.trainType,
railDirection = argument.railDirection,
startingStation = argument.startingStation,
terminalStation = argument.terminalStation,
trainOwner = argument.trainOwner,
train = argument.train
)
}
/**
* ้ง
ๅบๅ
ฅๅฃๆ
ๅ ฑๅๅพ๏ผใใผใฟๆค็ดขAPIๅฉ็จ๏ผ
*
* @param id ๅบๆ่ญๅฅๅญ(ucode)
* @param title ๅฐ็ฉๅใใจใฌใใผใฟใซใฏใใจใฌใใผใฟใใจใใๆๅญๅใๅซใใใๅบๅ
ฅๅฃใใฎๆๅญๅใฎๅพใซๅบๅฃ็ชๅทใ็ถใ
* @return ้ง
ๅบๅ
ฅๅฃๆ
ๅ ฑใชในใ
*/
suspend fun getUgPoi(id: String? = null, title: String? = null): List<UgPoi> {
return trainDataPointApiService().getUgPoiAsync(
consumerKey = consumerKey(),
id = id,
title = title
).await()
}
}
| 0 |
Kotlin
|
0
| 1 |
002554e4ca6e2f460207cfd1cb8265c2267f149d
| 13,737 |
odpt
|
Apache License 2.0
|
app/src/main/kotlin/com/omarmohameddev/teleshows/cache/db/TeleshowsDatabase.kt
|
OmarMohamedDev
| 115,188,126 | false | null |
package com.omarmohameddev.teleshows.cache.db
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.content.Context
import com.omarmohameddev.teleshows.cache.dao.TeleshowDao
import com.omarmohameddev.teleshows.model.Teleshow
@Database(entities = arrayOf(Teleshow::class), version = 1)
abstract class TeleshowsDatabase : RoomDatabase() {
abstract fun cachedTeleshowDao(): TeleshowDao
private var INSTANCE: TeleshowsDatabase? = null
private val sLock = Any()
fun getInstance(context: Context): TeleshowsDatabase {
if (INSTANCE == null) {
synchronized(sLock) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
TeleshowsDatabase::class.java, TeleshowsDbConstants.DATABASE_NAME)
.build()
}
return INSTANCE!!
}
}
return INSTANCE!!
}
}
| 0 |
Kotlin
|
0
| 0 |
c4cefbd68860e797d3a25e5e98de4804ba20fd1f
| 1,061 |
Teleshows
|
MIT License
|
android/library-magiccube/src/main/java/com/hellobike/magiccube/v2/CardService.kt
|
hellof2e
| 651,011,094 | false |
{"Kotlin": 499995, "Objective-C": 421129, "JavaScript": 39299, "Java": 29943, "Swift": 24514, "Ruby": 5345, "TypeScript": 3969, "Shell": 255}
|
package com.hellobike.magiccube.v2
import com.hellobike.magiccube.LoadStyleParams
import com.hellobike.magiccube.StyleManager
import com.hellobike.magiccube.model.StyleModel
import com.hellobike.magiccube.model.contractmodel.LayoutViewModel
import com.hellobike.magiccube.utils.UIUtils
import com.hellobike.magiccube.v2.ext.loge
import com.hellobike.magiccube.v2.ext.logt
import com.hellobike.magiccube.v2.js.IJsEngine
import com.hellobike.magiccube.v2.js.JSEngineInitializer
import com.hellobike.magiccube.v2.js.MainJSEngine
import com.hellobike.magiccube.v2.reports.Codes
internal class CardService(private val cardContext: CardContext?) {
private val taskQueue = AsyncTaskQueue()
/**
* @param onFailure: code[ DSLParser.ErrorCode ]
* INVALID_STYLE: Context == null ๆ่
DownloadManager ไธ่ฝฝๆๅ๏ผไฝๆฏๅจ็ๆStyleModelๆถๅๆๅบๅผๅธธ
*
* INVALID_URL: url ๆฏ็ฉบ็ๆถๅๅ่ฐ
* VERSION_NOT_SUPPORT: MD5 ๆ ก้ชๆๅ version ๆ ก้ชๅคฑ่ดฅ
* INVALID_STYLE: json ๆฏ็ฉบ
* DOWNLOAD_FAILURE: MD5 ๆ ก้ชๅคฑ่ดฅ๏ผๆ่
ๆๅผๅธธ
* DOWNLOAD_CANCEL: ไธ่ฝฝไปปๅก่ขซๅๆถ
*/
fun loadStyleV2(
url: String,
jsEngineInitializer: JSEngineInitializer,
onComplete: (style: StyleModel, jsEngine: IJsEngine, newData: Map<String, Any?>?) -> Unit,
onFailure: (url: String, code: Int, message: String?) -> Unit
) {
// ไผๅ
ๆฅๆพๅ
ๅญ
val styleModel = StyleModelCache.getStyleModelFromCache(url)
val viewModel = styleModel?.layoutModel
if (styleModel?.isValidViewModel() == true && viewModel != null) {
onLoadMemSuccess(styleModel, viewModel, url, jsEngineInitializer, onComplete, onFailure)
return
}
// ๅ
ๅญๆฒกๆ๏ผๅผๆญฅๅ ่ฝฝๅนถ่งฃๆ ViewModel
taskQueue.clear() // ้ฆๅ
ๆธ
็ฉบไนๅ็งฏๅ็ไปปๅก้ๅ
val currentTime = System.currentTimeMillis() // ๆ นๆฎไธป็บฟ็จ่ฐ็จไบไปถๆฅ้กบๅบๅ่ฐ
taskQueue.exec {
// ๅ ่ฝฝๆ ทๅผ
val params = LoadStyleParams(url)
params.id = currentTime
StyleManager.loadStyleWithUrl(object : StyleManager.IOnLoadViewModelListener {
override fun getLoadParams(): LoadStyleParams = params
override fun loadCompleted(url: String, style: StyleModel) {
onLoadCompleted(url, jsEngineInitializer, style, onComplete, onFailure)
}
override fun loadFailure(url: String, errorCode: Int, message: String) {
onLoadFailed(url, errorCode, message, onFailure)
}
})
}
}
// ๅ
ๅญ็ผๅญๅ ่ฝฝๆๅ
private fun onLoadMemSuccess(
styleModel: StyleModel,
viewModel: LayoutViewModel,
url: String,
jsEngineInitializer: JSEngineInitializer,
onComplete: (style: StyleModel, jsEngine: IJsEngine, newData: Map<String, Any?>?) -> Unit,
onFailure: (url: String, code: Int, message: String?) -> Unit
) {
styleModel.fromCache = true
jsEngineInitializer.installLogic(viewModel.logic)
if (!viewModel.enableJSLifecycle()) { // ๆฒกๆๅฏ็จ๏ผ็ดๆฅๅๆญฅๆง่ก
handleDisableLifecycle(styleModel, url, jsEngineInitializer, onComplete, onFailure)
} else { // ๅฏ็จไบๅฐฑๅผๆญฅๅ ่ฝฝ
handleEnableLifecycle(styleModel, url, jsEngineInitializer, onComplete, onFailure)
}
}
// ๆ ทๅผๅ ่ฝฝๅคฑ่ดฅ
private fun onLoadFailed(
url: String,
errorCode: Int,
message: String?,
onFailure: (url: String, code: Int, message: String?) -> Unit
) {
val cardContext = cardContext
if (cardContext != null) {
cardContext.runOnUiThread {
StyleModelCache.removeStyleModel(url)
onFailure.invoke(url, errorCode, message ?: "ๆ ทๅผๅ ่ฝฝๅคฑ่ดฅ")
}
} else {
UIUtils.runOnUiThread {
StyleModelCache.removeStyleModel(url)
onFailure.invoke(url, errorCode, message ?: "ๆ ทๅผๅ ่ฝฝๅคฑ่ดฅ")
}
}
}
// ๆ ทๅผๅ ่ฝฝๆๅ
private fun onLoadCompleted(
url: String,
jsEngineInitializer: JSEngineInitializer,
style: StyleModel,
onComplete: (style: StyleModel, jsEngine: IJsEngine, newData: Map<String, Any?>?) -> Unit,
onFailure: (url: String, code: Int, message: String?) -> Unit
) {
val viewModel = style.layoutModel
if (viewModel == null) {
onLoadFailed(url, Codes.ERROR_PARSE_VIEW_MODEL, "ViewModel ่ทๅๅคฑ่ดฅ!", onFailure)
return
}
jsEngineInitializer.installLogic(viewModel.logic)
if (viewModel.enableJSLifecycle()) {
handleEnableLifecycle(style, url, jsEngineInitializer, onComplete, onFailure)
} else {
handleDisableLifecycle(style, url, jsEngineInitializer, onComplete, onFailure)
}
}
// ็ฆๅค็็จ js lifecycle๏ผไธ้่ฆๅ็ฝฎๆง่กjsๅผๆ
private fun handleDisableLifecycle(
styleModel: StyleModel,
url: String,
jsEngineInitializer: JSEngineInitializer,
onComplete: (style: StyleModel, jsEngine: IJsEngine, newData: Map<String, Any?>?) -> Unit,
onFailure: (url: String, code: Int, message: String?) -> Unit
) {
var throwable: Throwable? = null
val jsEngine = try {
jsEngineInitializer.load(false)
} catch (t: Throwable) {
t.printStackTrace()
throwable = t
null
}
if (jsEngine != null) {
val cardContext = cardContext
if (cardContext != null) {
cardContext.runOnUiThread { onComplete.invoke(styleModel, jsEngine, null) }
} else {
UIUtils.runOnUiThread { onComplete.invoke(styleModel, jsEngine, null) }
}
} else {
val code = Codes.ERROR_JS_LOAD_FAILED
val msg = throwable?.toString() ?: "ๅ ่ฝฝjsๅผๆๅคฑ่ดฅ"
onLoadFailed(url, code, msg, onFailure)
}
}
// ๅค็ๅฏ็จ js lifecycle ็้ป่พ๏ผ้่ฆๅ็ฝฎๅชๆง่กjs
private fun handleEnableLifecycle(
styleModel: StyleModel,
url: String,
jsEngineInitializer: JSEngineInitializer,
onComplete: (style: StyleModel, jsEngine: IJsEngine, newData: Map<String, Any?>?) -> Unit,
onFailure: (url: String, code: Int, message: String?) -> Unit
) = MainJSEngine.postJSQueue {
try {
val jsEngine = jsEngineInitializer.load(true)
val jsDataMap = jsEngine.callBeforeCreate()
// ๆฐๆฎๅ็ๆดๆน๏ผๅ้่ฆๆๆฐๆฐๆฎ้็ฅๅบๅป๏ผๆฐๆฎๆฒกๆๅ็ๆนๅ๏ผไธ้่ฆๅ่ฐ
val newData = try {
if (jsDataMap.isNullOrEmpty()
|| jsDataMap == jsEngineInitializer.getData()?.originData()
) null
else jsDataMap
} catch (t: Throwable) {
t.printStackTrace()
logt(t)
jsDataMap
}
val cardContext = cardContext
if (cardContext != null) {
cardContext.runOnUiThread { onComplete.invoke(styleModel, jsEngine, newData) }
} else {
UIUtils.runOnUiThread { onComplete.invoke(styleModel, jsEngine, newData) }
}
} catch (t: Throwable) {
t.printStackTrace()
val code = Codes.ERROR_JS_LOAD_FAILED
val msg = t.toString()
onLoadFailed(url, code, msg, onFailure)
}
}
}
| 3 |
Kotlin
|
9
| 60 |
8123fdaafa9ee7eaeee43fb73789b7fa3feac697
| 7,273 |
Wukong
|
Apache License 2.0
|
app/src/main/java/com/cjrodriguez/cjchatgpt/presentation/screens/topicScreen/components/DeleteDialog.kt
|
Cj-Rodriguez101
| 681,417,664 | false |
{"Kotlin": 208634}
|
package com.cjrodriguez.cjchatgpt.presentation.screens.topicScreen.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@Preview
fun DeleteDialog(
topicId: String = "",
onDismiss: () -> Unit = {},
onPositiveAction: () -> Unit = {}
) {
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.background(
color = MaterialTheme.colorScheme.surfaceVariant,
shape = CardDefaults.shape
)
) {
Column(
verticalArrangement = Arrangement.SpaceBetween
) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
text = "Are You Sure You Want To Delete This Chat?",
textAlign = TextAlign.Justify,
color = MaterialTheme.colorScheme.onSurface,
fontSize = 14.sp
)
Row(
verticalAlignment = Alignment.CenterVertically, modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.End
) {
OutlinedButton(onClick = onDismiss, modifier = Modifier.padding(end = 16.dp)) {
Text(text = "Cancel", fontSize = 16.sp)
}
OutlinedButton(
onClick = {
onPositiveAction()
onDismiss()
},
colors = ButtonDefaults
.textButtonColors(contentColor = MaterialTheme.colorScheme.error)
) {
Text(text = "Delete", fontSize = 16.sp)
}
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
cb73c8011b8fd439b6838b1eccefee8699b1f23d
| 2,684 |
Cj_ChatGPT
|
Apache License 2.0
|
src/main/java/com/pikolive/module/webview/indicator/IndicatorController.kt
|
InternetED
| 299,563,216 | false | null |
package com.pikolive.module.webview.indicator
import android.webkit.WebView
/**
* Creator: ED
* Date: 2020/11/17 9:53 AM
* Mail: <EMAIL>
*
* **/
interface IndicatorController {
fun progress(v: WebView?, newProgress: Int)
fun offerIndicator(): WebIndicator
fun showIndicator()
fun setProgress(newProgress: Int)
fun finish()
}
| 0 |
Kotlin
|
0
| 0 |
86c255e156a08e38f13c9348f79e0d461d9ea2ab
| 355 |
Thrid_Part_Plugin
|
Apache License 2.0
|
mission-heart/shared/src/commonMain/kotlin/ru/mission/heart/storage/Preferences.kt
|
KYamshanov
| 805,006,151 | false |
{"Kotlin": 24362}
|
package ru.mission.heart.storage
internal expect fun setValue(key: String, value: String)
/**
* return null if value did not set
*/
internal expect fun getValue(key: String): String?
| 0 |
Kotlin
|
0
| 0 |
e597b3f2554e399c9c329c1f2fffeb06b5d88c5c
| 186 |
Mission-LSP
|
Apache License 2.0
|
Pokemon/app/src/main/java/com/example/android/pokemon/details/DetailsViewModelFactory.kt
|
Savitar97
| 319,745,352 | false | null |
package com.example.android.pokemon.details
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.android.pokemon.dao.PokeListDao
class DetailsViewModelFactory (private val pokemonID: Long,
private val dataSource: PokeListDao) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(DetailsViewModel::class.java)) {
return DetailsViewModel(pokemonID, dataSource) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| 0 |
Kotlin
|
0
| 0 |
267d7c868dfecf39fbc5bd2b9b7ae5ae75def625
| 624 |
PokemonAndroid
|
MIT License
|
k4-core/src/main/kotlin/com/luggsoft/k4/core/engine/tokenizers/tokens/TextTokenizerState.kt
|
luggsoft
| 243,032,262 | false | null |
package com.luggsoft.k4.core.engine.tokenizers.tokens
import com.luggsoft.k4.core.Source
import com.luggsoft.k4.core.engine.Location
import com.luggsoft.k4.core.engine.tokenizers.TokenizerSettings
class TextTokenizerState(
tokenizerSettings: TokenizerSettings
) : TokenizerStateBase(
tokenizerSettings = tokenizerSettings
)
{
@Throws(TokenizerStateException::class)
override fun getNextToken(source: Source, startIndex: Int, tokenizerStateSetter: TokenizerStateSetter): Token
{
var index = startIndex
val stringBuffer = StringBuffer()
while (index < source.text.length)
{
stringBuffer.append(source.text[index++])
if (stringBuffer.endsWith("<#"))
{
val tokenProviderState = when (source.text[index++])
{
'!' -> CodeTokenizerState(this.tokenizerSettings)
'=' -> EchoTokenizerState(this.tokenizerSettings)
'+' -> BodyTokenizerState(this.tokenizerSettings)
'@' -> InfoTokenizerState(this.tokenizerSettings)
'*' -> NoteTokenizerState(this.tokenizerSettings)
else -> UnknownTokenizerState
}
tokenizerStateSetter(tokenProviderState)
return TextToken(
text = stringBuffer.removeSuffix("<#").toString(),
location = Location(
name = source.name,
startIndex = startIndex,
untilIndex = index
)
)
}
}
return TextToken(
text = stringBuffer.toString(),
location = Location(
name = source.name,
startIndex = startIndex,
untilIndex = index
)
)
}
}
| 1 |
Kotlin
|
0
| 1 |
da96e3655090bf332f609e18ca64e223da18529e
| 1,894 |
k4
|
MIT License
|
k4-core/src/main/kotlin/com/luggsoft/k4/core/engine/tokenizers/tokens/TextTokenizerState.kt
|
luggsoft
| 243,032,262 | false | null |
package com.luggsoft.k4.core.engine.tokenizers.tokens
import com.luggsoft.k4.core.Source
import com.luggsoft.k4.core.engine.Location
import com.luggsoft.k4.core.engine.tokenizers.TokenizerSettings
class TextTokenizerState(
tokenizerSettings: TokenizerSettings
) : TokenizerStateBase(
tokenizerSettings = tokenizerSettings
)
{
@Throws(TokenizerStateException::class)
override fun getNextToken(source: Source, startIndex: Int, tokenizerStateSetter: TokenizerStateSetter): Token
{
var index = startIndex
val stringBuffer = StringBuffer()
while (index < source.text.length)
{
stringBuffer.append(source.text[index++])
if (stringBuffer.endsWith("<#"))
{
val tokenProviderState = when (source.text[index++])
{
'!' -> CodeTokenizerState(this.tokenizerSettings)
'=' -> EchoTokenizerState(this.tokenizerSettings)
'+' -> BodyTokenizerState(this.tokenizerSettings)
'@' -> InfoTokenizerState(this.tokenizerSettings)
'*' -> NoteTokenizerState(this.tokenizerSettings)
else -> UnknownTokenizerState
}
tokenizerStateSetter(tokenProviderState)
return TextToken(
text = stringBuffer.removeSuffix("<#").toString(),
location = Location(
name = source.name,
startIndex = startIndex,
untilIndex = index
)
)
}
}
return TextToken(
text = stringBuffer.toString(),
location = Location(
name = source.name,
startIndex = startIndex,
untilIndex = index
)
)
}
}
| 1 |
Kotlin
|
0
| 1 |
da96e3655090bf332f609e18ca64e223da18529e
| 1,894 |
k4
|
MIT License
|
amiibodetail/src/main/java/com/oscarg798/amiibowiki/amiibodetail/AmiiboDetailFragment.kt
|
aliceresponde
| 296,732,120 | true |
{"Kotlin": 870948, "Shell": 3484}
|
/*
* Copyright 2020 Oscar David Gallon Rosero
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
package com.oscarg798.amiibowiki.amiibodetail
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.snackbar.Snackbar
import com.oscarg798.amiibowiki.amiibodetail.databinding.FragmentAmiiboDetailBinding
import com.oscarg798.amiibowiki.amiibodetail.di.DaggerAmiiboDetailComponent
import com.oscarg798.amiibowiki.amiibodetail.mvi.AmiiboDetailWish
import com.oscarg798.amiibowiki.amiibodetail.mvi.ShowingAmiiboDetailsParams
import com.oscarg798.amiibowiki.core.constants.ARGUMENT_TAIL
import com.oscarg798.amiibowiki.core.di.entrypoints.AmiiboDetailEntryPoint
import com.oscarg798.amiibowiki.core.extensions.setImage
import com.oscarg798.amiibowiki.core.extensions.showExpandedImages
import com.oscarg798.amiibowiki.core.failures.AmiiboDetailFailure
import com.oscarg798.amiibowiki.searchgamesresults.SearchResultFragment
import com.oscarg798.amiibowiki.searchgamesresults.models.GameSearchParam
import dagger.hilt.android.EntryPointAccessors
import javax.inject.Inject
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class AmiiboDetailFragment : Fragment() {
@Inject
lateinit var viewModel: AmiiboDetailViewModel
private lateinit var binding: FragmentAmiiboDetailBinding
private var bottomSheetBehavior: BottomSheetBehavior<View>? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAmiiboDetailBinding.inflate(
LayoutInflater.from(requireContext()),
container,
false
)
return binding.root
}
override fun onAttach(context: Context) {
super.onAttach(context)
val tail = arguments?.getString(ARGUMENT_TAIL, null)
?: throw IllegalArgumentException("Tail is required")
DaggerAmiiboDetailComponent.factory()
.create(
tail,
EntryPointAccessors.fromApplication(
requireActivity().application,
AmiiboDetailEntryPoint::class.java
)
)
.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setup()
}
private fun setup() {
childFragmentManager.beginTransaction()
.replace(
R.id.searchResultFragment,
SearchResultFragment.newInstance(),
getString(R.string.search_result_fragment_tag)
)
.commit()
ViewCompat.isNestedScrollingEnabled(binding.searchResultFragment)
binding.searchResultFragment.setOnClickListener {
bottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
}
configureBackDrop()
viewModel.state.onEach {
when {
it.isLoading -> showLoading()
it.error != null -> showError(it.error)
it.imageExpanded != null -> showExpandedImages(listOf(it.imageExpanded))
it.amiiboDetails != null -> showDetail(it.amiiboDetails)
}
}.launchIn(lifecycleScope)
viewModel.onWish(AmiiboDetailWish.ShowAmiiboDetail)
}
// override fun onBackPressed() {
// if (bottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) {
// bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
// } else {
// super.onBackPressed()
// }
// }
private fun showError(amiiboDetailFailure: AmiiboDetailFailure) {
hideLoading()
Snackbar.make(
binding.clMain,
amiiboDetailFailure.message ?: getString(R.string.general_error),
Snackbar.LENGTH_LONG
).show()
}
private fun configureBackDrop() {
bottomSheetBehavior = BottomSheetBehavior.from<View>(binding.searchResultFragment)
bottomSheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN
}
private fun showDetail(
showingAmiiboDetailsParams: ShowingAmiiboDetailsParams
) {
hideLoading()
val viewAmiiboDetails = showingAmiiboDetailsParams.amiiboDetails
// supportActionBar?.title = viewAmiiboDetails.name
with(binding) {
ivImage.setImage(viewAmiiboDetails.imageUrl)
tvGameCharacter.setText(viewAmiiboDetails.character)
tvSerie.setText(viewAmiiboDetails.gameSeries)
tvType.setText(viewAmiiboDetails.type)
ivImage.setOnClickListener {
viewModel.onWish(AmiiboDetailWish.ExpandAmiiboImage(viewAmiiboDetails.imageUrl))
}
}
if (showingAmiiboDetailsParams.isRelatedGamesSectionEnabled) {
showSearchResultFragment(viewAmiiboDetails.id)
} else {
hideSearchResultFragment()
}
}
private fun showSearchResultFragment(amiiboId: String) {
binding.searchResultFragment.visibility = View.VISIBLE
val searchResultFragment = getSearchResultsFragment() ?: return
searchResultFragment.search(GameSearchParam.AmiiboGameSearchParam(amiiboId))
}
private fun hideSearchResultFragment() {
binding.searchResultFragment.visibility = View.GONE
}
private fun showLoading() {
with(binding) {
shimmer.root.visibility = View.VISIBLE
shimmer.shimmerViewContainer.startShimmer()
tvSerieTitle.visibility = View.GONE
tvTypeTitle.visibility = View.GONE
}
}
private fun hideLoading() {
with(binding) {
shimmer.root.visibility = View.GONE
shimmer.shimmerViewContainer.stopShimmer()
tvSerieTitle.visibility = View.VISIBLE
tvTypeTitle.visibility = View.VISIBLE
}
}
private fun getSearchResultsFragment(): SearchResultFragment? {
return childFragmentManager.findFragmentByTag(getString(R.string.search_result_fragment_tag)) as? SearchResultFragment
}
}
private const val NO_ELEVATION = 0f
| 0 | null |
0
| 0 |
d2d0a1c4edaa4031b3fa89af93c3d93a79ffb016
| 7,644 |
AmiiboWiki
|
MIT License
|
screen/main/src/main/kotlin/ru/maksonic/beresta/screen/main/core/MainSandbox.kt
|
maksonic
| 580,058,579 | false |
{"Kotlin": 1587340, "Assembly": 374}
|
package ru.maksonic.beresta.screen.main.core
import ru.maksonic.beresta.feature.notes_list.ui.api.NoteUi
import ru.maksonic.beresta.feature.notes_list.ui.api.unselectAll
import ru.maksonic.beresta.feature.ui.edit_note.api.EditNoteFabState
import ru.maksonic.beresta.feature.ui.edit_note.api.isExpanded
import ru.maksonic.beresta.feature.ui.search_bar.api.SearchBarState
import ru.maksonic.beresta.platform.elm.core.ElmBaseModel.Companion.Loading
import ru.maksonic.beresta.platform.elm.core.ElmBaseModel.Companion.loadedFailure
import ru.maksonic.beresta.platform.elm.core.ElmBaseModel.Companion.loadedSuccess
import ru.maksonic.beresta.platform.elm.core.ElmUpdate
import ru.maksonic.beresta.platform.elm.core.Sandbox
import ru.maksonic.beresta.screen.main.core.program.ChipsDataProgram
import ru.maksonic.beresta.screen.main.core.program.ChipsSortProgram
import ru.maksonic.beresta.screen.main.core.program.NotesDataProgram
import ru.maksonic.beresta.screen.main.core.program.NotesSortProgram
import ru.maksonic.beresta.screen.main.ui.SnackBarKey
/**
* @Author maksonic on 15.10.2023
*/
private typealias Update = ElmUpdate<Model, Set<Cmd>, Set<Eff>>
class MainSandbox(
notesDataProgram: NotesDataProgram,
notesSortProgram: NotesSortProgram,
chipsDataProgram: ChipsDataProgram,
chipsSortProgram: ChipsSortProgram
) : Sandbox<Model, Msg, Cmd, Eff>(
initialModel = Model.Initial,
initialCmd = setOf(
Cmd.FetchNotesList,
Cmd.FetchNotesSortState,
Cmd.FetchChipsList,
Cmd.FetchChipsSortState
),
subscriptions = listOf(notesDataProgram, notesSortProgram, chipsDataProgram, chipsSortProgram)
) {
companion object {
private const val STICKY_START_FOLDER_ID = 1L
private const val MINIMAL_FOR_LOADING_ITEMS_COUNT = 2000
}
override fun update(msg: Msg, model: Model): Update = when (msg) {
// Notes
is Msg.Inner.FetchedNotesSuccess -> fetchedNotesSuccess(model, msg)
is Msg.Inner.FetchedNotesFail -> fetchedNotesFail(model, msg)
is Msg.Inner.FetchedNotesSort -> fetchedNotesSort(model, msg)
is Msg.Ui.OnNoteClicked -> onNoteClicked(model, msg)
is Msg.Ui.OnNoteLongClicked -> onNoteLongClicked(model, msg)
is Msg.Ui.CancelNotesSelection -> onCancelSelectionClicked(model)
// Folders
is Msg.Inner.FetchedChipsSuccess -> fetchedChipsSuccess(model, msg)
is Msg.Inner.FetchedChipsFail -> fetchedChipsFail(model)
is Msg.Inner.FetchedChipsSort -> fetchedChipsSort(model, msg)
is Msg.Ui.OnRetryFetchChipsClicked -> onRetryFetchChipsClicked(model)
is Msg.Ui.OnChipClicked -> onChipClicked(model, msg)
is Msg.Inner.ResetCurrentSelectedFolder -> resetCurrentSelectedFolder(model)
is Msg.Ui.OnAddNewChipClicked -> onAddNewChipClicked(model)
is Msg.Ui.OnCloseAddChipDialogClicked -> onCloseAddChipDialogClicked(model)
// Idle bottom bar actions
is Msg.Ui.OnBottomBarSettingsClicked -> onBottomBarSettingsClicked(model)
is Msg.Ui.OnBottomBarTrashClicked -> onBottomBarTrashClicked(model)
is Msg.Ui.OnBottomBarFoldersClicked -> onBottomBarFoldersClicked(model)
is Msg.Ui.OnBottomBarSortNotesClicked -> onBottomBarSortNotesClicked(model)
// Selected bottom bar actions
is Msg.Ui.OnBottomBarHideSelectedNotesClicked -> onBottomBarHideSelectedClicked(model)
is Msg.Ui.OnBottomBarPinSelectedNotesClicked -> onBottomBarPinSelectedClicked(model)
is Msg.Ui.OnBottomBarMoveSelectedNotesClicked -> onBottomBarMoveSelectedClicked(model)
is Msg.Ui.OnBottomBarRemoveSelectedNotesClicked -> onBottomBarRemoveSelectedClicked(model)
is Msg.Inner.UpdatedEditNoteFabState -> updatedEditNoteFabState(model, msg)
// Search bar
is Msg.Ui.OnCollapseSearchBar -> onCollapseSearchBar(model)
is Msg.Ui.OnExpandSearchBar -> onExpandSearchBar(model)
is Msg.Ui.OnCounterBarSelectAllClicked -> onCounterBarSelectAllClicked(model, msg)
is Msg.Ui.OnCounterBarShareClicked -> onCounterBarShareClicked(model)
is Msg.Ui.OnChangeGridViewClicked -> onSearchBarGridViewClicked(model, msg)
is Msg.Ui.OnCancelSelectionClicked -> onCancelSelectionClicked(model)
// Snack bar
is Msg.Ui.OnSnackUndoRemoveNotesClicked -> onSnackBarUndoRemoveClicked(model)
//
is Msg.Inner.HiddenModalBottomSheet -> hiddenModalBottomSheet(model)
// Hidden notes
is Msg.Inner.NavigatedToHiddenNotes -> navigatedToHiddenNotes(model)
is Msg.Inner.UpdatedHiddenNotesDialogVisibility -> {
updatedHiddenNotesDialogVisibility(model, msg)
}
}
private fun fetchedNotesSuccess(model: Model, msg: Msg.Inner.FetchedNotesSuccess): Update =
ElmUpdate(
model.copy(
notes = model.notes.copy(
state = model.notes.state.loadedSuccess, collection = msg.notes
),
searchBarState = model.searchBarState.copy(searchList = msg.notes)
)
)
private fun fetchedNotesFail(model: Model, msg: Msg.Inner.FetchedNotesFail): Update =
ElmUpdate(
model.copy(
notes = model.notes.copy(
state = model.notes.state.loadedFailure(msg.failInfo),
collection = NoteUi.Collection.Empty
),
searchBarState = model.searchBarState.copy(searchList = NoteUi.Collection.Empty)
)
)
private fun fetchedNotesSort(model: Model, msg: Msg.Inner.FetchedNotesSort): Update = ElmUpdate(
model.copy(sortState = model.sortState.copy(notes = msg.sort))
)
private fun onNoteClicked(model: Model, msg: Msg.Ui.OnNoteClicked): Update =
if (model.notes.isSelection) baseOnNoteAction(model, msg.id)
else ElmUpdate(
model.copy(
editNoteFabState = model.editNoteFabState.copy(state = EditNoteFabState.COLLAPSED)
),
effects = setOf(Eff.NavigateToEditNote(msg.id))
)
private fun onNoteLongClicked(model: Model, msg: Msg.Ui.OnNoteLongClicked): Update =
baseOnNoteAction(model, msg.id)
private fun baseOnNoteAction(model: Model, noteId: Long): Update {
val notes = model.notes.collection.copy(model.notes.collection.data.map { note ->
val isSelected = if (note.id == noteId) !note.isSelected else note.isSelected
note.copy(isSelected = isSelected)
})
val selectedList = notes.data.filter { it.isSelected }
val isVisibleUnpinButton = selectedList.isNotEmpty().run {
if (this) !selectedList.map { it.style.isPinned }.contains(false) else false
}
return ElmUpdate(
model.copy(
notes = model.notes.copy(
collection = notes,
isSelection = true,
isVisibleUnpinBottomBarIcon = isVisibleUnpinButton
),
searchBarState = model.searchBarState.copy(
barState = SearchBarState.Selected,
counterValue = selectedList.count()
),
editNoteFabState = model.editNoteFabState.copy(
isVisible = false, state = EditNoteFabState.COLLAPSED
),
),
)
}
private fun onCancelSelectionClicked(model: Model): Update = ElmUpdate(
model.copy(
notes = model.notes.copy(
collection = model.notes.collection.unselectAll(), isSelection = false
),
searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed),
editNoteFabState = model.editNoteFabState.copy(isVisible = true),
)
)
private fun fetchedChipsSuccess(model: Model, msg: Msg.Inner.FetchedChipsSuccess): Update =
ElmUpdate(
model.copy(
chips = model.chips.copy(
state = model.chips.state.loadedSuccess, collection = msg.chips
),
),
)
private fun fetchedChipsFail(model: Model): Update = ElmUpdate(
model.copy(
chips = model.chips.copy(
state = model.chips.state.loadedFailure(""),
collection = model.chips.collection.copy(emptyList())
)
)
)
private fun fetchedChipsSort(model: Model, msg: Msg.Inner.FetchedChipsSort): Update =
ElmUpdate(model.copy(sortState = model.sortState.copy(chips = msg.sort)))
private fun onRetryFetchChipsClicked(model: Model): Update = ElmUpdate(
model.copy(chips = model.chips.copy(state = model.chips.state.Loading)),
commands = setOf(Cmd.FetchChipsList)
)
private fun onChipClicked(model: Model, msg: Msg.Ui.OnChipClicked): Update =
ElmUpdate(model, effects = setOf(Eff.UpdateCurrentSelectedFolder(msg.id)))
private fun onAddNewChipClicked(model: Model): Update = ElmUpdate(
model.copy(isVisibleAddChipDialog = true), effects = setOf(Eff.ShowAddNewChipDialog)
)
private fun onCloseAddChipDialogClicked(model: Model): Update =
ElmUpdate(model = model.copy(isVisibleAddChipDialog = false))
private fun onBottomBarSettingsClicked(model: Model): Update =
ElmUpdate(model, effects = setOf(Eff.NavigateToSettings))
private fun onBottomBarFoldersClicked(model: Model): Update {
val selectedList = model.notes.collection.data.filter { it.isSelected }
val passedNotesIds = if (selectedList.isNotEmpty() && model.notes.isSelection)
selectedList.map { it.id } else emptyList()
return ElmUpdate(model, effects = setOf(Eff.NavigateToFolders(passedNotesIds)))
}
private fun onSearchBarGridViewClicked(
model: Model,
msg: Msg.Ui.OnChangeGridViewClicked
): Update = ElmUpdate(
model.copy(
sortState = model.sortState.copy(
notes = model.sortState.notes.copy(gridCount = msg.count)
)
),
commands = setOf(Cmd.UpdateNotesGrid(msg.count))
)
private fun onBottomBarSortNotesClicked(model: Model): Update = ElmUpdate(
model.copy(
modalSheet = model.modalSheet.copy(
isVisible = true, content = ModalSheetContent.SORT_NOTES
)
)
)
private fun onBottomBarTrashClicked(model: Model): Update =
ElmUpdate(model, effects = setOf(Eff.NavigateToTrash))
private fun onBottomBarPinSelectedClicked(model: Model): Update = ElmUpdate(
model = model.copy(
notes = model.notes.copy(collection = model.notes.collection.unselectAll())
),
commands = setOf(
Cmd.UpdatePinnedNotes(model.notes.collection.data.filter { it.isSelected })
)
)
private fun onBottomBarMoveSelectedClicked(model: Model): Update {
val selectedList = model.notes.collection.data.filter { it.isSelected }
val passedNotesIds = if (selectedList.isNotEmpty() && model.notes.isSelection)
selectedList.map { it.id } else emptyList()
return ElmUpdate(
model.copy(
notes = model.notes.copy(
isSelection = false, collection = model.notes.collection.unselectAll()
),
searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed),
editNoteFabState = model.editNoteFabState.copy(isVisible = true),
),
effects = setOf(Eff.NavigateToFolders(passedNotesIds))
)
}
private fun onBottomBarRemoveSelectedClicked(model: Model): Update {
val selectedList = model.notes.collection.data.filter { it.isSelected }
return ElmUpdate(
model.copy(
notes = model.notes.copy(
state = model.notes.state.copy(
isLoading = selectedList.count() >= MINIMAL_FOR_LOADING_ITEMS_COUNT
),
collection = model.notes.collection.unselectAll(),
removedList = selectedList,
isSelection = false,
),
searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed),
editNoteFabState = model.editNoteFabState.copy(isVisible = true)
),
commands = setOf(Cmd.RemoveSelectedNotes(selectedList.toList())),
effects = setOf(
Eff.ShowSnackBar(
SnackBarKey.REMOVED_NOTES, message = "${selectedList.count()}"
)
)
)
}
private fun hiddenModalBottomSheet(model: Model): Update = ElmUpdate(
model.copy(
modalSheet = model.modalSheet.copy(
isVisible = false, content = ModalSheetContent.NOTHING
)
)
)
private fun onCollapseSearchBar(model: Model): Update = ElmUpdate(
model.copy(
searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed),
editNoteFabState = model.editNoteFabState.copy(
isVisible = !model.notes.isSelection, state = EditNoteFabState.COLLAPSED
)
)
)
private fun onExpandSearchBar(model: Model): Update = ElmUpdate(
model.copy(
searchBarState = model.searchBarState.copy(barState = SearchBarState.Expanded),
editNoteFabState = model.editNoteFabState.copy(
isVisible = false, state = EditNoteFabState.COLLAPSED
),
)
)
private fun onCounterBarShareClicked(model: Model): Update = ElmUpdate(model)
private fun onCounterBarSelectAllClicked(
model: Model,
msg: Msg.Ui.OnCounterBarSelectAllClicked
): Update {
val byFolder = model.notes.collection.data.filter { it.folderId == msg.currentFolderId }
val allSelected = byFolder.all { it.isSelected }
val notes = model.notes.collection.data.map { item ->
if (msg.currentFolderId == STICKY_START_FOLDER_ID) {
item.copy(isSelected = !model.notes.collection.data.all { it.isSelected })
} else {
val isSelected = if (byFolder.contains(item)) !allSelected else item.isSelected
item.copy(isSelected = isSelected)
}
}
val selectedList = notes.filter { it.isSelected }
val isVisibleUnpinButton = selectedList.isNotEmpty().run {
if (this) !selectedList.map { it.style.isPinned }.contains(false) else false
}
return ElmUpdate(
model.copy(
notes = model.notes.copy(
collection = model.notes.collection.copy(notes),
isVisibleUnpinBottomBarIcon = isVisibleUnpinButton
),
searchBarState = model.searchBarState.copy(
counterValue = notes.count { it.isSelected }
)
)
)
}
private fun onSnackBarUndoRemoveClicked(model: Model): Update {
val restored = model.notes.removedList.map { note -> note.copy(isMovedToTrash = false) }
val isShowLoading = restored.count() >= MINIMAL_FOR_LOADING_ITEMS_COUNT
return ElmUpdate(
model.copy(
notes = model.notes.copy(
state = model.notes.state.copy(isLoading = isShowLoading),
isSelection = false,
collection = model.notes.collection.copy(
model.notes.collection.data.map { it.copy(isSelected = false) }
)
),
searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed)
),
commands = setOf(Cmd.UndoRemoveNotes(restored))
)
}
private fun updatedEditNoteFabState(
model: Model,
msg: Msg.Inner.UpdatedEditNoteFabState
): Update {
val searchBarState = if (msg.state.isExpanded)
model.searchBarState.copy(barState = SearchBarState.Collapsed)
else model.searchBarState
return ElmUpdate(
model.copy(
searchBarState = searchBarState,
editNoteFabState = model.editNoteFabState.copy(
isVisible = !model.notes.isSelection, state = msg.state
)
),
)
}
private fun resetCurrentSelectedFolder(model: Model): Update =
ElmUpdate(model, effects = setOf(Eff.UpdateCurrentSelectedFolder(1L)))
private fun navigatedToHiddenNotes(model: Model): Update {
val selectedList = model.notes.collection.data.filter { it.isSelected }
val hiddenNotes =
if (selectedList.isNotEmpty() && model.notes.isSelection) selectedList else emptyList()
return ElmUpdate(
model.copy(
notes = model.notes.copy(
isSelection = false, collection = model.notes.collection.unselectAll()
),
searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed),
editNoteFabState = model.editNoteFabState.copy(isVisible = true),
isVisibleHiddenNotesDialog = false,
isVisibleAddChipDialog = false
),
commands = setOf(Cmd.HideSelectedNotes(hiddenNotes)),
effects = setOf(Eff.NavigateToHiddenNotes)
)
}
private fun onBottomBarHideSelectedClicked(model: Model): Update {
val unselectedAll = model.notes.collection.copy(
model.notes.collection.data.map { it.copy(isSelected = false) }
)
val selectedList = model.notes.collection.data.filter { it.isSelected }
val hiddenNotes =
if (selectedList.isNotEmpty() && model.notes.isSelection) selectedList else emptyList()
return ElmUpdate(
model = model.copy(
notes = model.notes.copy(isSelection = false, collection = unselectedAll),
searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed),
editNoteFabState = model.editNoteFabState.copy(isVisible = true),
),
commands = setOf(Cmd.TryHideSelectedNotes(hiddenNotes))
)
}
private fun updatedHiddenNotesDialogVisibility(
model: Model,
msg: Msg.Inner.UpdatedHiddenNotesDialogVisibility
): Update = ElmUpdate(model.copy(isVisibleHiddenNotesDialog = msg.isVisible))
}
| 0 |
Kotlin
|
0
| 0 |
863585ab17882e444060e5535401c728f9fc335d
| 18,644 |
Beresta
|
MIT License
|
konvert-processor/src/main/kotlin/me/hubertus248/konvert/processor/model/ConvertibleProperty.kt
|
HubertBalcerzak
| 373,667,306 | false | null |
package me.hubertus248.konvert.processor.model
import com.squareup.kotlinpoet.CodeBlock
interface ConvertibleProperty {
val property: KotlinProperty
fun getBlock(): CodeBlock
}
data class SimpleConvertibleProperty(
override val property: KotlinProperty,
val konverter: KonverterDefinition.Generated
) : ConvertibleProperty {
override fun getBlock(): CodeBlock = konverter.getBlock(property.name)
}
data class ConvertibleIterableProperty(
override val property: KotlinProperty,
val konverter: KonverterDefinition.Predefined
) : ConvertibleProperty {
override fun getBlock(): CodeBlock = konverter.getBlock(property.name)
}
| 0 |
Kotlin
|
0
| 4 |
172a92317a3c16f82e19bac6e0d2ea3b0600bb38
| 662 |
konvert
|
Apache License 2.0
|
libs/storage/src/main/java/com/ericafenyo/libs/storage/EncryptedPreferences.kt
|
ericafenyo
| 309,510,894 | false |
{"Kotlin": 708479, "Java": 21815, "Ruby": 1118, "Shell": 180}
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2021 TransWay
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.ericafenyo.libs.storage
import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV
import androidx.security.crypto.EncryptedSharedPreferences.PrefValueEncryptionScheme
import androidx.security.crypto.MasterKey.Builder
import androidx.security.crypto.MasterKey.KeyScheme.AES256_GCM
import com.ericafenyo.libs.serialization.KotlinJsonSerializer
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.reflect.KClass
interface EncryptedPreferences : Storage
@Singleton
internal class EncryptedPreferencesImpl @Inject constructor(
@ApplicationContext private val context: Context,
) : EncryptedPreferences {
private val masterKey = Builder(context, ENCRYPTED_PREFERENCES_KEY_ALIAS)
.setKeyScheme(AES256_GCM)
.build()
private val preferences: SharedPreferences by lazy {
EncryptedSharedPreferences.create(
context, ENCRYPTED_PREFERENCES_FILE_NAME, masterKey,
AES256_SIV,
PrefValueEncryptionScheme.AES256_GCM
)
}
override fun store(key: String, value: Long) {
preferences.edit { putLong(key, value) }
}
override fun store(key: String, value: Int) {
preferences.edit { putInt(key, value) }
}
override fun store(key: String, value: String) {
preferences.edit { putString(key, value) }
}
override fun store(key: String, value: Boolean) {
preferences.edit { putBoolean(key, value) }
}
override fun <T : Any> store(key: String, value: T) {
val serializer = KotlinJsonSerializer.getInstance()
val json = serializer.toJson(value, value.javaClass)
store(key, json)
}
override fun retrieveLong(key: String): Long? {
val result = preferences.getLong(key, -1L)
return if (result != -1L) result else null
}
override fun retrieveString(key: String): String? {
return preferences.getString(key, null)
}
override fun retrieveInteger(key: String): Int? {
val result = preferences.getInt(key, -1)
return if (result != -1) result else null
}
override fun retrieveBoolean(key: String): Boolean {
return preferences.getBoolean(key, false)
}
override fun <T : Any> retrieve(key: String, clazz: KClass<T>): T? {
val serializer = KotlinJsonSerializer.getInstance()
val json = retrieveString(key) ?: return null
@Suppress("UNCHECKED_CAST")
return serializer.fromJson(json, clazz) as T
}
override fun remove(key: String) {
preferences.edit { remove(key) }
}
override fun clear() {
preferences.edit { clear() }
}
companion object {
private const val ENCRYPTED_PREFERENCES_KEY_ALIAS = "ENCRYPTED_PREFERENCES_KEY_ALIAS"
private const val ENCRYPTED_PREFERENCES_FILE_NAME = "encrypted_preferences_file"
}
}
| 22 |
Kotlin
|
0
| 1 |
053d41da4a7f90b4e4bb53a56b70a73f4642e45d
| 4,094 |
bike-diary
|
MIT License
|
app/src/main/java/com/lateinit/rightweight/data/database/entity/ExerciseSet.kt
|
boostcampwm-2022
| 563,132,819 | false |
{"Kotlin": 320392}
|
package com.lateinit.rightweight.data.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.PrimaryKey
@Entity(
tableName = "exercise_set",
foreignKeys = [
ForeignKey(
entity = Exercise::class,
parentColumns = ["exercise_id"],
childColumns = ["exercise_id"],
onDelete = CASCADE
)
]
)
data class ExerciseSet(
@PrimaryKey
@ColumnInfo(name = "set_id")
val setId: String,
@ColumnInfo(name = "exercise_id")
val exerciseId: String,
@ColumnInfo(name = "weight")
val weight: String,
@ColumnInfo(name = "count")
val count: String,
@ColumnInfo(name = "order")
val order: Int
)
| 6 |
Kotlin
|
0
| 27 |
ff6116ee9e49bd8ed493d3c6928d0b9a7f892689
| 803 |
android09-RightWeight
|
MIT License
|
app/src/main/java/com/lateinit/rightweight/data/database/entity/ExerciseSet.kt
|
boostcampwm-2022
| 563,132,819 | false |
{"Kotlin": 320392}
|
package com.lateinit.rightweight.data.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.PrimaryKey
@Entity(
tableName = "exercise_set",
foreignKeys = [
ForeignKey(
entity = Exercise::class,
parentColumns = ["exercise_id"],
childColumns = ["exercise_id"],
onDelete = CASCADE
)
]
)
data class ExerciseSet(
@PrimaryKey
@ColumnInfo(name = "set_id")
val setId: String,
@ColumnInfo(name = "exercise_id")
val exerciseId: String,
@ColumnInfo(name = "weight")
val weight: String,
@ColumnInfo(name = "count")
val count: String,
@ColumnInfo(name = "order")
val order: Int
)
| 6 |
Kotlin
|
0
| 27 |
ff6116ee9e49bd8ed493d3c6928d0b9a7f892689
| 803 |
android09-RightWeight
|
MIT License
|
cache/src/jvmTest/kotlin/com/motorro/rxlcemodel/cache/CacheDelegateSerializerDeserializerTest.kt
|
motorro
| 172,682,449 | false |
{"Kotlin": 323907, "Dockerfile": 3863}
|
/*
* Copyright 2022 <NAME>.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.motorro.rxlcemodel.cache
import com.motorro.rxlcemodel.cache.entity.Entity
import com.motorro.rxlcemodel.cache.entity.EntityValidator
import com.motorro.rxlcemodel.cache.entity.EntityValidatorFactory
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import kotlin.test.*
class CacheDelegateSerializerDeserializerTest {
companion object {
private val ENTITY = Entity.Impl("String", EntityValidator.Always)
}
private lateinit var validatorFactory: EntityValidatorFactory
private lateinit var objectStream: CacheDelegateSerializerDeserializer.WithObjectStream<String>
@BeforeTest
fun init() {
validatorFactory = mock()
whenever(validatorFactory.createSnapshot(any())).thenReturn(EntityValidator.Always)
objectStream = CacheDelegateSerializerDeserializer.WithObjectStream(validatorFactory, String::class.java)
}
@Test
fun serializesToObjectStream() {
val sOut = ByteArrayOutputStream()
objectStream.serialize(ENTITY, sOut)
assertTrue { sOut.size() > 0 }
val sIn = ByteArrayInputStream(sOut.toByteArray())
assertEquals(
ENTITY,
objectStream.deserializeSnapshot(sIn, sOut.size().toLong(), false)
)
}
@Test
fun ifInvalidatedCreatesInvalidEntity() {
val sOut = ByteArrayOutputStream()
objectStream.serialize(ENTITY, sOut)
assertTrue { sOut.size() > 0 }
val sIn = ByteArrayInputStream(sOut.toByteArray())
assertFalse { objectStream.deserializeSnapshot(sIn, sOut.size().toLong(), true)!!.isValid() }
}
@Test
fun ifDeserializationFailsReturnsNull() {
val sIn = ByteArrayInputStream(emptyArray<Byte>().toByteArray())
assertNull(objectStream.deserializeSnapshot(sIn, 0L, false))
}
@Test
fun ifValidatorFactoryFailsReturnsNull() {
val sOut = ByteArrayOutputStream()
objectStream.serialize(ENTITY, sOut)
assertTrue { sOut.size() > 0 }
val sIn = ByteArrayInputStream(sOut.toByteArray())
whenever(validatorFactory.createSnapshot(any())).thenAnswer {
throw Exception("Error")
}
assertNull(objectStream.deserializeSnapshot(sIn, sOut.size().toLong(), false))
}
}
| 2 |
Kotlin
|
0
| 5 |
1bb0f2851cab558e52eff8c73e2be1080a5347e3
| 3,010 |
RxLceModel
|
Apache License 2.0
|
example_mod_1_14_4/src/main/java/sharkbound/forge/firstmod/gui/screen/RepulserScreen.kt
|
sharkbound
| 247,764,906 | false | null |
package sharkbound.forge.firstmod.gui.screen
import com.mojang.blaze3d.platform.GlStateManager
import net.minecraft.client.gui.screen.inventory.ContainerScreen
import net.minecraft.client.gui.widget.button.AbstractButton
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.inventory.container.Container
import net.minecraft.inventory.container.INamedContainerProvider
import net.minecraft.util.ResourceLocation
import net.minecraft.util.text.ITextComponent
import sharkbound.commonutils.extensions.max
import sharkbound.forge.firstmod.MOD_ID
import sharkbound.forge.firstmod.gui.container.RepulserContainer
import sharkbound.forge.firstmod.items.Repulser
import sharkbound.forge.shared.extensions.item
import sharkbound.forge.shared.extensions.send
import sharkbound.forge.shared.util.asText
import sharkbound.forge.shared.util.imageButton
class RepulserScreen(container: RepulserContainer, val inv: PlayerInventory) : ContainerScreen<RepulserContainer>(container, inv, asText(TITLE)), INamedContainerProvider {
companion object {
const val TITLE = "&6Repulser Settings"
val GUI_TEXTURE = ResourceLocation(MOD_ID, "textures/gui/repulser/repulser.png")
val BUTTON_TEXTURE = ResourceLocation(MOD_ID, "textures/gui/repulser/button.png")
}
val player = inv.player
val addRangeButton = addButton(imageButton(0, 0, 25, 22, 0, 0, 0, BUTTON_TEXTURE) {
player.item.stack.let {
Repulser.setRadius(it, Repulser.radiusOf(it) + 10)
val newRadius = Repulser.radiusOf(it)
player.send("&aRadius updated to $newRadius")
Repulser.sendRadiusPacket(player.uniqueID, newRadius)
}
})
val subRangeButton = addButton(imageButton(0, 0, 25, 22, 25, 0, 0, BUTTON_TEXTURE) {
player.item.stack.let {
Repulser.setRadius(it, (Repulser.radiusOf(it) - 10) max 0)
val newRadius = Repulser.radiusOf(it)
player.send("&aRadius updated to $newRadius")
Repulser.sendRadiusPacket(player.uniqueID, newRadius)
}
})
override fun mouseClicked(x: Double, y: Double, k: Int): Boolean {
addRangeButton.clickIfHovered(x, y)
subRangeButton.clickIfHovered(x, y)
return super.mouseClicked(x, y, k)
}
override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) {
GlStateManager.color4f(1f, 1f, 1f, 1f)
minecraft!!.textureManager.bindTexture(GUI_TEXTURE)
blit(guiLeft, guiTop, 0, 0, xSize, ySize)
}
override fun render(mx: Int, my: Int, partialTicks: Float) {
minecraft!!.textureManager.bindTexture(GUI_TEXTURE)
addRangeButton.setPosition(guiLeft + 20, guiTop + 10)
subRangeButton.setPosition(guiLeft + 60, guiTop + 10)
super.render(mx, my, partialTicks)
addRangeButton.render(mx, my, partialTicks)
subRangeButton.render(mx, my, partialTicks)
renderHoveredToolTip(mx, my)
}
override fun createMenu(id: Int, inv: PlayerInventory, player: PlayerEntity): Container? {
return RepulserContainer(id, inv, player)
}
override fun getDisplayName(): ITextComponent =
asText(TITLE)
}
fun AbstractButton.clickIfHovered(x: Double, y: Double) {
if (isHovered) {
onClick(x, y)
}
}
| 0 |
Kotlin
|
0
| 0 |
3302ac118d6ed9da341b74c25e13edcc4e29a040
| 3,380 |
forge-projects
|
MIT License
|
src/main/kotlin/io/glossnyx/vibes/network/packet/ChangePositionBlock.kt
|
glossnyx
| 326,897,322 | false | null |
package io.glossnyx.vibes.network.packet
import io.glossnyx.vibes.Vibes
import net.minecraft.network.PacketByteBuf
import net.minecraft.util.math.BlockPos
import java.util.UUID
data class ChangePositionBlock(val uuid: UUID, val blockPos: BlockPos) : Packet {
companion object : PacketCompanion {
override val id = Vibes.id("change-position-block")
override fun fromBuf(buf: PacketByteBuf) = ChangePositionBlock(
buf.readUuid(),
buf.readBlockPos()
)
}
override val buffer = createPacket {
writeUuid(uuid)
writeBlockPos(blockPos)
}
}
| 0 |
Java
|
0
| 1 |
52ca8fca6e0fed9753cd94b757c2954f222d6d68
| 555 |
vibes
|
MIT License
|
app/src/main/java/com/example/doggypediaapp/repository/BreedsListRepository.kt
|
simonklejnstrup
| 536,015,933 | false |
{"Kotlin": 31248}
|
package com.example.doggypediaapp.repository
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.doggypediaapp.api.ApiInterface
import com.example.doggypediaapp.ui.list.BreedsListRetroResponse
import kotlinx.coroutines.*
import retrofit2.HttpException
class BreedsListRepository {
private var mutableLiveData = MutableLiveData<BreedsListRetroResponse>()
val completableJob = Job()
private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)
private val TAG = "BreedsListRepository"
private val service by lazy {
ApiInterface.create()
}
fun getMutableLiveData(): MutableLiveData<BreedsListRetroResponse> {
coroutineScope.launch {
val request = service.getBreedsList()
withContext(Dispatchers.Main) {
try {
if (request.body() != null) {
Log.d(TAG, request.body().toString())
mutableLiveData.value = request.body()!!
}
} catch (e: HttpException) {
Log.d(TAG, e.toString())
} catch (e: Throwable) {
Log.d(TAG, e.toString())
}
}
}
return mutableLiveData;
}
}
| 0 |
Kotlin
|
0
| 0 |
aeca34b1a242e5dd25e4bd9626354057b61e0d54
| 1,305 |
DoggypediaApp
|
MIT License
|
src/main/kotlin/parsers/expressionparts/ExpressionParts.kt
|
nybble16
| 733,939,836 | false |
{"Kotlin": 10068}
|
package com.tomaszz.parsers.expressionparts
import com.tomaszz.parsers.parsers.*
data class CronExpression(val minute: ExpressionPart, val hour: ExpressionPart, val dayOfMonth: ExpressionPart, val month: ExpressionPart, val dayOfWeek: ExpressionPart, val command: String) {
override fun toString(): String {
return """
minute ${minute.values.joinToString(" ")}
hour ${hour.values.joinToString(" ")}
day of month ${dayOfMonth.values.joinToString(" ")}
month ${month.values.joinToString(" ")}
day of week ${dayOfWeek.values.joinToString(" ")}
command $command
""".trimIndent()
}
companion object {
private const val MINUTE_RANGE_MAX = 60
private const val HOUR_RANGE_MAX = 24
private const val DAY_OF_MONTH_MAX = 32
private const val MONTH_MAX = 13
private const val DAY_OF_WEEK_MAX = 8
fun parse(input: String): CronExpression {
val inputSplit = input.split(" ").also {
if (it.size != 6) throw UnparsableExpressionException("Expected 6 parts, got ${it.size}.")
}
val minuteExpr = ExpressionPart.parse(inputSplit[0], 0, MINUTE_RANGE_MAX)
val hourExpr = ExpressionPart.parse(inputSplit[1], 0, HOUR_RANGE_MAX)
val dayOfMonth = ExpressionPart.parse(inputSplit[2], 1, DAY_OF_MONTH_MAX)
val month = ExpressionPart.parse(inputSplit[3], 1, MONTH_MAX)
val dayOfWeek = ExpressionPart.parse(inputSplit[4], 1, DAY_OF_WEEK_MAX)
return CronExpression(minuteExpr, hourExpr, dayOfMonth, month, dayOfWeek, inputSplit[5])
}
}
}
data class ExpressionPart(val expression: String, val values: List<Int>) {
companion object {
fun parse(input: String, lowerBound: Int, upperBound: Int): ExpressionPart {
if (isAsteriskExpression(input)) return ExpressionPart(input, parseAsterisk(input, lowerBound, upperBound))
if (isCommaSeparatedExpression(input)) return ExpressionPart(input, parseCommaSeparated(input, lowerBound, upperBound))
if (isRangeExpression(input)) return ExpressionPart(input, parseRange(input, lowerBound, upperBound))
throw UnparsableExpressionException("Invalid input: $input")
}
}
}
class UnparsableExpressionException(message: String) : IllegalArgumentException(message)
| 0 |
Kotlin
|
0
| 0 |
db59008652ed4d47a7ff65dd285aa08315fe2fab
| 2,453 |
olx-cron-expression
|
MIT License
|
tokisaki-server/src/main/kotlin/io/micro/server/dict/infra/repository/SystemDictRepository.kt
|
spcookie
| 730,690,607 | false |
{"Kotlin": 224366, "Java": 21819}
|
package io.micro.server.dict.infra.repository
import io.micro.core.rest.Pageable
import io.micro.core.util.converter
import io.micro.server.dict.domain.model.entity.SystemDictDO
import io.micro.server.dict.domain.repository.ISystemDictRepository
import io.micro.server.dict.infra.converter.SystemDictConverter
import io.micro.server.dict.infra.dao.ISystemDictDAO
import io.quarkus.panache.common.Page
import io.smallrye.mutiny.Uni
import jakarta.enterprise.context.ApplicationScoped
@ApplicationScoped
class SystemDictRepository(
private val systemDictDAO: ISystemDictDAO,
private val systemDictConverter: SystemDictConverter
) : ISystemDictRepository {
override fun findSystemDictByKeyLike(keyword: String, pageable: Pageable): Uni<List<SystemDictDO>> {
val page = Page.of(pageable.current - 1, pageable.limit)
return systemDictDAO.selectByKeyLike(keyword, page)
.map { it.converter(systemDictConverter::systemDictEntity2SystemDictDO) }
}
override fun findSystemDict(pageable: Pageable): Uni<List<SystemDictDO>> {
val page = Page.of(pageable.current - 1, pageable.limit)
return systemDictDAO.findAll()
.page(page).list()
.map { it.converter(systemDictConverter::systemDictEntity2SystemDictDO) }
}
override fun countSystemDict(): Uni<Long> {
return systemDictDAO.findAll().count()
}
override fun countSystemDictByKeyLike(keyword: String): Uni<Long> {
return systemDictDAO.countByKeyLike(keyword)
}
override fun findById(id: Long): Uni<SystemDictDO> {
return systemDictDAO.findById(id).map(systemDictConverter::systemDictEntity2SystemDictDO)
}
override fun updateById(systemDictDO: SystemDictDO): Uni<SystemDictDO> {
val id = systemDictDO.id
return if (id == null) {
Uni.createFrom().item(systemDictDO)
} else {
systemDictDAO.findById(id)
.invoke { entity ->
systemDictConverter.systemDictDO2SystemDictEntity(systemDictDO, entity)
}.replaceWith(systemDictDO)
}
}
override fun save(systemDictDO: SystemDictDO): Uni<SystemDictDO> {
return systemDictDAO.persist(
systemDictConverter.systemDictDO2SystemDictEntity(systemDictDO.also { it.id = null })
)
.map(systemDictConverter::systemDictEntity2SystemDictDO)
}
override fun findByKey(key: String): Uni<SystemDictDO> {
return systemDictDAO.selectByKey(key)
.map(systemDictConverter::systemDictEntity2SystemDictDO)
}
}
| 0 |
Kotlin
|
0
| 0 |
a0fb4013d85fc51e83754b2f0a21fe0920d71a8d
| 2,604 |
Tokisaki
|
Apache License 2.0
|
domain/src/main/kotlin/com/seanshubin/summarize/disk/storage/domain/Summary.kt
|
SeanShubin
| 703,224,958 | false |
{"Kotlin": 20909, "Shell": 808}
|
package com.seanshubin.summarize.disk.storage.domain
import java.nio.file.Path
data class Summary(
val path: Path,
val size: Long,
val files: Int,
val dirs: Int
) {
fun aggregateChild(child: Summary): Summary = Summary(
path,
size = size + child.size,
files = files + child.files,
dirs = dirs + child.dirs
)
companion object {
fun compose(parent: Path, children: List<Summary>): Summary {
val initial = Summary(parent, size = 0, files = 0, dirs = 1)
return children.fold(initial) { accumulator, child ->
accumulator.aggregateChild(child)
}
}
}
}
| 0 |
Kotlin
|
1
| 0 |
08c2651ca0cf9181506be46f70e73a6518c8b21a
| 681 |
summarize-disk-storage
|
The Unlicense
|
app/src/main/kotlin/ui/EntryViewModel.kt
|
takuji31
| 328,317,965 | false |
{"Kotlin": 105591}
|
package jp.takuji31.compose.navigation.example.ui
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import jp.takuji31.compose.navigation.example.model.Blog
import jp.takuji31.compose.navigation.example.model.Entry
import jp.takuji31.compose.navigation.example.navigation.ExampleScreen
import jp.takuji31.compose.navigation.example.repository.BlogRepository
import jp.takuji31.compose.navigation.example.repository.EntryRepository
import jp.takuji31.compose.navigation.screen.screen
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class EntryViewModel @Inject constructor(
private val blogRepository: BlogRepository,
private val entryRepository: EntryRepository,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val screen: ExampleScreen.Entry by savedStateHandle.screen()
private val _state = MutableStateFlow<State>(State.Loading)
val state: StateFlow<State>
get() = _state
init {
viewModelScope.launch {
load()
}
}
private suspend fun load() {
_state.value = State.Loading
val blog = blogRepository.getBlogById(screen.blogId)
val entry = entryRepository.getEntryById(screen.blogId, screen.entryId)
_state.value = State.Loaded(blog, entry)
}
fun reload() {
viewModelScope.launch { load() }
}
sealed class State {
object Loading : State()
data class Loaded(val blog: Blog, val entry: Entry) : State()
}
}
| 14 |
Kotlin
|
4
| 6 |
f56818bc3c46f7f814fcf5b75c3b631b6b4e2522
| 1,711 |
navigation-compose-screen
|
Apache License 2.0
|
app/src/main/java/com/fmt/compose/news/model/MovieModel.kt
|
fmtjava
| 376,556,406 | false | null |
package com.fmt.compose.news.model
class MovieModel(val itemList: List<MovieItemModel> = listOf())
class MovieItemModel(
val data: MovieItem
)
class MovieItem(
val category: String,
val playUrl: String,
val title: String,
val cover: Cover,
val duration: Int
)
class Cover(val feed: String)
| 1 |
Kotlin
|
13
| 66 |
ef94d98ab385cbb02891d8ed9d9c65d4879524aa
| 318 |
Jetpack_Compose_News
|
MIT License
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DateString.kt
|
Danilo-Araujo-Silva
| 271,904,885 | false | null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: DateString
*
* Full name: System`DateString
*
* DateString[] gives a string representing the complete current local date and time.
* DateString["elem"] gives the specified element or format for date and time.
* DateString[{"elem ", "elem ", โฆ}] concatenates the specified elements in the order given.
* 1 2
* DateString[{y, m, d, h, m, s}] gives a string corresponding to a DateList specification.
* DateString[time] gives a string corresponding to an AbsoluteTime specification.
* DateString[date] gives a string corresponding to a DateObject specification.
* Usage: DateString[spec, elems] gives elements elems of the date or time specification spec.
*
* DateDelimiters -> Automatic
* Options: TimeZone :> $TimeZone
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/DateString
* Documentation: web: http://reference.wolfram.com/language/ref/DateString.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun dateString(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("DateString", arguments.toMutableList(), options)
}
| 2 |
Kotlin
|
0
| 3 |
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,738 |
mathemagika
|
Apache License 2.0
|
app/src/main/java/com/revolgenx/anilib/staff/StaffMediaRoleHeaderSource.kt
|
AniLibApp
| 244,410,204 | false |
{"Kotlin": 1593083, "Shell": 52}
|
package com.revolgenx.anilib.staff
import android.content.Context
import com.otaliastudios.elements.Page
import com.otaliastudios.elements.Source
import com.otaliastudios.elements.extensions.HeaderSource
import com.revolgenx.anilib.R
import com.revolgenx.anilib.infrastructure.source.StaffMediaRoleSource
import com.revolgenx.anilib.media.data.model.MediaModel
class StaffMediaRoleHeaderSource(private val context: Context) : HeaderSource<MediaModel, String>() {
private var lastHeader: String = ""
override fun dependsOn(source: Source<*>): Boolean {
return source is StaffMediaRoleSource
}
override fun areItemsTheSame(first: Data<MediaModel, String>, second: Data<MediaModel, String>): Boolean {
return first.anchor.id == second.anchor.id
}
override fun computeHeaders(page: Page, list: List<MediaModel>): List<Data<MediaModel, String>> {
val results = arrayListOf<Data<MediaModel, String>>()
val animeStaffRoles = context.getString(R.string.anime_staff_roles)
val mangaStaffRoles = context.getString(R.string.manga_staff_roles)
for (model in list) {
val header = if (model.isAnime) animeStaffRoles else mangaStaffRoles
if (header != lastHeader) {
results.add(Data(model, header))
lastHeader = header
}
}
return results
}
}
| 36 |
Kotlin
|
3
| 76 |
b3caec5c00779c878e4cf22fb7d2034aefbeee54
| 1,390 |
AniLib
|
Apache License 2.0
|
app/src/main/java/com/costular/marvelheroes/presentation/heroedetail/MarvelHeroeDetailActivity.kt
|
JosepCristobal
| 148,382,400 | false | null |
package com.costular.marvelheroes.presentation.heroedetail
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.AppCompatDelegate
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.costular.marvelheroes.R
import com.costular.marvelheroes.data.model.MarvelHero
import com.costular.marvelheroes.data.repository.datasource.LocalDataSource
import com.costular.marvelheroes.domain.model.MarvelHeroEntity
import com.costular.marvelheroes.presentation.MainApp
import kotlinx.android.synthetic.main.activity_hero_detail.*
import javax.inject.Inject
/**
* Created by costular on 18/03/2018.
*/
class MarvelHeroeDetailActivity : AppCompatActivity() {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
lateinit var marvelHeroeDetailViewModel: MarvelHeroeDetailViewModel
companion object {
const val PARAM_HEROE = "heroe"
}
override fun onCreate(savedInstanceState: Bundle?) {
inject()
marvelHeroeDetailViewModel = ViewModelProviders.of(this, viewModelFactory).get(MarvelHeroeDetailViewModel::class.java)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hero_detail)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeButtonEnabled(true)
}
supportPostponeEnterTransition() // Wait for image load and then draw the animation
val hero: MarvelHeroEntity? = intent?.extras?.getParcelable(PARAM_HEROE)
hero?.let { fillHeroData(it) }
val btnShow = findViewById<Button>(R.id.btnSave)
btnShow?.setOnClickListener {
if (hero!=null) {saveReg(hero)
showText()
}}
}
fun inject() {
(application as MainApp).component.injectDetail(this)
}
private fun saveReg(hero: MarvelHeroEntity){
val editText = findViewById<EditText>(R.id.heroEditText).text.toString()
val hero4: List<MarvelHeroEntity> = listOf(
MarvelHeroEntity(hero.id, hero.name, hero.photoUrl,hero.realName,hero.height,hero.power,hero.abilities,editText,hero.groups))
//marvelHeroeDetailViewModel.deleteHeroes(userId)
marvelHeroeDetailViewModel.updateHeroe(hero4)
}
private fun showText() {
val editText = findViewById<EditText>(R.id.heroEditText).text
if (editText != null) {
Toast.makeText(this, "${editText}, SAVE!!", Toast.LENGTH_LONG).show()
onBackPressed()
}
}
private fun fillHeroData(hero: MarvelHeroEntity) {
Glide.with(this)
.load(hero.photoUrl)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
supportStartPostponedEnterTransition()
return false
}
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
supportStartPostponedEnterTransition()
return false
}
})
.into(heroDetailImage)
heroDetailName.text = hero.name
heroDetailRealName.text = hero.realName
heroDetailHeight.text = hero.height
heroDetailPower.text = hero.power
heroDetailAbilities.text = hero.abilities
heroFavourite.text=hero.favourite
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when(item?.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
817f7eb7739af744157e7a52e894757545a79774
| 4,275 |
Pt3-Marver-Super-Heroes
|
MIT License
|
pipesample/src/main/java/com/udeyrishi/pipesample/App.kt
|
udeyrishi
| 131,472,826 | false | null |
package com.udeyrishi.pipesample
import android.app.Application
import com.udeyrishi.pipe.Job
import com.udeyrishi.pipe.repository.InMemoryRepository
import com.udeyrishi.pipe.repository.MutableRepository
class App : Application() {
companion object {
lateinit var INSTANCE: App
private set
}
val jobsRepo: MutableRepository<Job<*>> = InMemoryRepository()
override fun onCreate() {
super.onCreate()
INSTANCE = this
}
override fun onTerminate() {
jobsRepo.apply {
items.forEach { (job, _, _) -> job.interrupt() }
clear()
close()
}
super.onTerminate()
}
}
| 2 |
Kotlin
|
1
| 4 |
307778d035c1f47d12ad1a10f288ea3e44491d93
| 683 |
pipe
|
MIT License
|
geary-papermc-features/src/main/kotlin/com/mineinabyss/geary/papermc/features/common/actions/SmiteAction.kt
|
MineInAbyss
| 592,086,123 | false |
{"Kotlin": 245944}
|
package com.mineinabyss.geary.papermc.features.common.actions
import com.mineinabyss.geary.actions.Action
import com.mineinabyss.geary.actions.ActionGroupContext
import com.mineinabyss.geary.actions.expressions.Expression
import kotlinx.serialization.Contextual
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.bukkit.Location
@Serializable
@SerialName("geary:smite")
class SmiteAction(
val at: Expression<@Contextual Location>,
) : Action {
override fun ActionGroupContext.execute() {
eval(at).world.strikeLightning(eval(at))
}
}
| 1 |
Kotlin
|
0
| 4 |
f765a15878512d314808f8622cd54dc85ed12beb
| 597 |
geary-papermc
|
MIT License
|
app/src/main/java/com/fanrong/frwallet/found/ViewmodelInter.kt
|
iamprivatewallet
| 464,003,911 | false |
{"JavaScript": 2822760, "Kotlin": 1140535, "Java": 953177, "HTML": 17003}
|
//package com.fanrong.frwallet.found
//
//import com.fanrong.frwallet.R
//import xc.common.framework.mvvm.BaseLiveData
//import xc.common.framework.mvvm.BaseViewModel
//
//interface ViewmodelInter<R : BaseLiveData, T : BaseViewModel<R>> {
// var viewmodel: T
// fun getViewModel(): T
//
// fun init() {
// viewmodel = getViewModel()
// getViewModel().observerDataChange(null, this::onStateChange)
// }
//
// fun onStateChange(state: T){
//
// }
//}
| 0 |
JavaScript
|
0
| 1 |
be8003e419afbe0429f2eb3fd757866e2e4b9152
| 480 |
PrivateWallet.Android
|
MIT License
|
j2k/tests/testData/ast/objectLiteral/MyFrame.kt
|
craastad
| 18,462,025 | false |
{"Markdown": 18, "XML": 405, "Ant Build System": 23, "Ignore List": 7, "Maven POM": 34, "Kotlin": 10194, "Java": 3675, "CSS": 10, "Shell": 6, "Batchfile": 6, "Java Properties": 9, "Gradle": 61, "INI": 6, "JavaScript": 42, "HTML": 77, "Text": 875, "Roff": 53, "Roff Manpage": 8, "JFlex": 3, "JAR Manifest": 1, "Protocol Buffer": 2}
|
package demo
open class WindowAdapter() {
public open fun windowClosing() {
}
}
public class Client() : Frame() {
{
var a: WindowAdapter? = object : WindowAdapter() {
override fun windowClosing() {
}
}
addWindowListener(a)
addWindowListener(object : WindowAdapter() {
override fun windowClosing() {
}
})
}
}
| 1 | null |
1
| 1 |
f41f48b1124e2f162295718850426193ab55f43f
| 413 |
kotlin
|
Apache License 2.0
|
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/SettingsSuggestRounded.kt
|
karakum-team
| 387,062,541 | false |
{"Kotlin": 3058356, "TypeScript": 2249, "HTML": 724, "CSS": 86}
|
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/SettingsSuggestRounded")
package mui.icons.material
@JsName("default")
external val SettingsSuggestRounded: SvgIconComponent
| 0 |
Kotlin
|
5
| 35 |
f8b65644caf9131e020de00a02718f005a84b45d
| 208 |
mui-kotlin
|
Apache License 2.0
|
app/src/main/java/pl/gmat/users/feature/details/ui/widget/UserDetailsBindingAdapters.kt
|
gmatyszczak
| 244,174,218 | false |
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 54, "XML": 18, "Java": 1}
|
package pl.gmat.users.feature.details.ui.widget
import android.widget.TextView
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import pl.gmat.users.common.model.Address
import pl.gmat.users.common.model.Gender
@BindingAdapter("genderText")
fun genderText(textView: TextView, gender: Gender?) {
gender?.let {
textView.text = textView.context.getString(it.nameResId)
}
}
@BindingAdapter("addressesList")
fun setAddressesList(recyclerView: RecyclerView, addresses: List<Address>?) {
if (addresses != null) {
(recyclerView.adapter as? AddressesAdapter)?.submitList(addresses)
}
}
| 1 | null |
1
| 1 |
b280b0b2796ead293d27a3cac1a4b2530bfcaba0
| 654 |
users-sample
|
Apache License 2.0
|
src/main/kotlin/com/timepath/hl2/io/demo/SignonState.kt
|
SourceUtils
| 9,677,599 | false |
{"Kotlin": 271789}
|
package com.timepath.hl2.io.demo
public enum class SignonState(val i: Int) {
/** No state yet; about to connect */
NONE(0),
/** Client challenging server; all OOB packets */
CHALLENGE(1),
/** Client is connected to server; netchans ready */
CONNECTED(2),
/** Just got serverinfo and string tables */
NEW(3),
/** Received signon buffers */
PRESPAWN(4),
/** Ready to receive entity packets */
SPAWN(5),
/** Fully connected; first non-delta packet received */
FULL(6),
/** Server is changing level; please wait */
CHANGELEVEL(7);
companion object {
fun get(i: Int) = values().firstOrNull { it.i == i }
}
}
| 0 |
Kotlin
|
1
| 3 |
60bd0fbc5a1b59805d0e40e7050b119323e6f393
| 686 |
hl2-toolkit
|
Artistic License 2.0
|
app/src/main/java/dog/snow/androidrecruittest/feature/BindingAdapter.kt
|
trOnk12
| 252,550,688 | false |
{"Kotlin": 57018}
|
package dog.snow.androidrecruittest.feature
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.squareup.picasso.Picasso
import dog.snow.androidrecruittest.R
@BindingAdapter("imageUrl")
fun loadImage(imageView: ImageView, url: String?) {
url?.let{
Picasso.get().load(it).placeholder(R.drawable.ic_placeholder).into(imageView)
}
}
| 0 |
Kotlin
|
0
| 0 |
1fea6aab8ff3838975ae8ac5416a1eda6dbb2383
| 381 |
image-viewer
|
Apache License 2.0
|
src/main/kotlin/me/mocha/spongeplugin/area/model/provider/ConfigAreaProvider.kt
|
namuare
| 325,523,606 | false | null |
package me.mocha.spongeplugin.area.model.provider
import com.google.common.reflect.TypeToken
import me.mocha.spongeplugin.area.AreaSystem
import me.mocha.spongeplugin.area.model.entity.Area
import me.mocha.spongeplugin.area.model.serializer.AreaSerializer
import me.mocha.spongeplugin.area.util.Vector3
class ConfigAreaProvider : AreaProvider {
private val token = TypeToken.of(Area::class.java)
private val config = AreaSystem.getInstance().config
private val configRoot = config.load()
override fun create(id: String, world: String, start: Vector3, end: Vector3): Area {
val created = Area(id, world, start, end)
configRoot.getNode(id).setValue(token, created)
this.save()
return created
}
override fun getById(id: String): Area? {
return configRoot.getNode(id).getValue(token)
}
override fun getAll(): List<Area> {
return configRoot.childrenMap.map { AreaSerializer.deserialize(token, it.value) }
}
private fun save() {
config.save(configRoot)
}
override fun close() {
this.save()
}
}
| 2 |
Kotlin
|
0
| 0 |
74f036c530e36d36b951d0dfb3d5818a29ff8f06
| 1,112 |
AreaSystem
|
MIT License
|
app/src/main/java/com/pkj/learn/asshopping/data/source/local/ProductsDao.kt
|
pkjvit
| 259,707,303 | false | null |
package com.pkj.learn.asshopping.data.source.local
import androidx.lifecycle.LiveData
import androidx.room.*
import com.pkj.learn.asshopping.data.Product
/**
* Data access object for the products table
*
* @author <NAME>
*/
@Dao
interface ProductsDao {
/**
* Observe list of Products
*
* @return all products
*/
@Query("SELECT * FROM Products")
fun observeProducts(): LiveData<List<Product>>
/**
* Select all products from table
*
* @return all products
*/
@Query("SELECT * FROM Products ORDER BY id")
suspend fun getProducts(): List<Product>
@Query("SELECT * FROM Products WHERE id = :productId")
suspend fun getProductById(productId: String): Product?
@Query("SELECT * FROM products WHERE id = :productId")
fun observeProductById(productId: String): LiveData<Product>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertProduct(product: Product)
@Update
suspend fun updateProduct(product: Product)
@Query("UPDATE Products SET likes = :likes WHERE id = :productId")
suspend fun updateProductLike(productId: String, likes: Int)
@Query("UPDATE Products SET offline = :offline WHERE id = :productId")
suspend fun updateProductOffline(productId: String, offline: Int)
}
| 0 |
Kotlin
|
0
| 0 |
6f8e1397fc4e71ab437de2b4ddc6b492bc69bdcc
| 1,308 |
ShoppingApp
|
MIT License
|
domain/src/main/java/com/tiagohs/domain/presenter/contract/HomePresenter.kt
|
tiagohs
| 273,999,200 | false | null |
package com.tiagohs.domain.presenter.contract
import com.tiagohs.domain.presenter.base.IPresenter
import com.tiagohs.domain.views.HomeView
interface HomePresenter: IPresenter {
}
| 0 |
Kotlin
|
1
| 2 |
6b7634ae7c6ceea06e891d4284ecb16f3d598142
| 180 |
script-reader
|
Apache License 2.0
|
presentation/src/test/kotlin/wskim/aos/simpledutch/prod/presentation/HomeWriteViewModelTest.kt
|
tmvlke
| 707,316,658 | false |
{"Kotlin": 149898}
|
package wskim.aos.simpledutch.prod.presentation
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collectIndexed
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.MethodOrderer
import org.junit.jupiter.api.Order
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestMethodOrder
import wskim.aos.domain.proguardSafeZone.vo.DutchListItemVO
import wskim.aos.domain.proguardSafeZone.vo.DutchPersonVO
import wskim.aos.domain.repository.DutchInfoRepository
import wskim.aos.domain.usecase.DutchInfoUseCase
import wskim.aos.simpledutch.core.BaseCoroutineTest
import wskim.aos.hometab.feature.homeInsert.HomeWriteContract
import wskim.aos.hometab.feature.homeInsert.HomeWriteViewModel
@ExperimentalCoroutinesApi
@TestMethodOrder(MethodOrderer.OrderAnnotation::class)
@DisplayName("๋์นํ์ด ๋ฑ๋ก ๋ทฐ๋ชจ๋ธ - ์ ๋ณด ์ ์ฅ ๋ก์ง ํ
์คํธ")
class HomeWriteViewModelTest : BaseCoroutineTest() {
private lateinit var vm: HomeWriteViewModel
private lateinit var dutchInfoUseCase: DutchInfoUseCase
private lateinit var dutchInfoRepository: DutchInfoRepository
private val title = "1์ฐจ ํ์"
private val amount = "100000"
private val enterPersonName = "์ฐธ์ฌ์1"
override fun onStart() {
dutchInfoRepository = mockk()
dutchInfoUseCase = DutchInfoUseCase(dutchInfoRepository = dutchInfoRepository)
vm = HomeWriteViewModel(dutchInfoUseCase = dutchInfoUseCase)
}
override fun onEnd() {}
@Test
@Order(10)
@DisplayName(
"๋์น ํ์ด ์ ๋ณด๋ฅผ ์
๋ ฅ ํ ๋ ๊ฒฝ์ฐ -> " +
"์ง์ถ ๋ด์ฉ๋ง ์
๋ ฅ ๊ฒฝ์ฐ -> " +
"์ถ๊ฐํ๊ธฐ ๋ฒํผ์ด ํ์ฑํ ๋์ง ์๋ ๊ฒ์ด ๋ง๋๊ฐ?"
)
fun t10() = runBlocking {
/***************************************************
* when - ๋์ ์คํ
***************************************************/
vm.viewState.value.title.value = title
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
/***************************************************
* then - ๊ฒฐ๊ณผ ๊ฒ์ฆ
***************************************************/
assertEquals(false, vm.viewState.value.completeButtonEnabled.value)
}
@Test
@Order(11)
@DisplayName(
"๋์น ํ์ด ์ ๋ณด๋ฅผ ์
๋ ฅ ํ ๋ ๊ฒฝ์ฐ -> " +
"์ด ๊ฐ๊ฒฉ๋ง ์
๋ ฅ ๊ฒฝ์ฐ -> " +
"์ถ๊ฐํ๊ธฐ ๋ฒํผ์ด ํ์ฑํ ๋์ง ์๋ ๊ฒ์ด ๋ง๋๊ฐ?"
)
fun t11() = runBlocking {
/***************************************************
* when - ๋์ ์คํ
***************************************************/
vm.viewState.value.amount.value = amount
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
/***************************************************
* then - ๊ฒฐ๊ณผ ๊ฒ์ฆ
***************************************************/
assertEquals(false, vm.viewState.value.completeButtonEnabled.value)
}
@Test
@Order(12)
@DisplayName(
"๋์น ํ์ด ์ ๋ณด๋ฅผ ์
๋ ฅ ํ ๋ ๊ฒฝ์ฐ -> " +
"์ฐธ์ฌ์ ๋ชฉ๋ก๋ง ์
๋ ฅ ๊ฒฝ์ฐ -> " +
"์ถ๊ฐํ๊ธฐ ๋ฒํผ์ด ํ์ฑํ ๋์ง ์๋ ๊ฒ์ด ๋ง๋๊ฐ?"
)
fun t12() = runBlocking {
/***************************************************
* when - ๋์ ์คํ
***************************************************/
vm.viewState.value.enterPersonName.value = enterPersonName
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.setEvent(HomeWriteContract.Event.SaveEnterPersonClicked)
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
/***************************************************
* then - ๊ฒฐ๊ณผ ๊ฒ์ฆ
***************************************************/
assertEquals(false, vm.viewState.value.completeButtonEnabled.value)
}
@Test
@Order(13)
@DisplayName(
"๋์น ํ์ด ์ ๋ณด๋ฅผ ์
๋ ฅ ํ ๋ ๊ฒฝ์ฐ -> " +
"์ง์ถ ๋ด์ฉ ๋ฐ ์ด ๊ฐ๊ฒฉ๋ง ์
๋ ฅ ๊ฒฝ์ฐ -> " +
"์ถ๊ฐํ๊ธฐ ๋ฒํผ์ด ํ์ฑํ ๋์ง ์๋ ๊ฒ์ด ๋ง๋๊ฐ?"
)
fun t13() = runBlocking {
/***************************************************
* when - ๋์ ์คํ
***************************************************/
vm.viewState.value.title.value = title
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.viewState.value.amount.value = amount
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
/***************************************************
* then - ๊ฒฐ๊ณผ ๊ฒ์ฆ
***************************************************/
assertEquals(false, vm.viewState.value.completeButtonEnabled.value)
}
@Test
@Order(14)
@DisplayName(
"๋์น ํ์ด ์ ๋ณด๋ฅผ ์
๋ ฅ ํ ๋ ๊ฒฝ์ฐ -> " +
"์ด ๊ฐ๊ฒฉ ๋ฐ ์ฐธ์ฌ์ ๋ชฉ๋ก๋ง ์
๋ ฅ ๊ฒฝ์ฐ -> " +
"์ถ๊ฐํ๊ธฐ ๋ฒํผ์ด ํ์ฑํ ๋์ง ์๋ ๊ฒ์ด ๋ง๋๊ฐ?"
)
fun t14() = runBlocking {
/***************************************************
* when - ๋์ ์คํ
***************************************************/
vm.viewState.value.amount.value = amount
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.viewState.value.enterPersonName.value = enterPersonName
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.setEvent(HomeWriteContract.Event.SaveEnterPersonClicked)
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
/***************************************************
* then - ๊ฒฐ๊ณผ ๊ฒ์ฆ
***************************************************/
assertEquals(false, vm.viewState.value.completeButtonEnabled.value)
}
@Test
@Order(15)
@DisplayName(
"๋์น ํ์ด ์ ๋ณด๋ฅผ ์
๋ ฅ ํ ๋ ๊ฒฝ์ฐ -> " +
"์ง์ถ ๋ด์ฉ ๋ฐ ์ฐธ์ฌ์ ๋ชฉ๋ก๋ง ์
๋ ฅ ๊ฒฝ์ฐ -> " +
"์ถ๊ฐํ๊ธฐ ๋ฒํผ์ด ํ์ฑํ ๋์ง ์๋ ๊ฒ์ด ๋ง๋๊ฐ?"
)
fun t15() = runBlocking {
/***************************************************
* when - ๋์ ์คํ
***************************************************/
vm.viewState.value.title.value = title
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.viewState.value.enterPersonName.value = enterPersonName
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.setEvent(HomeWriteContract.Event.SaveEnterPersonClicked)
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
/***************************************************
* then - ๊ฒฐ๊ณผ ๊ฒ์ฆ
***************************************************/
assertEquals(false, vm.viewState.value.completeButtonEnabled.value)
}
@Test
@Order(20)
@DisplayName(
"๋์น ํ์ด ์ ๋ณด ์
๋ ฅ ์๋ฃ ํ -> " +
"์ถ๊ฐํ๊ธฐ ๋ฒํผ์ ๋๋ ์ ๋ -> " +
"๋ฐ์ดํฐ ์ ์ฅ ํ ํ ์คํธ ๋
ธ์ถ ๋ฐ ์ด์ ํ์ด์ง๋ก ์ด๋ ๋๋ ๊ฒ์ด ๋ง๋๊ฐ?"
)
fun t20() = runBlocking {
/***************************************************
* given - ๊ฐ์
***************************************************/
coEvery {
dutchInfoRepository.insertDutchInfo(
DutchListItemVO(
title = title,
amount = amount,
enterPersonList = arrayListOf(
DutchPersonVO(
name = enterPersonName,
isEnd = false
)
)
)
)
} returns (Unit)
/***************************************************
* when - ๋์ ์คํ
***************************************************/
vm.viewState.value.title.value = title
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.viewState.value.amount.value = amount
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.viewState.value.enterPersonName.value = enterPersonName
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.setEvent(HomeWriteContract.Event.SaveEnterPersonClicked)
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
vm.setEvent(HomeWriteContract.Event.CompleteButtonClicked)
coroutineExtension.dispatcher.scheduler.advanceUntilIdle()
// effect ์ ๋ง์ง๋ง ๊ฐ์ ๊ฐ์ ธ์ต๋๋ค.
var toast : HomeWriteContract.Effect? = null
var navigation : HomeWriteContract.Effect? = null
// ๊ฐ์ ธ์ค๊ณ ์ ํ๋ flow
vm.effect.take(2).collectIndexed { index, value ->
if (index == 0) {
toast = value
} else {
navigation = value
}
}
// advanceUntilIdle ์ ์ฌ์ฉํ๋ฉด ๋๊ธฐ์ค์ธ ์ฝ๋ฃจํด์ ๊ณ์ ๊ธฐ๋ค๋ฆฌ๊ธฐ ๋๋ฌธ์ 1์ด๋ง ๊ธฐ๋ค๋ฆฌ๊ธฐ
coroutineExtension.dispatcher.scheduler.advanceTimeBy(1000)
/***************************************************
* then - ๊ฒฐ๊ณผ ๊ฒ์ฆ
***************************************************/
assertEquals(true, vm.viewState.value.completeButtonEnabled.value)
assertEquals(HomeWriteContract.Effect.Toast.ShowComplete, toast)
assertEquals(HomeWriteContract.Effect.Navigation.GoToBack, navigation)
}
}
| 0 |
Kotlin
|
0
| 1 |
5823e99c4545f9856696eec27a4afeed4c8228de
| 9,093 |
SimpleDutch
|
Apache License 2.0
|
src/test/kotlin/difi/covid/support/RoleBuilder.kt
|
unq-arqsoft-difi
| 258,350,130 | false | null |
package difi.covid.support
import difi.covid.Role
object RoleBuilder {
private const val name = "Lord Commander"
fun anyOne() = Role(name)
}
| 0 |
Kotlin
|
0
| 0 |
820916808a57bcfe37c4d7dc646e00578ef65621
| 151 |
covid-back-kotlin
|
ISC License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.