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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/mrwhoknows/csgeeks/ui/home_page/login/LoginFragment.kt
|
mrwhoknows55
| 284,306,294
| false
| null |
package com.mrwhoknows.csgeeks.ui.home_page.login
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.google.android.material.snackbar.Snackbar
import com.mrwhoknows.csgeeks.R
import com.mrwhoknows.csgeeks.ui.home_page.MainActivity
import com.mrwhoknows.csgeeks.util.Constants.LOGIN_TOKEN
import com.mrwhoknows.csgeeks.util.LoginInfo
import com.mrwhoknows.csgeeks.util.Resource
import com.mrwhoknows.csgeeks.viewmodels.BlogViewModel
import kotlinx.android.synthetic.main.fragment_login.*
private const val TAG = "LoginFragment"
class LoginFragment : Fragment(R.layout.fragment_login) {
private lateinit var viewModel: BlogViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = (activity as MainActivity).viewModel
btLogin.setOnClickListener {
val username = usernameTextInput.editText!!.text.toString()
val passwd = passwordTextInput.editText!!.text.toString()
if (username.isBlank() or passwd.isBlank()) {
if (username.isBlank()) usernameTextInput.error = "Please Enter Username"
else usernameTextInput.error = null
if (passwd.isBlank()) passwordTextInput.error = "Please Enter Password"
else passwordTextInput.error = null
} else {
usernameTextInput.error = null
passwordTextInput.error = null
//Hide kyb when clicked on submit
val kbd =
requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
kbd.hideSoftInputFromWindow(requireActivity().currentFocus?.windowToken, 0)
viewModel.loginUserToServer(username, passwd)
observeLogin()
}
}
}
private fun observeLogin() {
viewModel.loginUser.observe(viewLifecycleOwner, { loginResource ->
when (loginResource) {
is Resource.Success -> {
Log.d(TAG, "token: ${loginResource.data!!.token}")
val token = loginResource.data?.token.toString()
val authorName = loginResource.data?.author.toString()
if (loginResource.data!!.success) {
saveLoginToken(true, token, authorName)
findNavController().navigate(R.id.action_loginFragment_to_adminActivity)
requireActivity().finish()
} else {
Snackbar.make(
requireView(),
loginResource.data!!.response,
Snackbar.LENGTH_SHORT
).show()
}
}
is Resource.Error -> {
Snackbar.make(
requireView(),
"Login Failed",
Snackbar.LENGTH_SHORT
).show()
Log.d(TAG, "error: ${loginResource.message!!}")
saveLoginToken(false, null, "")
}
}
})
}
private fun saveLoginToken(isLoginSuccess: Boolean, loginToken: String?, authorName: String?) {
val loginInfo = LoginInfo(requireActivity())
if (isLoginSuccess) {
loginInfo.editor.clear().remove(LOGIN_TOKEN)
loginInfo.setToken(loginToken!!)
loginInfo.setAuthorName(authorName!!)
loginInfo.setIsLoggedIn(isLoginSuccess)
} else
loginInfo.setIsLoggedIn(isLoginSuccess)
}
}
| 0
| null |
2
| 5
|
ba7c5af6f98c579cbba7ad9706150cadd7be4141
| 3,895
|
csgeeks-blog-app
|
MIT License
|
v1/src/main/kotlin/com/example/forsubmit/domain/post/controller/PostController.kt
|
jhhong0509
| 433,380,334
| false
|
{"Kotlin": 84514, "Groovy": 81151, "Vim Snippet": 690}
|
package com.example.forsubmit.domain.post.controller
import com.example.forsubmit.domain.post.payload.request.CreatePostRequest
import com.example.forsubmit.domain.post.payload.request.UpdatePostRequest
import com.example.forsubmit.domain.post.payload.response.DeletePostResponse
import com.example.forsubmit.domain.post.payload.response.PostContentResponse
import com.example.forsubmit.domain.post.payload.response.PostListResponse
import com.example.forsubmit.domain.post.payload.response.SavePostResponse
import com.example.forsubmit.domain.post.service.PostService
import com.example.forsubmit.global.payload.BaseResponse
import org.springframework.http.HttpStatus
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/post")
class PostController(
private val postService: PostService
) {
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
fun savePost(@RequestBody @Validated request: CreatePostRequest): BaseResponse<SavePostResponse> {
return postService.savePost(request)
}
@PatchMapping("/{id}")
fun updatePost(@PathVariable id: Long, @RequestBody @Validated request: UpdatePostRequest): BaseResponse<Unit> {
return postService.updatePost(id, request)
}
@DeleteMapping("/{id}")
fun deletePost(@PathVariable id: Long): BaseResponse<DeletePostResponse> {
return postService.deletePost(id)
}
@GetMapping("/{id}")
fun getPost(@PathVariable id: Long): BaseResponse<PostContentResponse> {
return postService.getSinglePost(id)
}
@GetMapping
fun getPostList(@RequestParam(required = false) lastId: Long?): BaseResponse<PostListResponse> {
return postService.getPostList(lastId)
}
}
| 5
|
Kotlin
|
4
| 29
|
3f8effaca61e6d8f328e3aca7356cbd1d67335b4
| 1,782
|
Kopring-Best-Practice
|
Apache License 2.0
|
examples/welcome/login/src/main/java/com/motorro/statemachine/login/di/LoginEntryPoint.kt
|
motorro
| 512,762,123
| false
|
{"Kotlin": 102349}
|
/*
* 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.statemachine.login.di
import com.motorro.statemachine.commonapi.welcome.model.state.FlowStarter
import com.motorro.statemachine.login.data.LoginGesture
import com.motorro.statemachine.login.data.LoginUiState
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
/**
* Login feature entry point
*/
@EntryPoint
@InstallIn(LoginComponent::class)
interface LoginEntryPoint {
/**
* Flow starter
*/
fun flowStarter(): FlowStarter<LoginGesture, LoginUiState>
}
| 1
|
Kotlin
|
5
| 42
|
5f6cbf2d867f027ce852fe90d38cc077d22308f7
| 1,082
|
CommonStateMachine
|
Apache License 2.0
|
app/src/main/java/com/chocolate/triviatitans/TriviaGameNavGraph.kt
|
team-chocolate-cake
| 661,943,976
| false
| null |
package com.chocolate.triviatitans
import android.provider.DocumentsContract.Root
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.chocolate.triviatitans.presentation.Screens
import com.chocolate.triviatitans.presentation.SplashScreen
import com.chocolate.triviatitans.presentation.screens.category.categoryRoute
import com.chocolate.triviatitans.presentation.screens.home.homeRoute
import com.chocolate.triviatitans.presentation.screens.level.levelRoute
import com.chocolate.triviatitans.presentation.screens.lose.loseRoute
import com.chocolate.triviatitans.presentation.screens.quiz_screen.image_game.imageGameRoute
import com.chocolate.triviatitans.presentation.screens.quiz_screen.text_game.textGameRoute
import com.chocolate.triviatitans.presentation.screens.quiz_screen.word_wise.wordWiseRoute
import com.chocolate.triviatitans.presentation.screens.spinWheel.spinWheelRoute
import com.chocolate.triviatitans.presentation.screens.win.winRoute
@Composable
fun TriviaNavGraph() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = Screens.SplashScreen.route
) {
homeRoute(navController)
categoryRoute(navController)
levelRoute(navController)
imageGameRoute(navController)
textGameRoute(navController)
wordWiseRoute(navController)
loseRoute(navController)
spinWheelRoute(navController)
winRoute(navController)
splashScreenRoute(navController)
}
}
fun NavGraphBuilder.splashScreenRoute(navController: NavController){
composable(route = Screens.SplashScreen.route) {
SplashScreen(navController = navController)
}
}
| 0
|
Kotlin
|
3
| 1
|
94e74e9943f25d94a64311d898baf4b07fabfc63
| 1,932
|
TriviaTitans
|
MIT License
|
native/swift/swift-export-standalone/testData/package_flattening/input_root/foo.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 78866546, "Java": 6826073, "Swift": 4062833, "C": 2609426, "C++": 1970234, "Objective-C++": 171723, "JavaScript": 138329, "Python": 59488, "Shell": 35024, "TypeScript": 22800, "Objective-C": 22132, "Lex": 21352, "Groovy": 17400, "Batchfile": 11746, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
package org.kotlin.foo
typealias Typealias = Int
class Clazz
fun function(arg: Int) = arg
var variable: Int = 0
val constant: Int = 0
| 178
|
Kotlin
|
5638
| 48,021
|
093e432a97b4e7af469bc55a3d321dec964bc6de
| 138
|
kotlin
|
Apache License 2.0
|
ok-marketplace-mp-transport-mp/src/commonMain/kotlin/ru/otus/otuskotlin/marketplace/transport/kmp/models/demands/MpResponseDemandList.kt
|
otuskotlin
| 323,966,359
| false
| null |
package ru.otus.otuskotlin.marketplace.transport.kmp.models.demands
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import ru.otus.otuskotlin.marketplace.transport.kmp.models.common.*
@Serializable
@SerialName("MpResponseDemandList")
data class MpResponseDemandList(
override val responseId: String? = null,
override val onRequest: String? = null,
override val endTime: String? = null,
override val errors: List<ErrorDto>? = null,
override val status: ResponseStatusDto? = null,
override val debug: Debug? = null,
val demands: List<MpDemandDto>? = null,
val pageCount: Int? = null,
): IMpResponse, MpMessage() {
@Serializable
data class Debug(
override val mode: MpWorkModeDto?
) : IMpDebug
}
| 0
|
Kotlin
|
0
| 1
|
5f05fe658504dfa5d7300e3f0f523d250ff6ce31
| 782
|
202012-otuskotlin-marketplace
|
MIT License
|
src/main/kotlin/main/RepoWatcher.kt
|
flobaader
| 119,988,956
| false
| null |
package main
import model.KnownRepo
import networking.GitHubChecker
import networking.SQLConnection
import networking.trigger
import java.util.*
import kotlin.concurrent.timer
/**
* This is the main Application class
*/
class RepoWatcher {
companion object {
@JvmStatic
fun main(args: Array<String>) {
var watcher = RepoWatcher()
watcher.startMonitoring()
}
}
val checker = GitHubChecker()
//Attention: This URL ist not visible in the heroku config but dynamically created at the gradle startup
val sqlConnection = SQLConnection(System.getenv("JDBC_DATABASE_URL"))
init {
println("GitHubCommit Watcher starting..")
}
fun startMonitoring() {
println("Starting Monitoring")
timer("RepoWatcher", false, Date(), 500L, {
println("Starting new monitoring circle")
scanForChangedRepos()
})
}
//TODO Save triggered state in the database
private fun scanForChangedRepos() {
//Get all known repos from the sql database
sqlConnection.getAllKnownRepos().forEach {
//Check and update the commit
if (updateCommitHash(it)) {
val triggerUrls = sqlConnection.getAllTriggerURLs(it.url)
triggerUrls.forEach { it.trigger() }
}
}
}
/**
* Checks if a new commit was published and updates it if necessary
* @return if the commit was updated
*/
private fun updateCommitHash(repo: KnownRepo): Boolean {
val currentSHA = checker.getLastCommitHash(repo.url)
val updated = repo.lastCommitHash != currentSHA
if (updated) {
repo.lastCommitHash = currentSHA
}
return updated
}
}
| 0
|
Kotlin
|
0
| 0
|
310851d87382be3a26226c9749366f70e1469b97
| 1,784
|
githubcommittrigger
|
Apache License 2.0
|
inappmessaging/src/main/java/com/rakuten/tech/mobile/inappmessaging/runtime/data/customjson/CustomJsonDeserializer.kt
|
rakutentech
| 253,402,688
| false
|
{"Kotlin": 738651, "Shell": 1497, "Ruby": 63}
|
package com.rakuten.tech.mobile.inappmessaging.runtime.data.customjson
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.rakuten.tech.mobile.inappmessaging.runtime.utils.InAppLogger
import java.lang.reflect.Type
internal class CustomJsonDeserializer : JsonDeserializer<CustomJson> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): CustomJson {
val jsonObject = json?.asJsonObject
val pushPrimer = context?.safeDeserialize<PushPrimer>(jsonObject?.get("pushPrimer"))
val clickableImage = context?.safeDeserialize<ClickableImage>(jsonObject?.get("clickableImage"))
val background = context?.safeDeserialize<Background>(jsonObject?.get("background"))
return CustomJson(pushPrimer, clickableImage, background)
}
@SuppressWarnings("TooGenericExceptionCaught")
private inline fun <reified T> JsonDeserializationContext.safeDeserialize(jsonElement: JsonElement?): T? {
return try {
this.deserialize<T>(jsonElement, T::class.java)
} catch (_: Exception) {
InAppLogger("IAM_CustomJsonDeserializer")
.warn("Invalid format for ${T::class.java.name.split(".").lastOrNull()}")
null
}
}
}
| 1
|
Kotlin
|
10
| 7
|
355909da73f163ef90ff72944447d7a3cbe5ae9f
| 1,354
|
android-inappmessaging
|
MIT License
|
src/main/kotlin/me/camdenorrb/kportals/commands/sub/SubCmd.kt
|
camdenorrb
| 85,821,749
| false
| null |
package me.camdenorrb.kportals.commands.sub
import me.camdenorrb.kportals.KPortals
import org.bukkit.command.CommandSender
/**
* Created by camdenorrb on 3/20/17.
*/
abstract class SubCmd(val arg: String, val usage: String, val permission: String) {
abstract fun execute(sender: CommandSender, plugin: KPortals, args: List<String>): Boolean
}
| 0
|
Kotlin
|
0
| 2
|
d2d7312596758972bfbe89c120a0d176359e322a
| 350
|
KPortals
|
MIT License
|
app/src/main/java/com/muvi/view/widget/StackViewWidget.kt
|
ezralazuardy
| 210,104,940
| false
| null |
/*
* Created by <NAME> on 10/14/19 9:55 AM
* Copyright (c) 2019 . All rights reserved.
* Last modified 10/14/19 9:54 AM
*/
package com.muvi.view.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.RemoteViews
import com.muvi.R
import com.muvi.config.AppConfig
import com.muvi.view.detail.DetailActivity
import org.jetbrains.anko.startActivity
class StackViewWidget : AppWidgetProvider() {
companion object {
private const val TOAST_ACTION = "com.muvi.TOAST_ACTION"
const val EXTRA_ITEM = "com.muvi.EXTRA_ITEM"
const val UPDATE_WIDGET = "com.muvi.UPDATE_WIDGET"
internal fun updateAppWidget(
context: Context, appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
appWidgetManager.updateAppWidget(
appWidgetId,
RemoteViews(context.packageName, R.layout.stack_view_widget).apply {
this.setRemoteAdapter(
R.id.stackView,
Intent(context, StackWidgetService::class.java).apply {
data = Uri.parse(this.toUri(Intent.URI_INTENT_SCHEME))
this.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
}
)
this.setEmptyView(R.id.stackView, R.id.emptyView)
this.setPendingIntentTemplate(
R.id.stackView,
PendingIntent.getBroadcast(
context,
0,
Intent(context, this::class.java).apply {
action = TOAST_ACTION
this.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
},
PendingIntent.FLAG_UPDATE_CURRENT
)
)
}
)
}
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
for (appWidgetId in appWidgetIds) updateAppWidget(context, appWidgetManager, appWidgetId)
}
override fun onEnabled(context: Context) { }
override fun onDisabled(context: Context) { }
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
Log.e(this::class.java.simpleName, "onReceive(${intent.action})")
when(intent.action) {
UPDATE_WIDGET -> {
val appWidgetManager = AppWidgetManager.getInstance(context)
appWidgetManager.notifyAppWidgetViewDataChanged(
appWidgetManager.getAppWidgetIds(ComponentName(context, this::class.java)),
R.id.stackView
)
}
EXTRA_ITEM -> {
context.startActivity<DetailActivity>(
AppConfig.INTENT_EXTRA_CONTENT_TYPE to intent.getSerializableExtra(AppConfig.INTENT_EXTRA_CONTENT_TYPE),
AppConfig.INTENT_EXTRA_DATA_MOVIE to intent.getParcelableArrayExtra(AppConfig.INTENT_EXTRA_DATA_MOVIE),
AppConfig.INTENT_EXTRA_OPEN_FROM to intent.getStringExtra(AppConfig.INTENT_EXTRA_OPEN_FROM)
)
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
59a4b017246faddf8912fb0d93eb429c78f57115
| 3,602
|
muvi
|
MIT License
|
plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintExtension.kt
|
Octogonapus
| 153,191,798
| true
|
{"Kotlin": 52599}
|
package org.jlleitschuh.gradle.ktlint
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType
/**
* Extension class for configuring the [KtlintPlugin].
*/
open class KtlintExtension(
objectFactory: ObjectFactory
) {
/**
* The version of ktlint to use.
*/
val version: Property<String> = objectFactory.property { set("0.29.0") }
/**
* Enable verbose mode.
*/
val verbose: Property<Boolean> = objectFactory.property { set(false) }
/**
* Enable debug mode.
*/
val debug: Property<Boolean> = objectFactory.property { set(false) }
/**
* Enable android mode.
*/
val android: Property<Boolean> = objectFactory.property { set(false) }
/**
* Enable console output mode.
*/
val outputToConsole: Property<Boolean> = objectFactory.property { set(true) }
/**
* Enabled colored output to console.
*/
val coloredOutput: Property<Boolean> = objectFactory.property { set(true) }
/**
* Whether or not to allow the build to continue if there are warnings;
* defaults to {@code false}, as for any other static code analysis tool.
* <p>
* Example: `ignoreFailures = true`
*/
val ignoreFailures: Property<Boolean> = objectFactory.property { set(false) }
/**
* The ruleset(s) of ktlint to use.
*/
val ruleSets: ListProperty<String> = objectFactory.listProperty { set(emptyList()) }
/**
* Report output formats.
*
* Available values: plain, plain_group_by_file, checkstyle, json.
*
* **Note** for Gradle scripts: for now all values should be uppercase due to bug in Gradle.
*
* Default is plain.
*/
val reporters: SetProperty<ReporterType> = objectFactory.setProperty {
set(setOf(ReporterType.PLAIN))
}
}
| 0
|
Kotlin
|
0
| 0
|
617987c0170b034b941b87ffbe6ea8b86d459a30
| 1,982
|
ktlint-gradle
|
MIT License
|
app/src/main/java/com/project/acehotel/core/di/interceptor/AuthInterceptor.kt
|
AceHotelProject
| 732,506,429
| false
|
{"Kotlin": 760501}
|
package com.project.acehotel.core.di.interceptor
import com.project.acehotel.core.data.source.local.datastore.DatastoreManager
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Response
import timber.log.Timber
import javax.inject.Inject
class AuthInterceptor @Inject constructor(private val datastoreManager: DatastoreManager) :
Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val token = runBlocking {
datastoreManager.getAccessToken().first().toString()
}
Timber.tag("TOKEN").d("Access token: %s", token)
val request = chain.request().newBuilder()
if (token.isNotEmpty()) {
request.addHeader("Authorization", "Bearer $token")
}
return chain.proceed(request.build())
}
}
| 0
|
Kotlin
|
0
| 0
|
785f99aa5c1d5be4e2d3505ee877fee5a33ba823
| 864
|
AceHotel-App
|
MIT License
|
app/src/main/java/com/ayatkhraisat/mvp_example/data/MoviesDataSource.kt
|
AyatKhraisat
| 158,123,741
| false
| null |
package com.ayatkhraisat.mvp_example.data
import android.util.Log
import androidx.paging.PageKeyedDataSource
import com.ayatkhraisat.mvp_example.models.Model
import com.ayatkhraisat.mvp_example.network.MoviesService
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
/**
* Created by <NAME> on 2/12/19
* <EMAIL>
* <p>
* Project Name: MVP_Architecture
* <p>
* Blessed Tree IT
*/
const val API_KEY = ""
class MoviesDataSource @Inject constructor(val moviesService: MoviesService) :
PageKeyedDataSource<Int, Model.MovieItem>() {
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Model.MovieItem>) {
moviesService.getTopRatedMovies(API_KEY, 1)
.enqueue(object : Callback<Model.MoviesList> {
override fun onResponse(call: Call<Model.MoviesList>, response: Response<Model.MoviesList>) {
if (response.isSuccessful) {
callback.onResult(response.body()!!.results, null, 2)
} else {
Log.e(javaClass.simpleName, "${response.errorBody()}")
}
}
override fun onFailure(call: Call<Model.MoviesList>, t: Throwable) {
Log.e(javaClass.simpleName, "Error: ${t.message}")
}
})
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Model.MovieItem>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Model.MovieItem>) {
moviesService.getTopRatedMovies(API_KEY, params.key)
.enqueue(object : Callback<Model.MoviesList> {
override fun onResponse(call: Call<Model.MoviesList>, response: Response<Model.MoviesList>) {
if (response.isSuccessful) {
val nextKey = if (params.key == response.body()!!.totalPages) null else params.key + 1
callback.onResult(response.body()!!.results, nextKey)
} else {
Log.e(javaClass.simpleName, "${response.errorBody()}")
}
}
override fun onFailure(call: Call<Model.MoviesList>, t: Throwable) {
Log.e(javaClass.simpleName, "Error: ${t.message}")
}
})
}
}
| 0
|
Kotlin
|
2
| 5
|
bd8bd152431505fff2168af177f2e2554016af76
| 2,541
|
MVP-Architecture
|
Apache License 2.0
|
platform/runner-extension/telegram/src/main/kotlin/io/hamal/extension/telegram/Extension.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 2114763, "C": 1398432, "TypeScript": 279976, "Lua": 100966, "C++": 40651, "Makefile": 11728, "Java": 7564, "JavaScript": 3406, "CMake": 2810, "CSS": 1626, "HTML": 1239, "Shell": 977}
|
package io.hamal.extension.telegram
import io.hamal.lib.kua.Sandbox
import io.hamal.lib.kua.extend.ExtensionConfig
import io.hamal.lib.kua.extend.extension.RunnerExtension
import io.hamal.lib.kua.extend.extension.RunnerExtensionFactory
import io.hamal.lib.kua.type.StringType
object TelegramScriptFactory : RunnerExtensionFactory {
override fun create(sandbox: Sandbox): RunnerExtension {
return RunnerExtension(
name = "telegram",
config = ExtensionConfig(
mutableMapOf(
"base_url" to StringType("https://api.telegram.org")
)
)
)
}
}
| 26
|
Kotlin
|
0
| 0
|
64288303fd12b334787c7bbb15afbaa99f716125
| 651
|
hamal
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/covid/misc/VisualizerApp.kt
|
christophpickl
| 344,232,553
| false
| null |
package covid.misc
import javafx.application.Application
import javafx.scene.Group
import javafx.scene.Node
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.layout.StackPane
import javafx.scene.layout.VBox
import javafx.scene.media.AudioSpectrumListener
import javafx.scene.media.Media
import javafx.scene.media.MediaPlayer
import javafx.scene.paint.Color
import javafx.scene.shape.Circle
import javafx.scene.shape.Rectangle
import javafx.scene.text.Text
import javafx.stage.Stage
import java.io.File
val MUTE_ON_START = true
val DO_PRINT_DEBUG = false
/**
* see: http://www.java2s.com/ref/java/javafx-audiospectrumlistener-handle-spectrum-data-update.html
*/
class VisualizerApp : AudioSpectrumListener, Application() {
private val mp3 = File("/Users/wu/Desktop/audio.mp3")
private val media = Media(mp3.toURI().toString())
private val player = MediaPlayer(media)
private val visualizers: Set<Visualizer> = setOf(
BalkenVisualizer(),
CircleVisualizer(),
)
companion object {
@JvmStatic
fun main(args: Array<String>) {
launch(VisualizerApp::class.java, *args)
}
}
init {
player.audioSpectrumListener = this
player.audioSpectrumThreshold = -100
player.setOnReady { println("Player ready") }
}
override fun start(primaryStage: Stage) {
primaryStage.title = "Visualizer"
if (MUTE_ON_START) {
player.isMute = true
}
val btnPanel = StackPane().apply {
children.add(Button("toggle pause").apply {
setOnAction {
if (player.status == MediaPlayer.Status.PAUSED) {
player.play()
} else {
player.pause()
}
}
})
}
val root = VBox()
root.children.add(btnPanel)
visualizers.forEach {
root.children.add(it.view)
}
primaryStage.scene = Scene(root, 1200.0, 500.0)
primaryStage.setOnShown { player.play() }
primaryStage.show()
}
override fun spectrumDataUpdate(
timestamp: Double, // current location in seconds
duration: Double, // always 0.1
rawMagnitudes: FloatArray, // the data in DB; size=128
phases: FloatArray // ignore so far
) {
val magnitudes = rawMagnitudes.map { (it - player.audioSpectrumThreshold) / 100 } // [ 0,0 .. 1,0 ]
if (DO_PRINT_DEBUG) {
val p = "%.2f"
System.out.printf(
"sec: %.2f => $p / $p / $p / $p / $p%n",
timestamp,
magnitudes[0],
magnitudes[1],
magnitudes[2],
magnitudes[3],
magnitudes[4]
)
}
// https://www.tutorialspoint.com/javafx/javafx_2d_shapes.htm
visualizers.forEach {
it.onData(magnitudes)
}
}
}
interface Visualizer {
val view: Node
fun onData(magnitudes: List<Float>)
}
class CircleVisualizer : Visualizer, Group() {
override val view = this
private val maxRadius = 50.0
private val gap = 10.0
init {
resize(100.0, 100.0)
}
override fun onData(magnitudes: List<Float>) {
children.clear()
listOf(10, 60, 110).forEachIndexed { i, magnPos ->
val magn: Float = magnitudes[magnPos].let {
when(magnPos) {
10 -> it
60 -> reconvert(it, 0.6F)
110 -> reconvert(it, 0.2F)
else -> error("unhandled magnitude position: $magnPos")
}
}
children.add(Circle(i * (maxRadius * 2 + gap), 10.0 + maxRadius, maxRadius * magn, when(i) {
0 -> Color.RED
1 -> Color.GREEN
else -> Color.BLUE
}))
}
}
private fun reconvert(magnitude: Float, upper: Float): Float {
if(magnitude == 0.0F) return 0.0F
return (magnitude / upper).coerceAtMost(1.0F)
}
}
class BalkenVisualizer : Visualizer, Group() {
override val view = this
private val rectWidth = 5.0
private val horizontalGap = 0.0
private val rectMaxHeight = 300.0
override fun onData(magnitudes: List<Float>) {
children.clear()
children.add(Rectangle(0.0, 0.0, 128.0 * (rectWidth + horizontalGap), rectMaxHeight).apply {
fill = Color.color(0.6, 0.8, magnitudes[10].toDouble())
})
magnitudes.forEachIndexed { i, magnitude ->
val posX = i * (rectWidth + horizontalGap)
val height = rectMaxHeight * magnitude
val posY = rectMaxHeight - height
children.add(Rectangle(posX, posY, rectWidth, height).apply {
fill = colorFor(magnitude)
})
}
magnitudes.forEachIndexed { i, magnitude ->
if (i % 10 == 0) {
val posX = i * (rectWidth + horizontalGap)
val height = rectMaxHeight * magnitude
val posY = rectMaxHeight - height
children.add(Text(posX, posY, "${(magnitude * 100).toInt()}"))
}
}
val avg = magnitudes.map { (it * 100) }.average()
val max = magnitudes.maxOrNull()!!
println("avg: ${avg.toInt()}, max: $max")
}
// Color.color(1.0, 1.0, 1.0)
private fun colorFor(magnitude: Float) = when (magnitude) {
in 0.0F..0.1F -> Color.GREEN
in 0.1F..0.5F -> Color.YELLOW
in 0.3F..0.5F -> Color.ORANGE
in 0.5F..1.0F -> Color.RED
else -> Color.BLACK
}
}
| 0
|
Kotlin
|
0
| 0
|
1f2811ff07418aa793819c394045d764bfa2bbe8
| 5,730
|
covid-playground
|
The Unlicense
|
template/app/src/main/kotlin/app/ui/navigation/adaptive/AdaptiveNavigation.kt
|
kotlitecture
| 738,057,168
| false
|
{"Kotlin": 316837, "HTML": 891}
|
@file:OptIn(ExperimentalMaterial3AdaptiveNavigationSuiteApi::class)
package app.ui.navigation.adaptive
import androidx.compose.material3.Text
import androidx.compose.material3.adaptive.navigationsuite.ExperimentalMaterial3AdaptiveNavigationSuiteApi
import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteScaffold
import androidx.compose.runtime.Composable
import app.provideHiltViewModel
import app.ui.component.AnyIcon
import app.ui.navigation.NavigationBarViewModel
/**
* Composable function to display an adaptive navigation.
*
* @param content The content to display.
*/
@Composable
fun AdaptiveNavigation(content: @Composable () -> Unit) {
val viewModel: NavigationBarViewModel = provideHiltViewModel()
val pages = viewModel.availablePagesStore.asStateValue()?.takeIf { it.isNotEmpty() } ?: return
NavigationSuiteScaffold(
navigationSuiteItems = {
val selected = viewModel.activePageStore.asStateValue()
pages.forEach { page ->
item(
label = { page.label?.let { Text(text = it) } },
icon = { AnyIcon(model = page.icon) },
selected = page.id == selected?.id,
onClick = page.onClick,
)
}
},
content = content
)
}
| 0
|
Kotlin
|
0
| 0
|
2f09ff83c7864fb15aca22ac7a9419b7881e5d15
| 1,329
|
template-android-compose
|
MIT License
|
jvm-library/buildSrc/src/Releases.kt
|
hendraanggrian
| 204,931,838
| false
| null |
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
import org.gradle.api.publish.maven.MavenPom
import org.gradle.api.publish.maven.MavenPomDeveloper
const val DEVELOPER_ID = "hendraanggrian"
const val DEVELOPER_NAME = "Hendra Anggrian"
const val DEVELOPER_URL = "https://github.com/$DEVELOPER_ID/"
const val RELEASE_GROUP = "com.hendraanggrian"
const val RELEASE_ARTIFACT = "library"
const val RELEASE_VERSION = "0.1"
const val RELEASE_DESCRIPTION = "A very awesome library"
const val RELEASE_URL = "https://github.com/$DEVELOPER_ID/$RELEASE_ARTIFACT/"
| 0
|
Kotlin
|
1
| 4
|
c567392dae98a0d58c28faea2a23941af6d84ec4
| 631
|
kt-project-templates
|
Apache License 2.0
|
app/src/main/java/me/androidbox/pokemon/data/requests/PokemonDetailInteractorImp.kt
|
steve1rm
| 286,256,755
| false
| null |
package me.androidbox.pokemon.data.requests
import io.reactivex.Single
import me.androidbox.pokemon.data.service.PokemonService
import me.androidbox.pokemon.domain.interactors.PokemonDetailInteractor
import me.androidbox.pokemon.domain.models.PokemonModel
import java.util.concurrent.TimeUnit
class PokemonDetailInteractorImp(private val pokemonService: PokemonService) : PokemonDetailInteractor {
override fun getPokemonDetailById(id: Int): Single<PokemonModel> {
return pokemonService.getPokemonById(id)
.timeout(10, TimeUnit.SECONDS)
}
override fun getPokemonDetailByName(name: String): Single<PokemonModel> {
return pokemonService.getPokemonByName(name)
.timeout(10, TimeUnit.SECONDS)
}
}
| 1
|
Kotlin
|
0
| 0
|
8c3167e33241c5eb3f3fd484425b02a010788c1f
| 753
|
pokemons
|
MIT License
|
HankyongSample/app/src/main/java/com/hankyong/hankyongsample/presentation/SplashActivity.kt
|
json-mentor
| 737,809,644
| false
|
{"Kotlin": 51006}
|
package com.hankyong.hankyongsample.presentation
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.hankyong.hankyongsample.databinding.ActivitySplashBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
@SuppressLint("CustomSplashScreen")
@AndroidEntryPoint
class SplashActivity @Inject constructor() : AppCompatActivity() {
private lateinit var mContext: Context
private lateinit var binding: ActivitySplashBinding
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
mContext = this@SplashActivity
super.onCreate(savedInstanceState)
binding = ActivitySplashBinding.inflate(layoutInflater)
setContentView(binding.root)
//Todo 여기서 레이아웃에 대한 처리와 앱 구동 시 수행 되어야 하는 작업들을 정의 하세요.
// 샘플은 3초가 기다린 후에 메인 화면으로 이동합니다.
}
private fun moveToMain() {
CoroutineScope(Dispatchers.Main).launch {
//3초간 정지.
delay(3_000)
//메인 화면 호출.
MainActivity.start(this@SplashActivity)
//Splash 화면은 종료.
finish()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1f7516532ff330309e3ed9775918975fec86d072
| 1,434
|
Hankyong
|
Apache License 2.0
|
KotlinSamples-master/src/main/kotlin/chapter7/actor/interaction/actor_samples.kt
|
PacktPublishing
| 142,565,876
| false
| null |
package chapter7.actor.interaction
import kotlinx.coroutines.experimental.CoroutineStart
import kotlinx.coroutines.experimental.channels.actor
import kotlinx.coroutines.experimental.newFixedThreadPoolContext
import kotlinx.coroutines.experimental.runBlocking
/**
* Interacting with an actor.
*/
fun main(args: Array<String>) = runBlocking {
bufferedActor()
actorWithContext()
lazyActor()
}
suspend fun bufferedActor() {
val bufferedPrinter = actor<String>(capacity = 10) {
for (msg in channel) {
println(msg)
}
}
bufferedPrinter.send("hello")
bufferedPrinter.send("world")
bufferedPrinter.close()
}
suspend fun actorWithContext() {
val dispatcher = newFixedThreadPoolContext(3, "pool")
val actor = actor<String>(dispatcher) {
for (msg in channel) {
println("Running in ${Thread.currentThread().name}")
}
}
for (i in 1..10) {
actor.send("a")
}
}
suspend fun lazyActor() {
val actor = actor<String>(start = CoroutineStart.LAZY) {
for (msg in channel) {
println(msg)
}
}
actor.send("hello lazy")
}
| 0
|
Kotlin
|
10
| 34
|
b80e6baaab137696080b1698e235f2bfcc72de57
| 1,158
|
Learning-Concurrency-in-Kotlin
|
MIT License
|
devfun-httpd/src/main/java/com/nextfaze/devfun/httpd/HttpD.kt
|
suclike
| 98,347,273
| true
|
{"Kotlin": 378699, "Prolog": 1350, "CSS": 355}
|
package com.nextfaze.devfun.httpd
import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.support.v7.app.AlertDialog
import com.google.auto.service.AutoService
import com.nextfaze.devfun.annotations.DeveloperCategory
import com.nextfaze.devfun.annotations.DeveloperFunction
import com.nextfaze.devfun.core.*
import com.nextfaze.devfun.inject.InstanceProvider
import com.nextfaze.devfun.inject.captureInstance
import com.nextfaze.devfun.internal.*
import fi.iki.elonen.NanoHTTPD.IHTTPSession
import fi.iki.elonen.NanoHTTPD.Response
import fi.iki.elonen.NanoHTTPD.Response.Status.*
import fi.iki.elonen.router.RouterNanoHTTPD
import fi.iki.elonen.router.RouterNanoHTTPD.UriResource
import fi.iki.elonen.router.RouterNanoHTTPD.newFixedLengthResponse
import java.net.NetworkInterface
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.LazyThreadSafetyMode.NONE
private const val DEFAULT_PORT = 0x5A23 // 23075
private val AVD_IP = "10.0.2.15"
private const val PRIVILEGED_PORTS_END = 1023
private const val EPHEMERAL_PORTS_START = 49152
/**
* The port to use for HTTPD server. Default value is 23075.
*
* This value needs to be set before [DevHttpD.init].
*
* More simply, it can also be overridden in resources: `R.integer.devDefaultPort`
*/
var devDefaultPort = DEFAULT_PORT
@AutoService(DevFunModule::class)
class DevHttpD : AbstractDevFunModule() {
private val log = logger()
internal val handler = Handler(Looper.getMainLooper())
var port = devDefaultPort
lateinit var nano: HttpDRouter
lateinit var captured: InstanceProvider
override fun init(context: Context) {
port = context.resources.getInteger(R.integer.df_httpd_default_port).takeUnless { it <= 0 } ?: devDefaultPort
// We'll try requested port and one based on package name
// Maybe only use package-generated one unless manually specified?
var lastException: Throwable? = null
val nanoHttpD = run startNanoHttpD@ {
listOf(port, generatePortFromPackage(port, context)).forEach { p ->
try {
// TODO? do this in another thread? (I suspect this will block during start() until new server thread is bound)
return@startNanoHttpD HttpDRouter(context, p).apply { start() }
} catch (t: Throwable) {
log.w(t) { "Failed to start NanoHttpD on port $p, attempting port generated from application package..." }
lastException = t
}
}
return@startNanoHttpD null
} ?: throw lastException ?: RuntimeException("Failed to initialize NanoHttpD - unknown error")
nano = nanoHttpD
devFun.instanceProviders += captureInstance { nano }.also { captured = it }
}
override fun dispose() {
nano.stop()
devFun.instanceProviders -= captured
}
private fun generatePortFromPackage(startingPort: Int, context: Context): Int {
val port = startingPort xor (context.packageName.hashCode() and 0xffff)
return when {
port <= PRIVILEGED_PORTS_END -> port + PRIVILEGED_PORTS_END * 2
port >= EPHEMERAL_PORTS_START -> port - (port - EPHEMERAL_PORTS_START) * 2
else -> port
}
}
}
val DevFun.devHttpD get() = get<DevHttpD>()
@DeveloperCategory("DevFun", "HTTPD")
class HttpDRouter(private val context: Context, private val port: Int) : RouterNanoHTTPD(port) {
private val log = logger()
init {
setRoutePrioritizer(InsertionOrderRoutePrioritizer())
addMappings()
}
override fun addMappings() {
setNotImplementedHandler(NotImplementedHandler::class.java)
setNotFoundHandler(Error404UriHandler::class.java)
addRoute("/invoke/:hashCode", InvokeHandler::class.java)
}
@DeveloperFunction
override fun start() = super.start()
override fun start(timeout: Int, daemon: Boolean) {
super.start(timeout, daemon)
logServerInfo()
}
@DeveloperFunction
override fun stop() = super.stop()
@DeveloperFunction
private fun showServerInfoDialog(activity: Activity) =
logServerInfo().also {
AlertDialog.Builder(activity)
.setTitle("Server Info")
.setMessage(it)
.show()
}
@DeveloperFunction("Show Server Info Dialog TL;DR;")
private fun showServerInfoDialogTlDr(activity: Activity) =
serverInfoTlDr().also {
log.i { "Server Info TL;DR;\n$it" }
AlertDialog.Builder(activity)
.setTitle("Server Info TL;DR;")
.setMessage(it)
.show()
}
private fun serverInfoTlDr() = """
Run this: adb forward tcp:$port tcp:$port
Click this: http://127.0.0.1:$port/"""
@DeveloperFunction
private fun logServerInfo(): String {
val b = StringBuilder()
val wifiIpV4 = wifiIpV4
"Local HTTP server started. (hasWifiIpV4=${wifiIpV4 != 0}, isEmulator=$isEmulator, isAvd=$isAvd)".also {
b.append(it).append("\n")
log.i { it }
}
// Use wifi IPv4 if present
if (wifiIpV4 != 0) {
"Access via wifi: http://${wifiIpV4.toIpV4String()}:$port/".also {
b.append(it).append("\n")
log.i { it }
}
}
// If we're in an AVD then log help/setup info
if (isAvd) {
"""================================================
This device appears to be a local AVD instance.
To enable access from host machine, port forwarding must be enabled for device.
//
// Forward using ADB
//
- Use ADB 'forward' command:
> adb forward tcp:<machinePort> tcp:<emulatorPort>
e.g.
adb forward tcp:$port tcp:$port
//
// Forward using Emulator Console
//
- Connect to emulator console via telnet (default is 5554)
> telnet localhost <port>
- Authenticate with telnet (auth token found in user home directory e.g. ~/.emulator_console_auth_token)
> auth <auth_token>
- Add port redirection (emulatorPort=$port)
> redir add tcp:<machinePort>:<emulatorPort>
==== Commands for default environment ====
> telnet localhost 5554
> auth <auth_token>
> redir add tcp:$port:$port
- Access via: http://127.0.0.1:$port/
==== Additional Info ====
Emulator console port can be found via:
- Window title of emulator ("Android Emulator - Nexus_5X_API_23:5554") // 5554
- ADB command "adb devices" > "emulator-5554 device" // 5554
On Linux auth token can be seen via "cat ~/.emulator_console_auth_token"
On other machines, after connecting to emulator console you will be told where you can find your auth token.
//
// Remarks
//
When adding the port redirect:
- <machinePort> can be whatever you want (it will be the port you use in browser URL)
- <emulatorPort> needs to be the value passed in to "initHttpD" (DEFAULT_PORT=$DEFAULT_PORT)
Official documentation:
- ADB forwarding: https://developer.android.com/studio/command-line/adb.html#forwardports
- Console access: https://developer.android.com/studio/run/emulator-commandline.html#console
- Network config: https://developer.android.com/studio/run/emulator-commandline.html#emulatornetworking
Once completed access via: 127.0.0.1:<machinePort>
If you used the same <machinePort> as <emulatorPort>: http://127.0.0.1:$port/
TL;DR;
${serverInfoTlDr()}
================================================""".also {
b.append(it).append("\n")
log.i { it }
}
}
// Dump all possible network address
val addresses = NetworkInterface.getNetworkInterfaces().asSequence()
.flatMap { it.inetAddresses.asSequence().filter { it.address != null && it.address.isNotEmpty() } }
.map { if (it.address.size == 4) it.hostAddress else "[${it.hostAddress}]" }
.filter { it != AVD_IP }
.toSet()
if (addresses.isNotEmpty()) {
"""Other possible access addresses from device all-networks list (these might not work):
${addresses.joinToString("\n") { "http://$it:$port/" }}""".also {
b.append(it).append("\n")
log.i { it }
}
}
return b.toString()
}
private val wifiIpV4 get() = wifiManager.connectionInfo?.ipAddress ?: 0
private val isAvd by lazy(NONE) hasAvdIp@ {
NetworkInterface.getNetworkInterfaces().asSequence().any {
it.inetAddresses.asSequence().any {
it.hostAddress == AVD_IP
}
}
}
private val isEmulator by lazy(NONE) {
Build.PRODUCT == "sdk" ||
Build.PRODUCT == "sdk_x86" ||
Build.PRODUCT == "sdk_google_phone_x86" ||
Build.PRODUCT.contains("genymotion", ignoreCase = true) ||
Build.DISPLAY.contains("vbox86p", ignoreCase = true)
}
private val wifiManager get() = context.wifiManager
private fun Int.toIpV4String() = "%d.%d.%d.%d".format(this and 0xff, this shr 8 and 0xff, this shr 16 and 0xff, this shr 24 and 0xff)
}
abstract class AbstractUriHandler : RouterNanoHTTPD.UriResponder {
private fun notAllowed(): Response = newFixedLengthResponse(METHOD_NOT_ALLOWED, "text/plain", METHOD_NOT_ALLOWED.description)
override fun get(uriResource: UriResource, urlParams: Map<String, String>, session: IHTTPSession) = notAllowed()
override fun put(uriResource: UriResource, urlParams: Map<String, String>, session: IHTTPSession) = notAllowed()
override fun post(uriResource: UriResource, urlParams: Map<String, String>, session: IHTTPSession) = notAllowed()
override fun delete(uriResource: UriResource, urlParams: Map<String, String>, session: IHTTPSession) = notAllowed()
override fun other(method: String, uriResource: UriResource, urlParams: Map<String, String>, session: IHTTPSession) = notAllowed()
}
internal class AssetHandler : AbstractUriHandler() {
private val log = logger()
override fun get(uriResource: UriResource, urlParams: Map<String, String>, session: IHTTPSession): Response {
log.t { "uriResource=$uriResource, session.uri=${session.uri}, urlParams=[${urlParams.entries.joinToString { "${it.key}=${it.value}" }}]" }
val mimeType = uriResource.initParameter(String::class.java)
devFun.devHttpD.context.assets.open(session.uri.substring(1)).bufferedReader().use {
return newFixedLengthResponse(Response.Status.OK, mimeType, it.readText())
}
}
}
internal class InvokeHandler : AbstractUriHandler() {
private val log = logger()
override fun post(uriResource: UriResource, urlParams: Map<String, String>, session: IHTTPSession): Response {
log.t { "uriResource=$uriResource, session.uri=${session.uri}, urlParams=[${urlParams.entries.joinToString { "${it.key}=${it.value}" }}]" }
val hashCode = urlParams["hashCode"]?.toIntOrNull() ?: return response(NOT_FOUND, "Invoke '${urlParams["hashCode"]}' not not found.")
log.t { devFun.categories.flatMap { it.items }.joinToString { "item[${it.hashCode()}]=$it" } }
val item = devFun.categories.flatMap { it.items }.firstOrNull { it.hashCode() == hashCode } ?:
return run notFoundBadRequest@ {
"${BAD_REQUEST.description}\nItem with hashCode $hashCode not found!".let {
log.d { it }
response(BAD_REQUEST, it)
}
}
val invokeWait = CountDownLatch(1)
try {
var result: InvokeResult? = null
devFun.devHttpD.handler.post {
result = item.callAndLog(logger = log)
invokeWait.countDown()
}
invokeWait.await(5, TimeUnit.SECONDS)
if (result != null && result?.exception == null) {
return response(OK, "${result?.value}")
} else {
return response(INTERNAL_ERROR, "Unexpected error ${result?.exception}")
}
} catch (ignore: InterruptedException) {
return response(REQUEST_TIMEOUT, "Timed out waiting for $item")
}
}
private fun response(status: Response.IStatus, text: String, mimeType: String = "text/plain")
= newFixedLengthResponse(status, mimeType, "${status.description}\n$text")
}
| 0
|
Kotlin
|
0
| 0
|
af96685910e76a00161b26e1962130dace7e80a9
| 12,576
|
dev-fun
|
Apache License 2.0
|
kandy-echarts/src/main/kotlin/org/jetbrains/kotlinx/kandy/echarts/layers/aes/lineAndAreaAes.kt
|
Kotlin
| 502,039,936
| false
| null |
/*
* Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.kandy.echarts.layers.aes
import org.jetbrains.kotlinx.kandy.ir.aes.Aes
//______________________________________LINE AES_____________________________________________
internal val LINE_COLOR: Aes = Aes("line_color")
// smooth parameter
internal val SMOOTH: Aes = Aes("smooth")
// width parameter
internal val WIDTH: Aes = Aes("width")
// opacity parameter for line
internal val LINE_ALPHA: Aes = Aes("line_alpha")
// type of line
internal val LINE_TYPE: Aes = Aes("line_type")
internal val SYMBOL: Aes = Aes("symbol")
internal val LINE_SHADOW_COLOR: Aes = Aes("line_shadow_color")
internal val LINE_SHADOW_BLUR: Aes = Aes("line_shadow_blur")
internal val STEP: Aes = Aes("step")
internal val CAP: Aes = Aes("cap")
//______________________________________AREA AES_____________________________________________
internal val AREA_COLOR: Aes = Aes("area_color")
// origin position of area
internal val AREA_POSITION: Aes = Aes("area_position")
// opacity parameter for area
internal val AREA_ALPHA: Aes = Aes("area_alpha")
internal val AREA_SHADOW_COLOR: Aes = Aes("area_shadow_color")
internal val AREA_SHADOW_BLUR: Aes = Aes("area_shadow_blur")
| 78
|
Kotlin
|
0
| 98
|
0e54a419c188b5e6dbee8a95af5213c7ac978bb6
| 1,297
|
kandy
|
Apache License 2.0
|
example/src/main/kotlin/snitch/example/database/repositories/users/PostgresUsersRepository.kt
|
memoizr
| 322,370,926
| false
| null |
package snitch.example.database.repositories.users
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import snitch.example.database.Users
import snitch.example.types.CreateUserAction
import snitch.example.types.Email
import snitch.example.types.Hash
import snitch.example.types.UserId
import java.util.*
class PostgresUsersRepository : UsersRepository {
override fun putUser(user: CreateUserAction) = tryStatement {
Users.insert {
it[id] = user.userId?.value ?: UUID.randomUUID().toString()
it[name] = user.name.value
it[email] = user.email.value
it[hash] = user.hash.value
}.let {
UserId(it[Users.id])
}
}
override fun findHashBy(email: Email): Pair<UserId, Hash>? =
Users
.select { Users.email eq email.value }
.map { UserId(it[Users.id]) to Hash(it[Users.hash]) }
.singleOrNull()
}
| 0
|
Kotlin
|
2
| 34
|
501b43074653207279fe3646a8f8519520967c3b
| 959
|
snitch
|
Apache License 2.0
|
feature/main/src/main/kotlin/com/masselis/tpmsadvanced/feature/main/ioc/VehicleModule.kt
|
VincentMasselis
| 501,773,706
| false
|
{"Kotlin": 611164}
|
package com.masselis.tpmsadvanced.feature.main.ioc
import com.masselis.tpmsadvanced.data.vehicle.model.Vehicle
import com.masselis.tpmsadvanced.feature.main.usecase.VehicleStateFlowUseCase
import dagger.Module
import dagger.Provides
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.StateFlow
@Module
internal object VehicleModule {
@Provides
fun carFlow(vehicleStateFlowUseCase: VehicleStateFlowUseCase): StateFlow<Vehicle> =
vehicleStateFlowUseCase
@Provides
@VehicleComponent.Scope
fun scope() = CoroutineScope(SupervisorJob())
}
| 10
|
Kotlin
|
3
| 9
|
41773455c3b0489e9eb5aae821bbf434d1faaa46
| 626
|
TPMS-advanced
|
Apache License 2.0
|
app/src/main/java/de/metzgore/beansplan/util/di/components/RemindersFragmentComponent.kt
|
metzgore
| 71,047,344
| false
| null |
package de.metzgore.beansplan.util.di.components
import dagger.Binds
import dagger.Module
import dagger.android.AndroidInjector
import dagger.multibindings.ClassKey
import dagger.multibindings.IntoMap
import de.metzgore.beansplan.reminders.RemindersFragment
@Module(subcomponents = [(RemindersFragmentSubComponent::class)])
abstract class RemindersFragmentComponent {
@Binds
@IntoMap
@ClassKey(RemindersFragment::class)
abstract fun bindRemindersFragment(builder: RemindersFragmentSubComponent.Builder): AndroidInjector.Factory<*>
}
| 0
|
Kotlin
|
2
| 3
|
46fcce056ee9039d76a5d3e1fa8ca602bcca9e80
| 553
|
BeansPlan
|
Apache License 2.0
|
src/test/kotlin/no/nav/samordning/hendelser/feed/FeedControllerAuthTest.kt
|
navikt
| 156,209,069
| false
| null |
package no.nav.samordning.hendelser.feed
import no.nav.pensjonsamhandling.maskinporten.validation.test.AutoConfigureMaskinportenValidator
import no.nav.pensjonsamhandling.maskinporten.validation.test.MaskinportenValidatorTokenGenerator
import no.nav.samordning.hendelser.feed.FeedController.Companion.SCOPE
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.web.servlet.MockHttpServletRequestDsl
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
/**
* Tests authentication/authorization (token validation) of the feed controller API.
*/
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureMaskinportenValidator
internal class FeedControllerAuthTest {
@Autowired
private lateinit var mockMvc: MockMvc
@Autowired
private lateinit var tokenGenerator: MaskinportenValidatorTokenGenerator
@Test
fun valid_token_issuer_is_authorized() {
mockMvc.get(ENDPOINT) {
withTokenFor(ORG_NUMBER_1)
param(TPNR_PARAM_NAME, TPNR_1)
}.andExpect {
status { isOk() }
}
}
@Test
fun valid_orgno_and_tpnr_is_authorized() {
mockMvc.get(ENDPOINT) {
withTokenFor(ORG_NUMBER_2)
param(TPNR_PARAM_NAME, TPNR_2)
}.andExpect {
status { isOk() }
}
}
@Test
fun permit_all_can_access_all() {
mockMvc.get(ENDPOINT) {
withTokenFor("2222222222")
param(TPNR_PARAM_NAME, TPNR_1)
}.andExpect {
status { isOk() }
}
mockMvc.get(ENDPOINT) {
withTokenFor("2222222222")
param(TPNR_PARAM_NAME, TPNR_2)
}.andExpect {
status { isOk() }
}
}
@Test
fun invalid_orgno_is_forbidden() {
mockMvc.get(ENDPOINT) {
withTokenFor("1111111111")
param(TPNR_PARAM_NAME, TPNR_1)
}.andExpect {
status { isForbidden() }
}
}
@Test
fun invalid_tpnr_is_forbidden() {
mockMvc.get(ENDPOINT) {
withTokenFor(ORG_NUMBER_1)
param(TPNR_PARAM_NAME, "1235")
}.andExpect {
status { isForbidden() }
}
}
@Test
fun invalid_orgno_and_tpnr_is_forbidden() {
mockMvc.get(ENDPOINT) {
withTokenFor("9999999999")
param(TPNR_PARAM_NAME, "2000")
}.andExpect {
status {
isForbidden()
}
}
}
@Test
fun no_token_is_unauthorized() {
mockMvc.get(ENDPOINT) {
param(TPNR_PARAM_NAME, TPNR_2)
}.andExpect {
status {
isUnauthorized()
}
}
}
private fun MockHttpServletRequestDsl.withTokenFor(orgno: String) =
headers {
setBearerAuth(
tokenGenerator.generateToken(SCOPE, orgno).serialize()
)
}
companion object {
private const val ENDPOINT = "/hendelser"
private const val TPNR_PARAM_NAME = "tpnr"
private const val ORG_NUMBER_1 = "0000000000"
private const val ORG_NUMBER_2 = "4444444444"
private const val TPNR_1 = "1000"
private const val TPNR_2 = "4000"
}
}
| 0
|
Kotlin
|
0
| 1
|
6958ece51fef3400af952fec9d395bb7260eb8ba
| 3,482
|
samordning-hendelse-api
|
MIT License
|
android/app/src/main/java/com/algorand/android/modules/swap/assetswap/ui/usecase/AssetSwapInitialPreviewUseCase.kt
|
perawallet
| 364,359,642
| false
|
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
|
/*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.swap.assetswap.ui.usecase
import com.algorand.android.models.BaseAccountAssetData.BaseOwnedAssetData.OwnedAssetData
import com.algorand.android.modules.accounticon.ui.usecase.CreateAccountIconDrawableUseCase
import com.algorand.android.modules.accounts.domain.usecase.AccountDetailSummaryUseCase
import com.algorand.android.modules.currency.domain.usecase.DisplayedCurrencyUseCase
import com.algorand.android.modules.swap.assetswap.ui.mapper.AssetSwapPreviewMapper
import com.algorand.android.modules.swap.assetswap.ui.mapper.SelectedAssetAmountDetailMapper
import com.algorand.android.modules.swap.assetswap.ui.mapper.SelectedAssetDetailMapper
import com.algorand.android.modules.swap.assetswap.ui.model.AssetSwapPreview
import com.algorand.android.modules.swap.common.SwapAppxValueParityHelper
import com.algorand.android.usecase.AccountAssetDataUseCase
import com.algorand.android.usecase.CheckUserHasAssetBalanceUseCase
import com.algorand.android.utils.emptyString
import javax.inject.Inject
class AssetSwapInitialPreviewUseCase @Inject constructor(
private val accountAssetDataUseCase: AccountAssetDataUseCase,
private val selectedAssetDetailMapper: SelectedAssetDetailMapper,
private val selectedAssetAmountDetailMapper: SelectedAssetAmountDetailMapper,
private val accountDetailSummaryUseCase: AccountDetailSummaryUseCase,
private val assetSwapPreviewMapper: AssetSwapPreviewMapper,
private val checkUserHasAssetBalanceUseCase: CheckUserHasAssetBalanceUseCase,
private val swapAppxValueParityHelper: SwapAppxValueParityHelper,
private val displayedCurrencyUseCase: DisplayedCurrencyUseCase,
private val createAccountIconDrawableUseCase: CreateAccountIconDrawableUseCase
) {
fun getAssetSwapPreviewInitializationState(
accountAddress: String,
fromAssetId: Long,
toAssetId: Long?
): AssetSwapPreview? {
val fromAssetDetail = getFromAssetDetail(accountAddress, fromAssetId) ?: return null
val toAssetDetail = getToAssetDetail(accountAddress, toAssetId)
val fromSelectedAssetAmountDetail = selectedAssetAmountDetailMapper.mapToDefaultSelectedAssetAmountDetail(
primaryCurrencySymbol = swapAppxValueParityHelper.getDisplayedCurrencySymbol()
)
val toSelectedAssetAmountDetail = selectedAssetAmountDetailMapper.mapToDefaultSelectedAssetAmountDetail(
primaryCurrencySymbol = displayedCurrencyUseCase.getDisplayedCurrencySymbol()
)
val accountDetailSummary = accountDetailSummaryUseCase.getAccountDetailSummary(accountAddress)
// TODO update isSwitchAssetsButtonEnabled when we merge tinyman-swap-2
return assetSwapPreviewMapper.mapToAssetSwapPreview(
accountDisplayName = accountDetailSummary.accountDisplayName,
accountIconDrawablePreview = createAccountIconDrawableUseCase.invoke(accountAddress),
fromSelectedAssetDetail = fromAssetDetail,
toSelectedAssetDetail = toAssetDetail,
isSwapButtonEnabled = false,
isLoadingVisible = false,
fromSelectedAssetAmountDetail = fromSelectedAssetAmountDetail,
toSelectedAssetAmountDetail = toSelectedAssetAmountDetail,
isSwitchAssetsButtonEnabled = if (toAssetId == null) {
false
} else {
checkUserHasAssetBalanceUseCase.hasUserAssetBalance(accountAddress, toAssetId)
},
isMaxAndPercentageButtonEnabled = toAssetDetail != null,
errorEvent = null,
swapQuote = null,
clearToSelectedAssetDetailEvent = null,
navigateToConfirmSwapFragmentEvent = null,
formattedPercentageText = emptyString()
)
}
private fun getFromAssetDetail(accountAddress: String, assetId: Long): AssetSwapPreview.SelectedAssetDetail? {
val ownedFromAssetDetail = accountAssetDataUseCase.getAccountOwnedAssetData(accountAddress, true).run {
firstOrNull { assetId == it.id } ?: firstOrNull { it.isAlgo } ?: return null
}
return getAssetDetail(ownedFromAssetDetail)
}
private fun getToAssetDetail(accountAddress: String, assetId: Long?): AssetSwapPreview.SelectedAssetDetail? {
val ownedToAssetDetail = accountAssetDataUseCase.getAccountOwnedAssetData(accountAddress, true).run {
firstOrNull { assetId == it.id } ?: return null
}
return getAssetDetail(ownedToAssetDetail)
}
private fun getAssetDetail(ownedAssetData: OwnedAssetData): AssetSwapPreview.SelectedAssetDetail {
return selectedAssetDetailMapper.mapToSelectedAssetDetail(
assetId = ownedAssetData.id,
formattedBalance = ownedAssetData.formattedAmount,
assetShortName = ownedAssetData.shortName,
verificationTier = ownedAssetData.verificationTier,
assetDecimal = ownedAssetData.decimals
)
}
}
| 22
|
Swift
|
62
| 181
|
92fc77f73fa4105de82d5e87b03c1e67600a57c0
| 5,567
|
pera-wallet
|
Apache License 2.0
|
common/src/commonMain/kotlin/com/mcxross/cohesive/common/ds/tree/PreOrderTreeIterator.kt
|
mcxross
| 514,846,313
| false
| null |
package com.mcxross.cohesive.common.ds.tree
expect class PreOrderTreeIterator<T>(root: TreeNode<T>) : Iterator<TreeNode<T>>
| 0
|
Kotlin
|
0
| 0
|
0ce0ca84f551231d07dae06e94fe71e52ce25de4
| 124
|
cohesive
|
Apache License 2.0
|
data/RF03933/rnartist.kts
|
fjossinet
| 449,239,232
| false
|
{"Kotlin": 8214424}
|
import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF03933"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
1 to 4
114 to 117
}
value = "#5db902"
}
color {
location {
6 to 15
103 to 112
}
value = "#97a19e"
}
color {
location {
17 to 35
84 to 102
}
value = "#d6d7c0"
}
color {
location {
36 to 39
65 to 68
}
value = "#dd75e8"
}
color {
location {
42 to 44
62 to 64
}
value = "#432563"
}
color {
location {
49 to 51
59 to 61
}
value = "#61d1c9"
}
color {
location {
5 to 5
113 to 113
}
value = "#9733de"
}
color {
location {
16 to 16
103 to 102
}
value = "#cf29bf"
}
color {
location {
36 to 35
69 to 83
}
value = "#97ae25"
}
color {
location {
40 to 41
65 to 64
}
value = "#801c95"
}
color {
location {
45 to 48
62 to 61
}
value = "#15f008"
}
color {
location {
52 to 58
}
value = "#9b4006"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3016050675602d506a0e308f07d071abf1524b67
| 1,998
|
Rfam-for-RNArtist
|
MIT License
|
app/src/main/java/com/lagradost/shiro/ui/result/ResultsViewModel.kt
|
deceptions
| 410,639,357
| false
| null |
package com.lagradost.shiro.ui.result
import ANILIST_SHOULD_UPDATE_LIST
import ANILIST_TOKEN_KEY
import DataStore.getKey
import DataStore.mapper
import DataStore.setKey
import MAL_SHOULD_UPDATE_LIST
import MAL_TOKEN_KEY
import RESULTS_PAGE_OVERRIDE_ANILIST
import RESULTS_PAGE_OVERRIDE_MAL
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.module.kotlin.readValue
import com.lagradost.shiro.ui.library.LibraryFragment.Companion.libraryViewModel
import com.lagradost.shiro.utils.*
import com.lagradost.shiro.utils.AniListApi.Companion.fromIntToAnimeStatus
import com.lagradost.shiro.utils.AniListApi.Companion.getDataAboutId
import com.lagradost.shiro.utils.AniListApi.Companion.getShowId
import com.lagradost.shiro.utils.AniListApi.Companion.postDataAboutId
import com.lagradost.shiro.utils.AppUtils.guaranteedContext
import com.lagradost.shiro.utils.MALApi.Companion.getDataAboutMalId
import com.lagradost.shiro.utils.MALApi.Companion.malStatusAsString
import com.lagradost.shiro.utils.MALApi.Companion.setScoreRequest
import com.lagradost.shiro.utils.ShiroApi.Companion.getAnimePageNew
import com.lagradost.shiro.utils.ShiroApi.Companion.getAnimePageNewMal
import kotlin.concurrent.thread
data class SyncData(
var malId: Int?,
var anilistId: Int?,
var title: String,
var status: Int,
var progress: Int,
var episodes: Int,
var score: Int,
)
class ResultsViewModel : ViewModel() {
val localData = MutableLiveData<SyncData?>(null)
val syncData = MutableLiveData<SyncData?>(null)
private var isCurrentlySubbed = true
private var allowSyncDataUpdates = false
private var lastMalId: Int? = null
private var lastAnilistId: Int? = null
private val dataSubbed = MutableLiveData<ShiroApi.Companion.AnimePageNewData?>()
private val dataDubbed = MutableLiveData<ShiroApi.Companion.AnimePageNewData?>()
private val _data = MutableLiveData<ShiroApi.Companion.AnimePageNewData?>()
val data: LiveData<ShiroApi.Companion.AnimePageNewData?> = _data
val recommendations = MutableLiveData<List<AniListApi.Recommendation>?>(null)
val related = MutableLiveData<List<AniListApi.Recommendation>?>(null)
// Because data cannot be posted as null
private val _hasFailed = MutableLiveData(false)
val hasFailed: LiveData<Boolean> = _hasFailed
private val _hasLoadedOther = MutableLiveData(false)
val hasLoadedOther: LiveData<Boolean> = _hasLoadedOther
private fun loadOther(slug: String) {
if (slug.endsWith("-dub")) {
getAnimePageNew(
slug.replace("shippuuden", "shippuden").removeSuffix("-dub")
)?.data?.let {
dataSubbed.postValue(it)
_hasLoadedOther.postValue(true)
}
} else {
getAnimePageNew(slug.replace("shippuden", "shippuuden") + "-dub")?.data?.let {
dataDubbed.postValue(it)
_hasLoadedOther.postValue(true)
}
}
}
data class IdObject(
@JsonProperty("mal") val mal: String?,
)
private fun Context.updateSyncData(
/** Because viewModel values aren't instant */
overrideMalId: Int? = null,
overrideAnilistId: Int? = null
) {
val hasAniList = getKey<String>(
ANILIST_TOKEN_KEY,
ANILIST_ACCOUNT_ID,
null
) != null
val hasMAL = getKey<String>(MAL_TOKEN_KEY, MAL_ACCOUNT_ID, null) != null
val malId = overrideMalId ?: getMalId()
val anilistId = overrideAnilistId ?: getAnilistId()
println("HERE! $malId $anilistId $lastAnilistId $lastMalId")
if (malId == lastMalId && anilistId == lastAnilistId) return
lastAnilistId = anilistId
lastMalId = malId
val holder = if (hasAniList) anilistId?.let {
getDataAboutId(
it
)
} else null
val malHolder =
if (hasMAL && holder == null) malId?.let {
getDataAboutMalId(
it
)
} else null
val localSyncData = when {
holder != null -> {
SyncData(
malId,
anilistId,
holder.title.english ?: holder.title.romaji ?: "",
holder.type.value,
holder.progress,
holder.episodes,
holder.score,
)
}
malHolder != null -> {
SyncData(
malId,
anilistId,
malHolder.title,
malStatusAsString.indexOf(malHolder.my_list_status?.status ?: "none"),
malHolder.my_list_status?.num_episodes_watched ?: 0,
malHolder.num_episodes,
malHolder.my_list_status?.score ?: 0,
)
}
else -> return
}
syncData.postValue(localSyncData)
if (localData.value == null || (overrideAnilistId ?: overrideMalId) != null) localData.postValue(localSyncData)
}
fun syncLocalData(context: Context, overrideData: SyncData? = null) {
val data = overrideData ?: localData.value ?: return
context.setKey(MAL_SHOULD_UPDATE_LIST, true)
context.setKey(ANILIST_SHOULD_UPDATE_LIST, true)
libraryViewModel?.requestMalList(context)
libraryViewModel?.requestAnilistList(context)
val hasAniList = context.getKey<String>(
ANILIST_TOKEN_KEY,
ANILIST_ACCOUNT_ID,
null
) != null
val hasMAL = context.getKey<String>(MAL_TOKEN_KEY, MAL_ACCOUNT_ID, null) != null
thread {
val anilistPost =
if (hasAniList) getAnilistId()?.let {
context.postDataAboutId(
it,
fromIntToAnimeStatus(data.status),
data.score,
data.progress
)
} else true
val malPost = if (hasMAL)
getMalId()?.let {
context.setScoreRequest(
it,
MALApi.fromIntToAnimeStatus(data.status),
data.score,
data.progress
)
} else true
// TODO ERROR HANDLING
if (malPost == true && anilistPost == true) {
syncData.postValue(data)
}
}
}
private fun Context.assignData(data: ShiroApi.Companion.AnimePageNewData?) {
if (data == null) {
_hasFailed.postValue(true)
return
}
isCurrentlySubbed = if (data.anime.slug.endsWith("-dub")) {
dataDubbed.postValue(data)
false
} else {
dataSubbed.postValue(data)
true
}
val overrideAnilistId = getKey<Int>(RESULTS_PAGE_OVERRIDE_ANILIST, data.anime.slug.removeSuffix("-dub"))
val overrideMalId = getKey<Int>(RESULTS_PAGE_OVERRIDE_MAL, data.anime.slug.removeSuffix("-dub"))
setMalIdOverride(overrideMalId)
setAnilistIdOverride(overrideAnilistId)
thread {
val idMal = mapper.readValue<IdObject?>(data.anime.ids)?.mal
val anilistPage = getShowId(idMal.toString(), data.anime.title, data.anime.release_year?.toIntOrNull())
val fixedAnilistId = anilistPage?.id ?: -1
val fixedMalId = idMal?.toIntOrNull() ?: anilistPage?.idMal ?: -1
val localRecommendations = anilistPage?.recommendations?.nodes?.map {
AniListApi.Recommendation(
it.mediaRecommendation.title.english ?: it.mediaRecommendation.title.romaji ?: "",
it.mediaRecommendation.idMal ?: -1,
it.mediaRecommendation.coverImage.large ?: it.mediaRecommendation.coverImage.medium,
it.mediaRecommendation.averageScore
)
} ?: listOf()
val relations = anilistPage?.relations?.edges?.filter { it.node.format?.startsWith("TV") == true }?.map {
val node = it.node
AniListApi.Recommendation(
node.title.english ?: node.title.romaji ?: "",
node.idMal ?: -1,
node.coverImage.large ?: node.coverImage.medium,
node.averageScore
)
} ?: listOf()
related.postValue(relations)
recommendations.postValue(localRecommendations)
setAnilistId(fixedAnilistId)
setMalId(fixedMalId)
updateSyncData(overrideMalId ?: fixedMalId, overrideAnilistId ?: fixedAnilistId)
allowSyncDataUpdates = true
}
loadOther(data.anime.slug)
}
fun loadData(context: Context, slug: String, isMal: Boolean) {
thread {
if (isMal) {
val data = getAnimePageNewMal(slug)?.data
println("DATA $data")
_data.postValue(data)
context.assignData(data)
} else {
val data = getAnimePageNew(slug)?.data
_data.postValue(data)
context.assignData(data)
}
}
}
fun swapData() {
if (hasLoadedOther.value != true) return
if (isCurrentlySubbed) {
_data.postValue(dataDubbed.value)
} else {
_data.postValue(dataSubbed.value)
}
isCurrentlySubbed = !isCurrentlySubbed
}
// val visibleEpisodeProgress = MutableLiveData<Int?>()
// val episodes = MutableLiveData<Int?>()
// val slug = MutableLiveData<String?>()
/** For automatic selection */
private val _currentMalId = MutableLiveData<Int?>()
val currentMalId: LiveData<Int?> = _currentMalId
private val _currentAniListId = MutableLiveData<Int?>()
val currentAniListId: LiveData<Int?> = _currentAniListId
/** For manual selection */
private val _overrideMalId = MutableLiveData<Int?>()
val overrideMalId: LiveData<Int?> = _overrideMalId
private val _overrideAniListId = MutableLiveData<Int?>()
val overrideAniListId: LiveData<Int?> = _overrideAniListId
/** Overridden + current with overridden as priority */
private val _totalAniListId = MutableLiveData<Int?>()
val totalAniListId: LiveData<Int?> = _totalAniListId
private val _totalMalId = MutableLiveData<Int?>()
val totalMalId: LiveData<Int?> = _totalMalId
/** ------------------------------------------------- */
private fun syncData(
/** Because viewModel values aren't instant */
overrideMalId: Int? = null,
overrideAnilistId: Int? = null
) {
if (allowSyncDataUpdates) {
thread {
guaranteedContext(null).updateSyncData(overrideMalId, overrideAnilistId)
}
}
}
fun setAnilistId(id: Int) {
// For instant update, postValue is slow and threaded
_currentAniListId.postValue(id)
_totalAniListId.postValue(overrideAniListId.value ?: id)
syncData(overrideAnilistId = overrideAniListId.value ?: id)
}
fun setAnilistIdOverride(id: Int?) {
_overrideAniListId.postValue(id)
_totalAniListId.postValue(id ?: currentAniListId.value)
syncData(overrideAnilistId = id ?: currentAniListId.value)
}
fun setMalId(id: Int) {
_currentMalId.postValue(id)
_totalMalId.postValue(overrideMalId.value ?: id)
syncData(overrideMalId = overrideMalId.value ?: id)
}
fun setMalIdOverride(id: Int?) {
_overrideMalId.postValue(id)
_totalMalId.postValue(id ?: currentMalId.value)
syncData(overrideMalId = id ?: currentMalId.value)
}
fun getAnilistId(): Int? {
return overrideAniListId.value ?: currentAniListId.value
}
fun getMalId(): Int? {
return overrideMalId.value ?: currentMalId.value
}
}
| 44
|
Kotlin
|
6
| 92
|
6f8d6a26f9cc380899582b4aa642fca9998a9d08
| 12,293
|
no
|
MIT License
|
server/src/main/kotlin/com/heerkirov/hedge/server/enums/MetaType.kt
|
HeerKirov
| 298,201,781
| false
| null |
package com.heerkirov.hedge.server.enums
enum class MetaType {
TAG, // = 0
TOPIC, // = 1
AUTHOR // = 2
}
| 0
|
TypeScript
|
0
| 1
|
8140cd693759a371dc5387c4a3c7ffcef6fb14b2
| 122
|
Hedge-v2
|
MIT License
|
src/main/kotlin/cn/gionrose/facered/task/TaskHolder.kt
|
13022631363
| 681,233,772
| false
| null |
package cn.gionrose.facered.task
import org.bukkit.entity.Player
/**
* 任务所有者
* 任务所有者持有正在运行的任务列表
* 由于他是所有者 故它来操作任务的开始和结束是情理之中
*/
class TaskHolder (val player: Player)
{
val runningTask = arrayListOf<CraftTask>()
fun clear ()
{
runningTask.clear()
}
fun taskSize (): Int
{
return runningTask.size
}
/**
* 可重复添加任务
*/
fun addTask (task: CraftTask)
{
runningTask.add(task)
}
/**
* 删除任务
*/
fun removeTask (index: Int)
{
runningTask.removeAt(index)
}
/**
* 获取任务
*/
fun getTask (index: Int): CraftTask
{
return runningTask[index]
}
/**
* 任务所有者中持有的正在运行的任务列表是否为 empty
*/
fun isEmpty (): Boolean
{
return runningTask.isEmpty()
}
}
| 0
|
Kotlin
|
0
| 0
|
8b0c21f0735b743ebc8f1d43e81ea4bf40770b67
| 818
|
Processcraft
|
Apache License 2.0
|
MXVideoLib/src/main/java/com/mx/video/listener/MXVolumeTouchListener.kt
|
zhangmengxiong
| 386,496,265
| false
| null |
package com.mx.video.listener
import android.content.Context
import com.mx.video.utils.MXVolumeHelp
internal abstract class MXVolumeTouchListener(context: Context) : MXBaseTouchListener {
private val volumeHelp = MXVolumeHelp(context)
private val maxVolume = volumeHelp.getMaxVolume()
private var startVolume = 0
override fun touchStart() {
startVolume = volumeHelp.getVolume()
onSeekStart()
onSeekChange(startVolume, maxVolume)
}
override fun touchMove(percent: Float) {
var targetVolume = startVolume + (maxVolume * percent * 1.5).toInt()
if (targetVolume < 0) targetVolume = 0
if (targetVolume > maxVolume) targetVolume = maxVolume
volumeHelp.setVolume(targetVolume)
onSeekChange(targetVolume, maxVolume)
}
override fun touchEnd(percent: Float) {
var targetVolume = startVolume + (maxVolume * percent * 1.5).toInt()
if (targetVolume < 0) targetVolume = 0
if (targetVolume > maxVolume) targetVolume = maxVolume
volumeHelp.setVolume(targetVolume)
onSeekStop(targetVolume, maxVolume)
}
abstract fun onSeekStart()
abstract fun onSeekChange(volume: Int, maxVolume: Int)
abstract fun onSeekStop(volume: Int, maxVolume: Int)
override fun release() {
volumeHelp.release()
}
}
| 1
|
Kotlin
|
1
| 7
|
9b1fe8ea6514ce073203e1cb51770bc54c3529ce
| 1,344
|
MXVideo
|
Apache License 2.0
|
src/main/kotlin/com/ikuzMirel/data/friends/FriendDataSourceImpl.kt
|
IkuzItsuki
| 590,383,882
| false
| null |
package com.ikuzMirel.data.friends
import com.ikuzMirel.data.user.User
import org.bson.types.ObjectId
import org.litote.kmongo.coroutine.CoroutineDatabase
import org.litote.kmongo.eq
class FriendDataSourceImpl(
db: CoroutineDatabase
): FriendDataSource {
private val userFriends = db.getCollection<User>()
override suspend fun getAllFriends(userId: String): List<Friend> {
val userObjID = ObjectId(userId)
val user = userFriends.findOne(User::id eq userObjID)
return user?.friends ?: emptyList()
}
override suspend fun deleteFriend(userId: String, friend: Friend): Boolean {
val userObjID = ObjectId(userId)
val user = userFriends.findOne(User::id eq userObjID)
return user?.copy(friends = user.friends - friend)
?.let { userFriends.updateOne(User::id eq userObjID, it).wasAcknowledged() } ?: false
}
override suspend fun addFriend(userId: String, friend: Friend): Boolean {
val userObjID = ObjectId(userId)
val user = userFriends.findOne(User::id eq userObjID)
return user?.copy(friends = user.friends + friend)
?.let { userFriends.updateOne(User::id eq userObjID, it).wasAcknowledged() } ?: false
}
}
| 0
|
Kotlin
|
0
| 0
|
bf3b10d91a5389fc0664ded70b5f773a479ad739
| 1,235
|
Flick-Ktor
|
Apache License 2.0
|
app/src/main/java/thekolo/de/quicktilesforikeatradfri/ui/DevicesFragment.kt
|
koloo91
| 106,603,480
| false
| null |
package thekolo.de.quicktilesforikeatradfri.ui
import android.app.Fragment
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_devices.view.*
import thekolo.de.quicktilesforikeatradfri.models.Device
import thekolo.de.quicktilesforikeatradfri.R
import thekolo.de.quicktilesforikeatradfri.models.BulbState
import thekolo.de.quicktilesforikeatradfri.services.QueueService
import thekolo.de.quicktilesforikeatradfri.tradfri.TradfriService
import thekolo.de.quicktilesforikeatradfri.ui.adapter.DevicesAdapter
import java.util.*
class DevicesFragment : Fragment() {
private lateinit var mainActivity: MainActivity
private lateinit var service: TradfriService
private lateinit var layoutManager: LinearLayoutManager
private lateinit var adapter: DevicesAdapter
private var isLoadingDevices = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_devices, container, false)
view.devices_recycler_view.setHasFixedSize(true)
layoutManager = LinearLayoutManager(activity.applicationContext)
view.devices_recycler_view.layoutManager = layoutManager
val dividerItemDecoration = DividerItemDecoration(activity.applicationContext, layoutManager.orientation)
view.devices_recycler_view.addItemDecoration(dividerItemDecoration)
adapter = DevicesAdapter(Collections.emptyList(), deviceAdapterListener)
view.swipe_refresh_layout.setOnRefreshListener {
mainActivity.startLoadingProcess(this@DevicesFragment::loadDevices)
}
view.swipe_refresh_layout.isRefreshing = true
mainActivity.startLoadingProcess(this@DevicesFragment::loadDevices)
return view
}
override fun onResume() {
super.onResume()
mainActivity.startLoadingProcess(this@DevicesFragment::loadDevices)
}
override fun onPause() {
super.onPause()
Log.i("DevicesFragment", "onPause")
QueueService.instance().clearQueue()
}
override fun onAttach(context: Context?) {
super.onAttach(context)
Log.i("DevicesFragment", "onAttach")
mainActivity = context as MainActivity
service = TradfriService.instance(activity)
}
private val deviceAdapterListener = object : DevicesAdapter.DevicesAdapterActions {
override fun onStateSwitchCheckedChanged(device: Device, isChecked: Boolean) {
when (isChecked) {
true -> {
device.states?.first()?.on = BulbState.On
service.turnDeviceOn(device.id, {
println("turnDeviceOn onSuccess")
}, {
mainActivity.onError()
mainActivity.startLoadingProcess(this@DevicesFragment::loadDevices)
})
}
false -> {
device.states?.first()?.on = BulbState.Off
service.turnDeviceOff(device.id, {
println("turnDeviceOff onSuccess")
}, {
mainActivity.onError()
mainActivity.startLoadingProcess(this@DevicesFragment::loadDevices)
})
}
}
}
}
fun loadDevices() {
if (isLoadingDevices) return
view?.devices_recycler_view?.adapter = adapter
view?.swipe_refresh_layout?.isRefreshing = true
isLoadingDevices = true
service.getDevices({ devices ->
adapter.devices = devices
adapter.notifyDataSetChanged()
view?.swipe_refresh_layout?.isRefreshing = false
isLoadingDevices = false
if (devices.isEmpty())
mainActivity.displayMessage("No devices found.")
}, {
view?.swipe_refresh_layout?.isRefreshing = false
isLoadingDevices = false
mainActivity.onError()
})
}
companion object {
fun newInstance(): DevicesFragment {
return DevicesFragment()
}
}
}
| 0
|
Kotlin
|
0
| 4
|
7c92c4ddd0f12a061e476aeb90bbf8d9e050d7dc
| 4,531
|
Widgets-for-Ikea-Tradfri
|
MIT License
|
presentation/work/src/main/java/com/gyorgyzoltan/sprayApp/work/overview/list/WorkListItem.kt
|
pandulapeter
| 279,548,090
| false
| null |
package com.gyorgyzoltan.sprayApp.work.overview.list
import com.gyorgyzoltan.sprayApp.main.shared.list.ListItem
internal interface WorkListItem : ListItem
| 0
|
Kotlin
|
0
| 2
|
9a5238105eafc74373f496d26f97cf095daa4696
| 156
|
spray-app
|
Apache License 2.0
|
wearApp/src/main/java/dev/johnoreilly/confetti/wear/auth/GoogleSignOutScreenState.kt
|
joreilly
| 436,024,503
| false
|
{"Kotlin": 890305, "Swift": 38931, "HTML": 23893, "HCL": 9137, "CSS": 8489, "Ruby": 3629}
|
package dev.johnoreilly.confetti.wear.auth
enum class GoogleSignOutScreenState {
Idle,
Loading,
Success,
Failed
}
| 49
|
Kotlin
|
91
| 784
|
d43e98fa3cd6eee949c3a0e57cf35d76dc49f083
| 130
|
Confetti
|
Apache License 2.0
|
app/src/main/java/com/example/androiddevchallenge/list/PuppyListNetwork.kt
|
arkivanov
| 342,410,429
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.list
import com.example.androiddevchallenge.list.PuppyListStore.State.Item
import com.example.androiddevchallenge.list.additionaldata.PuppyAdditionalDataProvider
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import kotlinx.serialization.Serializable
internal class PuppyListNetwork(
private val client: HttpClient,
private val additionalDataProvider: PuppyAdditionalDataProvider
) : PuppyListStoreFactory.Network {
override suspend fun loadItems(): List<Item>? =
client
.runCatching {
try {
get<List<Dog>>("https://api.thedogapi.com/v1/images/search?limit=100&page=0&order=Desc")
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
.getOrElse {
emptyList()
}
?.asSequence()
?.mapNotNull { it.toItem() }
?.take(50)
?.toList()
private fun Dog.toItem(): Item? {
val breed: Breed = breeds?.firstOrNull { it.isValid() } ?: return null
val additionalData = additionalDataProvider.get(id = id)
return Item(
id = id,
imageUrl = url,
name = additionalData.name,
ageMonths = additionalData.ageMonth,
phoneNumber = additionalData.phoneNumber,
breedName = breed.name,
breedGroup = breed.breed_group,
breedTemperament = breed.temperament,
breedLifeSpan = breed.life_span,
breedHeight = breed.height?.metric,
breedWeight = breed.weight?.metric
)
}
private fun Breed.isValid(): Boolean {
val fieldCount =
countField(name) +
countField(breed_group) +
countField(temperament) +
countField(life_span) +
countField(weight) +
countField(height)
return fieldCount >= 2
}
private fun countField(arg: Any?): Int =
if (arg == null) 0 else 1
@Serializable
private class Dog(
val id: String,
val url: String,
val breeds: List<Breed>?
)
@Serializable
private class Breed(
val name: String? = null,
val breed_group: String? = null,
val temperament: String? = null,
val life_span: String? = null,
val weight: Measure? = null,
val height: Measure? = null
)
@Serializable
private class Measure(
val metric: String? = null
)
}
| 0
|
Kotlin
|
0
| 5
|
753201f65d7a00f0c6b9eedc3a06680d36eec162
| 3,241
|
android-dev-challenge-compose-1
|
Apache License 2.0
|
base/src/main/java/org/robojackets/apiary/base/repository/ServerInfoRepository.kt
|
RoboJackets
| 369,067,791
| false
|
{"Kotlin": 234535, "Ruby": 6715}
|
package org.robojackets.apiary.base.repository
import com.skydoves.sandwich.ApiResponse
import dagger.hilt.android.scopes.ActivityRetainedScoped
import org.robojackets.apiary.base.model.ServerInfoContainer
import org.robojackets.apiary.base.service.ServerInfoApiService
import javax.inject.Inject
@ActivityRetainedScoped
class ServerInfoRepository @Inject constructor(
val serverInfoApiService: ServerInfoApiService
) {
suspend fun getServerInfo(): ApiResponse<ServerInfoContainer> {
return serverInfoApiService.getServerInfo()
}
}
| 24
|
Kotlin
|
0
| 0
|
8478042da4fb7e27b723d26b976e7d6ef6dd82bd
| 554
|
apiary-mobile
|
Apache License 2.0
|
data/RF01209/rnartist.kts
|
fjossinet
| 449,239,232
| false
|
{"Kotlin": 8214424}
|
import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF01209"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
1 to 4
118 to 121
}
value = "#9e6f5b"
}
color {
location {
5 to 117
}
value = "#61d12a"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3016050675602d506a0e308f07d071abf1524b67
| 544
|
Rfam-for-RNArtist
|
MIT License
|
app/src/main/java/com/paprolafsmnew/features/marketing/model/GetMarketingDetailsResponse.kt
|
DebashisINT
| 676,852,117
| false
|
{"Kotlin": 13694213, "Java": 996851}
|
package com.paprolafsmnew.features.marketing.model
import com.paprolafsmnew.base.BaseResponse
/**
* Created by Pratishruti on 05-03-2018.
*/
class GetMarketingDetailsResponse:BaseResponse() {
lateinit var material_details:List<MarketingDetailData>
lateinit var marketing_img:List<MarketingDetailImageData>
}
| 0
|
Kotlin
|
0
| 0
|
be98678f759713d2d5f0b9ec4bc9aa35a54d51e9
| 320
|
PaprolaMarketing
|
Apache License 2.0
|
data/space/src/main/java/com/ku_stacks/ku_ring/space/repository/KuringSpaceRepositoryImpl.kt
|
ku-ring
| 412,458,697
| false
|
{"Kotlin": 651475}
|
package com.ku_stacks.ku_ring.space.repository
import com.ku_stacks.ku_ring.remote.space.KuringSpaceClient
import javax.inject.Inject
class KuringSpaceRepositoryImpl @Inject constructor(
private val kuringSpaceClient: KuringSpaceClient,
) : KuringSpaceRepository {
override suspend fun getMinimumAppVersion(): String {
return kuringSpaceClient.getMinimumAppVersion()
}
}
| 6
|
Kotlin
|
1
| 23
|
5580b0c1c5a9f82d44399df6e8f96ae64cbdd79d
| 392
|
KU-Ring-Android
|
Apache License 2.0
|
app/src/main/java/com/ngikut/u_future/screen/splash/SplashScreen.kt
|
fahmigutawan
| 631,299,852
| false
| null |
package com.ngikut.u_future.screen.splash
import android.window.SplashScreen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.ngikut.u_future.R
import com.ngikut.u_future.data.remote.Resource
import com.ngikut.u_future.ui.theme.AppColor
import com.ngikut.u_future.util.NavRoute
import com.ngikut.u_future.viewmodel.splash.SplashViewmodel
@Composable
fun SplashScreen(
navController: NavController
) {
val viewModel = hiltViewModel<SplashViewmodel>()
val iconWidth = LocalConfiguration.current.screenWidthDp / 2
val checkPenjurusanState = viewModel.checkPenjurusanState.collectAsState()
LaunchedEffect(key1 = checkPenjurusanState.value) {
if (viewModel.startCheckingPenjurusanState.value) {
when (checkPenjurusanState.value) {
is Resource.Error -> {
navController.navigate(NavRoute.Home.name) {
popUpTo(NavRoute.Splash.name) {
inclusive = true
}
}
viewModel.startCheckingPenjurusanState.value = false
}
is Resource.Loading -> {/*TODO*/
}
is Resource.Success -> {
checkPenjurusanState.value.data?.let {
if (it.data.already_taken) {
navController.navigate(NavRoute.Home.name) {
popUpTo(NavRoute.Splash.name) {
inclusive = true
}
}
} else {
navController.navigate(NavRoute.PenjurusanLanding.name) {
popUpTo(NavRoute.Splash.name) {
inclusive = true
}
}
}
}
viewModel.startCheckingPenjurusanState.value = false
}
}
}
}
LaunchedEffect(key1 = true) {
viewModel.getFirstTimeState { firstTime ->
if (firstTime) {
navController.navigate(NavRoute.Onboard.name) {
popUpTo(NavRoute.Splash.name) {
inclusive = true
}
}
} else {
viewModel.getToken { token ->
if (token.isEmpty()) {
navController.navigate(NavRoute.Login.name) {
popUpTo(NavRoute.Splash.name) {
inclusive = true
}
}
} else {
viewModel.startCheckingPenjurusanState.value = true
}
}
}
}
}
if (viewModel.startCheckingPenjurusanState.value) {
LaunchedEffect(key1 = true) {
viewModel.checkPenjurusanState()
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(AppColor.grey50),
contentAlignment = Alignment.Center
) {
AsyncImage(
modifier = Modifier.width(iconWidth.dp),
model = R.drawable.splashscreen_icon,
contentDescription = ""
)
}
}
| 0
|
Kotlin
|
0
| 0
|
456db2f0d0c79304fb362b5c8df4bc92caa2ceee
| 4,017
|
Jetpack-UFuture
|
MIT License
|
src/main/kotlin/com/igorini/mrdrafty/card/ClearTheDeck.kt
|
igorini
| 159,063,909
| false
| null |
package com.igorini.mrdrafty.card
/** Represents a card "Clear The Deck" */
class ClearTheDeck : Card() {
override fun name() = "Clear The Deck"
override fun imageUrl() = ""
override fun color() = CardColor.RED
override fun type() = CardType.SPELL
override fun rarity() = CardRarity.COMMON
override fun baseScore() = 99.8
}
| 0
|
Kotlin
|
0
| 1
|
6e59b9a1073788311b69210b05b8fe0ebb2a7e95
| 348
|
mr-drafty
|
Apache License 2.0
|
MyEcMall-K/BaseLibrary/src/main/java/cn/nieking/baselibrary/widgets/BannerImageLoader.kt
|
NieQing
| 132,399,328
| false
|
{"Kotlin": 241813, "Java": 7791}
|
package cn.nieking.baselibrary.widgets
import android.content.Context
import android.widget.ImageView
import cn.nieking.baselibrary.utils.GlideUtils
import com.youth.banner.loader.ImageLoader
class BannerImageLoader : ImageLoader() {
override fun displayImage(context: Context, path: Any, imageView: ImageView) {
GlideUtils.loadUrlImage(context, path.toString(), imageView)
}
}
| 0
|
Kotlin
|
0
| 0
|
07b22622f98c8bfd8b26ea1303d48f6d66cc4b4b
| 396
|
MyEcMall-K
|
Apache License 2.0
|
app/src/main/java/com/kopai/shinkansen/view/blend/config/BlendConfigFragment.kt
|
kopiai
| 805,653,375
| false
|
{"Kotlin": 147674}
|
package com.kopai.shinkansen.view.blend.config
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.kopai.shinkansen.R
class BlendConfigFragment : Fragment() {
companion object {
fun newInstance() = BlendConfigFragment()
}
private val viewModel: BlendConfigViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// TODO: Use the ViewModel
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
return inflater.inflate(R.layout.fragment_blend_config, container, false)
}
}
| 0
|
Kotlin
|
0
| 0
|
47442dcfa5771aa09b8c9d74ef42921ac3f4f88d
| 838
|
kopai-android
|
MIT License
|
feature/add-record/src/main/kotlin/com/kevlina/budgetplus/feature/add/record/ui/Calculator.kt
|
kevinguitar
| 517,537,183
| false
|
{"Kotlin": 686482}
|
package com.kevlina.budgetplus.feature.add.record.ui
import android.content.Context
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.Backspace
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.kevlina.budgetplus.core.theme.LocalAppColors
import com.kevlina.budgetplus.core.theme.ThemeColors
import com.kevlina.budgetplus.core.ui.AppTheme
import com.kevlina.budgetplus.core.ui.FontSize
import com.kevlina.budgetplus.core.ui.Icon
import com.kevlina.budgetplus.core.ui.Surface
import com.kevlina.budgetplus.core.ui.Text
import com.kevlina.budgetplus.feature.add.record.CalculatorViewModel
import com.kevlina.budgetplus.feature.add.record.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import com.kevlina.budgetplus.core.common.R as coreCommonR
enum class CalculatorButton(val text: Char) {
Seven('7'), Four('4'),
Eight('8'), Five('5'),
Nine('9'), Six('6'),
Divide('÷'), Multiply('×'),
One('1'), Zero('0'),
Two('2'), Dot('.'),
Three('3'), Back('<'),
Minus('-'), Plus('+');
}
enum class CalculatorAction {
Clear, Evaluate, Ok;
}
private val horizontalSpacing = 12.dp
private val verticalSpacing = 8.dp
private val calcButtons = CalculatorButton.entries.toList()
@Composable
internal fun Calculator(
uiState: CalculatorUiState,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val needEvaluate by uiState.needEvaluate.collectAsStateWithLifecycle()
Column(
verticalArrangement = Arrangement.spacedBy(verticalSpacing),
modifier = modifier
) {
calcButtons.chunked(calcButtons.size / 2).forEachIndexed { index, rows ->
Row(
horizontalArrangement = Arrangement.spacedBy(horizontalSpacing),
modifier = if (uiState.adaptiveButton) {
Modifier
.weight(1F)
.fillMaxWidth()
} else {
Modifier
.fillMaxWidth()
.height(intrinsicSize = IntrinsicSize.Min)
}
) {
rows.chunked(2).forEach { btns ->
Column(
verticalArrangement = Arrangement.spacedBy(verticalSpacing),
modifier = Modifier.weight(1F)
) {
btns.forEach { btn ->
CalculatorBtn(
button = btn,
isAdaptive = uiState.adaptiveButton,
onClick = { uiState.onInput(btn) }
)
}
}
}
when (index) {
0 -> ClearBtn(onClick = {
uiState.onCalculatorAction(context, CalculatorAction.Clear)
})
1 -> DoneBtn(
needEvaluate = needEvaluate,
onClick = {
uiState.onCalculatorAction(context, if (needEvaluate) {
CalculatorAction.Evaluate
} else {
CalculatorAction.Ok
})
}
)
}
}
}
}
}
@Composable
private fun ColumnScope.CalculatorBtn(
button: CalculatorButton,
isAdaptive: Boolean,
onClick: () -> Unit,
) {
Surface(
onClick = onClick,
modifier = if (isAdaptive) {
Modifier
.weight(1F)
.fillMaxWidth()
} else {
Modifier
.weight(1F)
.aspectRatio(1F)
},
shape = CircleShape,
color = LocalAppColors.current.primary
) {
Box(contentAlignment = Alignment.Center) {
when (button) {
CalculatorButton.Back -> Icon(
imageVector = Icons.AutoMirrored.Rounded.Backspace,
contentDescription = stringResource(id = coreCommonR.string.cta_delete),
tint = LocalAppColors.current.light
)
CalculatorButton.Plus -> Image(
painter = painterResource(id = R.drawable.ic_plus),
contentDescription = null,
colorFilter = ColorFilter.tint(LocalAppColors.current.light)
)
CalculatorButton.Minus -> Image(
painter = painterResource(id = R.drawable.ic_minus),
contentDescription = null,
colorFilter = ColorFilter.tint(LocalAppColors.current.light)
)
CalculatorButton.Multiply -> Image(
painter = painterResource(id = R.drawable.ic_multiply),
contentDescription = null,
colorFilter = ColorFilter.tint(LocalAppColors.current.light)
)
CalculatorButton.Divide -> Image(
painter = painterResource(id = R.drawable.ic_divide),
contentDescription = null,
colorFilter = ColorFilter.tint(LocalAppColors.current.light)
)
else -> Text(
text = button.text.toString(),
textAlign = TextAlign.Center,
fontSize = FontSize.HeaderLarge,
fontWeight = FontWeight.Bold,
color = LocalAppColors.current.light
)
}
}
}
}
@Composable
private fun RowScope.ClearBtn(onClick: () -> Unit) {
Surface(
onClick = onClick,
modifier = Modifier
.weight(1F)
.fillMaxHeight(),
shape = CircleShape,
color = LocalAppColors.current.dark
) {
Box(contentAlignment = Alignment.Center) {
Text(
text = "AC",
textAlign = TextAlign.Center,
fontSize = FontSize.Header,
fontWeight = FontWeight.Bold,
color = LocalAppColors.current.light
)
}
}
}
@Composable
private fun RowScope.DoneBtn(
needEvaluate: Boolean,
onClick: () -> Unit,
) {
Surface(
onClick = onClick,
modifier = Modifier
.weight(1F)
.fillMaxHeight(),
shape = CircleShape,
color = LocalAppColors.current.dark
) {
Box(contentAlignment = Alignment.Center) {
if (needEvaluate) {
Image(
painter = painterResource(id = R.drawable.ic_equal),
contentDescription = null,
colorFilter = ColorFilter.tint(LocalAppColors.current.light)
)
} else {
Text(
text = "OK",
textAlign = TextAlign.Center,
fontSize = FontSize.Header,
fontWeight = FontWeight.Bold,
color = LocalAppColors.current.light
)
}
}
}
}
@Stable
internal data class CalculatorUiState(
val needEvaluate: StateFlow<Boolean>,
val adaptiveButton: Boolean,
val onInput: (CalculatorButton) -> Unit,
val onCalculatorAction: (Context, CalculatorAction) -> Unit,
) {
companion object {
val preview = CalculatorUiState(
needEvaluate = MutableStateFlow(false),
adaptiveButton = false,
onInput = {},
onCalculatorAction = { _, _ -> }
)
}
}
internal fun CalculatorViewModel.toUiState(adaptiveButton: Boolean = false) = CalculatorUiState(
needEvaluate = needEvaluate,
adaptiveButton = adaptiveButton,
onInput = ::onInput,
onCalculatorAction = ::onCalculatorAction
)
@Preview
@Composable
private fun Calculator_Preview() = AppTheme {
Calculator(
uiState = CalculatorUiState.preview,
modifier = Modifier
.background(LocalAppColors.current.light)
.padding(all = 16.dp)
)
}
@Preview(widthDp = 400, heightDp = 600)
@Composable
private fun CalculatorAdaptive_Preview() = AppTheme(themeColors = ThemeColors.Lavender) {
Calculator(
uiState = CalculatorUiState.preview.copy(adaptiveButton = true),
modifier = Modifier
.background(LocalAppColors.current.light)
.padding(all = 16.dp)
)
}
| 2
|
Kotlin
|
0
| 9
|
9c964e063efdf797f84f58fcc3e8b17da75f8309
| 9,971
|
budgetplus-android
|
MIT License
|
cesium-kotlin/src/jsMain/kotlin/cesium/engine/GroundPrimitive.factory.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6328455}
|
// Automatically generated - do not modify!
package cesium.engine
import js.objects.jso
inline fun GroundPrimitive(
block: GroundPrimitive.ConstructorOptions.() -> Unit,
): GroundPrimitive =
GroundPrimitive(options = jso(block))
| 1
|
Kotlin
|
8
| 35
|
6c553c67c6cbf77a802c137d010b143895c7da60
| 240
|
types-kotlin
|
Apache License 2.0
|
application/src/main/kotlin/notes/view/Menubar.kt
|
Oliver-Fenton
| 721,902,234
| false
|
{"Kotlin": 134039, "Java": 980, "Dockerfile": 164}
|
// Copyright (c) 2023. <NAME>, <NAME>, <NAME>, <NAME>.
package notes.view
import javafx.application.Platform
import javafx.scene.control.*
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import notes.shared.Constants
import notes.shared.SysInfo
import notes.shared.model.Model
import notes.shared.preferences.Theme
class Menubar(val noteModel: Model, val noteView: NoteView, val noteList: NoteList, val tagsBar: TagsBar): MenuBar() {
// FILE MENU
private var fileMenu = Menu("File")
private var newNote = MenuItem("New Note")
private var deleteNote = MenuItem("Delete Note")
private val quit = MenuItem("Quit")
// EDIT MENU
private var editMenu = Menu("Edit")
private var undo = MenuItem("Undo")
private var redo = MenuItem("Redo")
private var cut = MenuItem("Cut")
private var copy = MenuItem("Copy")
private var paste = MenuItem("Paste")
// VIEW MENU
private var viewMenu = Menu("View")
private var sortSubMenu = SortMenu(noteModel, noteList)
private var themeSubMenu = Menu("Theme")
var darkTheme = CheckMenuItem("Dark")
var lightTheme = CheckMenuItem("Light")
init {
// TODO: ADD FUNCTIONALITY WHEN POSSIBLE
newNote.setOnAction {
noteModel.createNote()
//var newNote = NoteTemplate("")
// data.listOfNotes.add(newNote)
// data.preview.add("New Note")
}
deleteNote.setOnAction {
noteModel.deleteNote()
}
//newFolder.setOnAction { }
quit.setOnAction { Platform.exit() }
undo.setOnAction {
Constants.notesArea.htmlText = noteModel.activeNote.value?.undo()
}
redo.setOnAction {
Constants.notesArea.htmlText = noteModel.activeNote.value?.redo()
}
paste.setOnAction {
val pasteButton = Constants.notesArea.lookup(".html-editor-paste")
if (pasteButton is Button) {
pasteButton.fire()
noteModel.activeNote.value?.setNoteBody(Constants.notesArea.htmlText)
}
}
cut.setOnAction {
val cutButton = Constants.notesArea.lookup(".html-editor-cut")
if (cutButton is Button) {
cutButton.fire()
noteModel.activeNote.value?.setNoteBody(Constants.notesArea.htmlText)
}
}
copy.setOnAction {
val copyButton = Constants.notesArea.lookup(".html-editor-copy")
if (copyButton is Button) {
copyButton.fire()
}
}
darkTheme.setOnAction {
setDarkTheme()
}
lightTheme.setOnAction {
setLightTheme()
}
// TODO: DON'T FORGET TO ADD TEMP FROM VIEW MENU WHEN DECIDED
val OS_KeyCombo = if (SysInfo.osName.contains("Mac")) KeyCodeCombination.META_DOWN else KeyCodeCombination.CONTROL_DOWN
newNote.accelerator = KeyCodeCombination(KeyCode.N, OS_KeyCombo)
deleteNote.accelerator = KeyCodeCombination(KeyCode.D, OS_KeyCombo)
quit.accelerator = KeyCodeCombination(KeyCode.Q, OS_KeyCombo)
undo.accelerator = KeyCodeCombination(KeyCode.Z, OS_KeyCombo)
redo.accelerator = KeyCodeCombination(KeyCode.R, OS_KeyCombo) // not able to do 3 keycode combo
cut.accelerator = KeyCodeCombination(KeyCode.X, OS_KeyCombo)
copy.accelerator = KeyCodeCombination(KeyCode.C, OS_KeyCombo)
paste.accelerator = KeyCodeCombination(KeyCode.V, OS_KeyCombo)
fileMenu.items.addAll(newNote, deleteNote, quit)
editMenu.items.addAll(undo, redo, cut, copy, paste)
themeSubMenu.items.addAll(darkTheme, lightTheme)
// light theme as default selected
lightTheme.isSelected = true
viewMenu.items.addAll(themeSubMenu, sortSubMenu)
this.menus.addAll(fileMenu, editMenu, viewMenu)
}
fun setDarkTheme() {
darkTheme.isSelected = true
lightTheme.isSelected = false
scene.root.style = "-fx-base:black"
Constants.theme = "dark"
noteList.refreshList(noteModel.notes)
noteList.apply {
style = "-fx-background-color: ${Constants.DarkNoteListBackgroundColor};" // change to be theme background color
}
if (noteModel.activeNote.value != null) {
val newHtml = noteModel.activeNote.value?.changeBodyBackgroundColor(Constants.DarkHTMLEditorColor)
if (newHtml != null) {
noteModel.activeNote.value?.changeNoteBody(newHtml)
noteView.setTextArea(newHtml)
}
}
else {
val beginningStyleIndex = Constants.notesArea.htmlText.indexOf("<body style=")
val endingStyleIndex = Constants.notesArea.htmlText.indexOf("contenteditable=")
if (beginningStyleIndex == -1) { // no style set yet
var bodyTagIndex = Constants.notesArea.htmlText.indexOf("<body")
var beginningSubstring = Constants.notesArea.htmlText.substring(0, bodyTagIndex + 5)
var endingSubstring = Constants.notesArea.htmlText.substring(bodyTagIndex + 5)
Constants.notesArea.htmlText = "$beginningSubstring style=\"background-color: ${Constants.DarkHTMLEditorColor};\" $endingSubstring"
}
else { // has style already
var beginningSubstring = Constants.notesArea.htmlText.substring(0, beginningStyleIndex + 12)
var endingSubstring = Constants.notesArea.htmlText.substring(endingStyleIndex)
Constants.notesArea.htmlText = "$beginningSubstring\"background-color: ${Constants.DarkHTMLEditorColor};\" $endingSubstring"
}
}
val toolBar2: ToolBar = Constants.notesArea.lookup(".bottom-toolbar") as ToolBar
toolBar2.apply {
style = "-fx-background-color: ${Constants.DarkToolbarColor};"
}
val toolBar1: ToolBar = Constants.notesArea.lookup(".top-toolbar") as ToolBar
for (node in toolBar1.lookupAll(".button")) {
if (node is Button) {
if (node.id == "undo-button") {
val undoImageView = ImageView(Image("Dark-Undo-Icon.png"))
undoImageView.fitHeight = 20.0
undoImageView.isPreserveRatio = true
node.graphic = undoImageView
}
else if (node.id == "redo-button") {
val redoImageView = ImageView(Image("Dark-Redo-Icon.png"))
redoImageView.fitHeight = 20.0
redoImageView.isPreserveRatio = true
node.setPrefSize(20.0, 20.0)
node.graphic = redoImageView
}
else if (node.id == "list-collapsable") {
val listCollapsableImageView = ImageView(Image("Dark-Sidebar-Icon.png"))
listCollapsableImageView.fitHeight = 20.0
listCollapsableImageView.isPreserveRatio = true
node.setPrefSize(20.0, 20.0)
node.graphic = listCollapsableImageView
}
}
}
tagsBar.setTagsBarColors()
}
fun setLightTheme() {
lightTheme.isSelected = true
darkTheme.isSelected = false
scene.root.style = ""
Constants.theme = "light"
noteList.refreshList(noteModel.notes)
noteList.apply {
style = "-fx-background-color: ${Constants.LightNoteListBackgroundColor};" // change to be theme background color
}
if (noteModel.activeNote.value != null) {
val newHtml = noteModel.activeNote.value?.changeBodyBackgroundColor(Constants.LightHTMLEditorColor)
if (newHtml != null) {
noteModel.activeNote.value?.changeNoteBody(newHtml)
noteView.setTextArea(newHtml)
}
}
else {
val beginningStyleIndex = Constants.notesArea.htmlText.indexOf("<body style=")
val endingStyleIndex = Constants.notesArea.htmlText.indexOf("contenteditable=")
if (beginningStyleIndex == -1) { // no style set yet
var bodyTagIndex = Constants.notesArea.htmlText.indexOf("<body")
var beginningSubstring = Constants.notesArea.htmlText.substring(0, bodyTagIndex + 5)
var endingSubstring = Constants.notesArea.htmlText.substring(bodyTagIndex + 5)
Constants.notesArea.htmlText = "$beginningSubstring style=\"background-color: ${Constants.LightHTMLEditorColor};\" $endingSubstring"
}
else { // has style already
var beginningSubstring = Constants.notesArea.htmlText.substring(0, beginningStyleIndex + 12)
var endingSubstring = Constants.notesArea.htmlText.substring(endingStyleIndex)
Constants.notesArea.htmlText = "$beginningSubstring\"background-color: ${Constants.LightHTMLEditorColor};\" $endingSubstring"
}
}
val toolBar2: ToolBar = Constants.notesArea.lookup(".bottom-toolbar") as ToolBar
toolBar2.apply {
style = "-fx-background-color: ${Constants.LightToolbarColor};"
}
val toolBar1: ToolBar = Constants.notesArea.lookup(".top-toolbar") as ToolBar
for (node in toolBar1.lookupAll(".button")) {
if (node is Button) {
if (node.id == "undo-button") {
val undoImageView = ImageView(Image("Undo-Icon.png"))
undoImageView.fitHeight = 20.0
undoImageView.isPreserveRatio = true
node.graphic = undoImageView
}
else if (node.id == "redo-button") {
val redoImageView = ImageView(Image("Redo-Icon.png"))
redoImageView.fitHeight = 20.0
redoImageView.isPreserveRatio = true
node.setPrefSize(20.0, 20.0)
node.graphic = redoImageView
}
else if (node.id == "list-collapsable") {
val listCollapsableImageView = ImageView(Image("Sidebar-Icon.png"))
listCollapsableImageView.fitHeight = 20.0
listCollapsableImageView.isPreserveRatio = true
node.setPrefSize(20.0, 20.0)
node.graphic = listCollapsableImageView
}
}
}
tagsBar.setTagsBarColors()
}
fun getTheme(): Theme {
return if (lightTheme.isSelected) Theme.LIGHT else Theme.DARK
}
}
| 0
|
Kotlin
|
0
| 0
|
5d4a2c0cc5526c1c698854076b94aa79ff9bde14
| 10,758
|
notes
|
MIT License
|
core/src/main/kotlin/pw/mihou/unit/coders/interfaces/Encoders.kt
|
ShindouMihou
| 810,486,376
| false
|
{"Kotlin": 19879}
|
package pw.mihou.unit.coders.interfaces
interface Encoder {
fun encode(content: Any): String
}
| 0
|
Kotlin
|
0
| 0
|
120497aee585aa1761cb4f89a20d909534699070
| 99
|
unit
|
Intel Open Source License
|
diff.main.kts
|
blendthink
| 421,413,290
| false
| null |
#!/usr/bin/env kotlin
@file:Suppress("EXPERIMENTAL_API_USAGE")
@file:Repository("https://repo1.maven.org/maven2/")
@file:DependsOn("eu.jrie.jetbrains:kotlin-shell-core:0.2.1")
import eu.jrie.jetbrains.kotlinshell.shell.*
fun result(command: String): String {
val builder = StringBuilder()
shell {
pipeline {
command.process() pipe builder
}
}
return builder.toString()
}
val baseApkPath = args.getOrNull(0)
val targetApkPath = args.getOrNull(1)
if (baseApkPath.isNullOrBlank() || targetApkPath.isNullOrBlank()) {
throw IllegalArgumentException()
}
val baseDownloadSize = result("apkanalyzer -h apk download-size $baseApkPath")
.trimEnd()
val targetDownloadSize = result("apkanalyzer -h apk download-size $targetApkPath")
.trimEnd()
val basePermissions = result("apkanalyzer manifest permissions $baseApkPath")
.trimEnd()
.replace("\n", "<br>")
val targetPermissions = result("apkanalyzer manifest permissions $targetApkPath")
.trimEnd()
.replace("\n", "<br>")
val baseReferences = result("apkanalyzer dex references $baseApkPath")
.trimEnd()
.replace("\n", "<br>")
val targetReferences = result("apkanalyzer dex references $targetApkPath")
.trimEnd()
.replace("\n", "<br>")
val compare =
result("apkanalyzer -h apk compare --different-only $baseApkPath $targetApkPath")
.replace("\t", "|")
.split("\n")
.filter { !it.contains("""\dB.+$""".toRegex()) }
.joinToString("\n")
val diff = """
~ | before | after
--- | --- | ---
Download Size | $baseDownloadSize | $targetDownloadSize
Permissions | $basePermissions | $targetPermissions
References | $baseReferences | $targetReferences
""".trimIndent()
val sizeDetail = """
before | after | diff | path
--- | --- | --- | ---
$compare
""".trimIndent()
// https://github.community/t/set-output-truncates-multiline-strings/16852/3
val outputDiff = diff
.replace("%", "%25")
.replace("\n", "%0A")
.replace("\r", "%0D")
val outputSizeDetail = sizeDetail
.replace("%", "%25")
.replace("\n", "%0A")
.replace("\r", "%0D")
val echoDiffParam = "::set-output name=diff::$outputDiff"
val echoSizeDetailParam = "::set-output name=size-detail::$outputSizeDetail"
shell {
"echo $echoDiffParam"()
"echo $echoSizeDetailParam"()
}
| 0
|
Kotlin
|
0
| 1
|
d9824a88480fe74bb2719a3a73007e3229284f63
| 2,325
|
android-diff-action
|
MIT License
|
shared/src/iosMain/kotlin/org/flepper/currencyconvertor/di/Context.kt
|
develNerd
| 543,065,385
| false
| null |
package org.flepper.currencyconvertor.di
import platform.darwin.NSObject
actual typealias Context = NSObject
/**
* Expect Class to be implemented on both platforms to get the application context
* */
actual class KMMContext actual constructor(context: Context) {
actual var application: Context = context
}
| 0
|
Kotlin
|
0
| 6
|
0350e4991acd4cae1b852bb67133caa70665000b
| 316
|
FL-CurrencyConvertor-Kotlin-Multiplatform-Mobile
|
MIT License
|
2015/kt/src/test/kotlin/org/adventofcode/extractNumbers.kt
|
windmaomao
| 225,344,109
| false
|
{"JavaScript": 538717, "Ruby": 89779, "Kotlin": 58408, "Rust": 21350, "Go": 19106, "TypeScript": 9930, "Haskell": 8908, "Dhall": 3201, "PureScript": 1488, "HTML": 1307, "CSS": 1092}
|
package org.adventofcode
fun String.extractNumbers(
includeNegative: Boolean = false
): List<Int> {
val reg = if (includeNegative) "-?\\d+" else "\\d+"
return reg.toRegex()
.findAll(this)
.map { it.value.toInt() }
.toList()
}
| 5
|
JavaScript
|
0
| 0
|
1d64d7fffa6fcfc6825e6aa9322eda76e790700f
| 245
|
adventofcode
|
MIT License
|
core/di/src/main/java/uk/nightlines/core/di/ComponentHolder.kt
|
dns21395
| 603,470,891
| false
| null |
package uk.nightlines.core.di
import androidx.lifecycle.ViewModel
class ComponentHolder<T>(val component: T) : ViewModel()
| 0
|
Kotlin
|
0
| 2
|
3b954816bfc81881e8839d417745d19e74a794fd
| 125
|
ModoMultimodule
|
Apache License 2.0
|
android/app/src/main/java/com/algorand/android/modules/swap/introduction/ui/mapper/SwapIntroductionPreviewMapper.kt
|
perawallet
| 364,359,642
| false
|
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
|
/*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.swap.introduction.ui.mapper
import androidx.navigation.NavDirections
import com.algorand.android.modules.swap.introduction.ui.model.SwapIntroductionPreview
import com.algorand.android.utils.Event
import javax.inject.Inject
class SwapIntroductionPreviewMapper @Inject constructor() {
fun mapToSwapIntroductionPreview(
navigationDirectionEvent: Event<NavDirections>?
): SwapIntroductionPreview {
return SwapIntroductionPreview(
navigationDirectionEvent = navigationDirectionEvent
)
}
}
| 22
|
Swift
|
62
| 181
|
92fc77f73fa4105de82d5e87b03c1e67600a57c0
| 1,156
|
pera-wallet
|
Apache License 2.0
|
src/backend/ci/core/notify/biz-notify/src/main/kotlin/com/tencent/devops/notify/wework/pojo/UploadMediaResp.kt
|
TencentBlueKing
| 189,153,491
| false
|
{"Kotlin": 30176725, "Vue": 6739254, "JavaScript": 1256623, "Go": 616850, "Lua": 567159, "TypeScript": 461781, "SCSS": 365654, "Shell": 157561, "Java": 153049, "CSS": 106299, "HTML": 96201, "Python": 39238, "Less": 24714, "Makefile": 10630, "Smarty": 10297, "Dockerfile": 5097, "Batchfile": 4908, "PowerShell": 1626, "VBScript": 189}
|
package com.tencent.devops.notify.wework.pojo
import com.fasterxml.jackson.annotation.JsonProperty
data class UploadMediaResp(
@JsonProperty("created_at")
val createdAt: String?,
@JsonProperty("errcode")
val errCode: Int?,
@JsonProperty("errmsg")
val errMsg: String?,
@JsonProperty("media_id")
val mediaId: String?,
@JsonProperty("type")
val type: String?
)
| 719
|
Kotlin
|
498
| 2,382
|
dd483c38bdbe5c17fa0e5e5bc3390cd1cd40757c
| 400
|
bk-ci
|
MIT License
|
base/src/main/kotlin/com/hieunv/mvvmarch/base/preferences/SharedPrefsModule.kt
|
lvhieut
| 694,577,582
| false
|
{"Kotlin": 115915}
|
package com.hieunv.mvvmarch.base.preferences
import com.hieunv.mvvmarch.base.preferences.auth.AuthSharedPrefs
import com.hieunv.mvvmarch.base.preferences.auth.AuthSharedPrefsDataSource
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
@Module
@InstallIn(ApplicationComponent::class)
abstract class SharedPrefsModule {
// Makes Dagger provide AuthSharedPrefsDataSource when a AuthSharedPrefs type is requested
@Binds
abstract fun provideAuthSharedPreferences(authSharedPrefsDataSource: AuthSharedPrefsDataSource): AuthSharedPrefs
}
| 1
|
Kotlin
|
0
| 0
|
92b56b13990606a02c9a8d9f94ff15d1c37516b5
| 626
|
Base_mvvm_clone
|
MIT License
|
app/src/main/java/com/ingjuanocampo/enfila/domain/data/source/contact/ClientLocalSource.kt
|
ingjuanocampo
| 387,043,993
| false
|
{"Kotlin": 247926}
|
package com.ingjuanocampo.enfila.domain.data.source.contact
class ClientLocalSource
| 2
|
Kotlin
|
0
| 0
|
12309564fe50d599d2319d697b009d8d310f1bb5
| 85
|
EnFila-Android
|
MIT License
|
cryptocurrencychallenge/src/main/java/com/yoti/android/cryptocurrencychallenge/data/repository/CryptoRepositoryImpl.kt
|
zakaria-hajja
| 420,542,603
| false
| null |
package com.yoti.android.cryptocurrencychallenge.data.repository
import com.yoti.android.cryptocurrencychallenge.data.datasource.RemoteDataSource
import com.yoti.android.cryptocurrencychallenge.domain.repository.CryptoRepository
class CryptoRepositoryImpl(private val dataSource: RemoteDataSource) : CryptoRepository {
override suspend fun getAssets() = dataSource.getAssets().assetData ?: emptyList()
override suspend fun getMarkets() = dataSource.getMarkets().marketData ?: emptyList()
}
| 0
|
Kotlin
|
0
| 0
|
5f061c1149d3baf79f1f94639e082f83d223cffd
| 499
|
cryptocurrency
|
MIT License
|
_sample/sample-app/src/main/java/com/declarative/ui/pattern/SampleApplication.kt
|
SeongUgJung
| 311,954,386
| false
|
{"Kotlin": 30446}
|
package com.declarative.ui.pattern
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class SampleApplication : Application() {
}
| 0
|
Kotlin
|
0
| 0
|
55239dda550d070134a6f717f44e466d825aa048
| 169
|
DeclarativeUIPattern
|
MIT License
|
app/src/main/java/com/github/apognu/otter/Otter.kt
|
Skehmatics
| 268,192,895
| true
|
{"Kotlin": 180762}
|
package com.github.apognu.otter
import android.app.Application
import androidx.appcompat.app.AppCompatDelegate
import com.github.apognu.otter.utils.Command
import com.github.apognu.otter.utils.Event
import com.github.apognu.otter.utils.Request
import com.preference.PowerPreference
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
class Otter : Application() {
companion object {
private var instance: Otter = Otter()
fun get(): Otter = instance
}
val eventBus: BroadcastChannel<Event> = BroadcastChannel(10)
val commandBus: Channel<Command> = Channel(10)
val requestBus: BroadcastChannel<Request> = BroadcastChannel(10)
val progressBus: BroadcastChannel<Triple<Int, Int, Int>> = ConflatedBroadcastChannel()
override fun onCreate() {
super.onCreate()
instance = this
when (PowerPreference.getDefaultFile().getString("night_mode")) {
"on" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
"off" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
}
}
| 0
| null |
0
| 0
|
d5c1b89d3daf6e3dce7d3a3e6fd437c5755ef514
| 1,260
|
otter
|
MIT License
|
app/src/main/java/de/luckyworks/compose/charts/sample/ui/line/LineChartDataModel.kt
|
lacky1991
| 462,792,840
| false
|
{"Kotlin": 105296}
|
package de.luckyworks.compose.charts.sample.ui.line
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import de.luckyworks.compose.charts.line.LineChartData
import de.luckyworks.compose.charts.line.LineChartData.Point
import de.luckyworks.compose.charts.line.renderer.point.FilledCircularPointDrawer
import de.luckyworks.compose.charts.line.renderer.point.HollowCircularPointDrawer
import de.luckyworks.compose.charts.line.renderer.point.NoPointDrawer
import de.luckyworks.compose.charts.line.renderer.point.PointDrawer
import de.luckyworks.compose.charts.sample.ui.line.LineChartDataModel.PointDrawerType.Filled
import de.luckyworks.compose.charts.sample.ui.line.LineChartDataModel.PointDrawerType.Hollow
import de.luckyworks.compose.charts.sample.ui.line.LineChartDataModel.PointDrawerType.None
class LineChartDataModel {
var lineChartData by mutableStateOf(
LineChartData(
points = listOf(
Point(randomYValue(), "Label1"),
Point(randomYValue(), "Label2"),
Point(randomYValue(), "Label3"),
Point(randomYValue(), "Label4"),
Point(randomYValue(), "Label5"),
Point(randomYValue(), "Label6"),
Point(randomYValue(), "Label7")
)
)
)
var horizontalOffset by mutableStateOf(0f)
var pointDrawerType by mutableStateOf(Filled)
val pointDrawer: PointDrawer
get() {
return when (pointDrawerType) {
None -> NoPointDrawer
Filled -> FilledCircularPointDrawer()
Hollow -> HollowCircularPointDrawer()
}
}
private fun randomYValue(): Float = (100f * Math.random()).toFloat() + 45f
enum class PointDrawerType {
None,
Filled,
Hollow
}
}
| 11
|
Kotlin
|
0
| 1
|
c6b333fd18d38e49e0107aa4e847dd97180ed28f
| 1,897
|
compose-charts
|
Apache License 2.0
|
src/main/kotlin/xyz/chlamydomonos/hyphacraft/blocks/TumidusioHyphaHiddenBlock.kt
|
Chlamydomonos
| 832,406,228
| false
|
{"Kotlin": 139172, "Java": 3138}
|
package xyz.chlamydomonos.hyphacraft.blocks
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import xyz.chlamydomonos.hyphacraft.blocks.utils.ModProperties
class TumidusioHyphaHiddenBlock : Block(Properties.ofFullCopy(Blocks.GLASS)) {
override fun createBlockStateDefinition(builder: StateDefinition.Builder<Block, BlockState>) {
builder.add(ModProperties.PHASE)
}
}
| 0
|
Kotlin
|
0
| 0
|
ee09cd02a3a0d2e1dbf751849280e55ab9cd5dd1
| 543
|
HyphaCraft
|
MIT License
|
app/src/main/java/com/adeen/notesappkotlin/viewmodel/NoteViewModelFactory.kt
|
Adeen-Ayub-Vine
| 865,577,580
| false
|
{"Kotlin": 18116}
|
package com.adeen.notesappkotlin.viewmodel
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.adeen.notesappkotlin.repository.NoteRepository
class NoteViewModelFactory(val app: Application, private val noteRepository: NoteRepository): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return NoteViewModel(app,noteRepository) as T
}
}
| 0
|
Kotlin
|
0
| 0
|
fb3802c61ede88b14e764f5724beb32d83f9b517
| 465
|
Notes-App-Kotlin
|
MIT License
|
app/src/main/java/com/igorg/sicredevent/presentation/base/adapter/ListItem.kt
|
igorpk10
| 544,523,016
| false
| null |
package com.igorg.sicredevent.presentation.base.adapter
interface ListItem {
val key: Long
fun areItemsTheSame(other: ListItem) = this.key == other.key
fun areContentsTheSame(other: ListItem) = this == other
}
| 0
|
Kotlin
|
0
| 0
|
b27436c49fc49ac301d10e0de254483b1d93cc06
| 225
|
sicredEventos
|
MIT License
|
kompress/common/test/me/devnatan/kompress/ZLIB.kt
|
DevNatan
| 678,151,355
| false
|
{"Kotlin": 4362}
|
package me.devnatan.kompress
import kotlin.test.Test
import kotlin.test.assertEquals
class ZLIB {
@Test
fun `zlib inflate and deflate`() {
val text = "Hello, this is a test string."
val compressed = zlibDeflate(text.encodeToByteArray())
assertEquals(
expected = "[31, -117, 8, 0, 0, 0, 0, 0, 0, 19, -13, 72, -51, -55, -55, -41, 81, 40, -55, -56, 44, 86, 0, -94, 68, -123, -110, -44, -30, 18, -123, -30, -110, -94, -52, -68, 116, 61, 0, 20, -121, -54]",
actual = compressed.contentToString(),
)
val decompressed = zlibInflate(compressed)
assertEquals(
expected = text,
actual = decompressed.decodeToString(),
)
}
}
| 1
|
Kotlin
|
0
| 2
|
baf84813b18bde817ed711d1496a2bec59b21ffe
| 734
|
kompress
|
MIT License
|
app/src/main/kotlin/com/absinthe/kage/connect/tcp/IPacketWriter.kt
|
zhaobozhen
| 223,542,983
| false
| null |
package com.absinthe.kage.connect.tcp
interface IPacketWriter {
fun writePacket(packet: Packet)
fun shutdown()
}
| 1
|
Kotlin
|
5
| 25
|
71dc5f8ee51b3b566723455fbc4b019845c2a347
| 121
|
Kage
|
Apache License 2.0
|
app/src/main/java/com/egeysn/githubapp/data/local/UserDatabase.kt
|
egeysn
| 620,311,795
| false
| null |
package com.egeysn.githubapp.data.local
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.egeysn.githubapp.data.local.entities.FavEntity
import com.egeysn.githubapp.data.local.entities.UserEntity
@Database(
entities = [UserEntity::class, FavEntity::class],
version = 8,
exportSchema = false
)
@TypeConverters(DatabaseConverters::class)
abstract class UserDatabase : RoomDatabase() {
abstract val dao: UserDao
}
| 0
|
Kotlin
|
0
| 0
|
fbb8fe0b0bb71bada7741ff2d58d3905e31ef35b
| 490
|
AndroidSampleGithubApp
|
Apache License 2.0
|
app/src/main/java/com/erdemserhat/harmonyhaven/data/local/entities/JwtTokenEntity.kt
|
erdemserhat
| 752,867,053
| false
|
{"Kotlin": 445738}
|
package com.erdemserhat.harmonyhaven.data.local.entities
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Represents a JWT token entity in the 'jwt_token' table of the database.
*
* This data class defines the structure of a JWT token record stored in the database.
* Each property maps to a column in the 'jwt_token' table.
*
* @property id The unique identifier of the JWT token record. It is set to 1 by default and serves as the primary key.
* @property token The JWT token string that is stored in the database.
*/
@Entity(tableName = "jwt_token")
data class JwtTokenEntity(
@PrimaryKey
val id: Int = 1,
val token: String
)
| 6
|
Kotlin
|
1
| 16
|
b817eb5ce99bccc2bc81042040d50382d5d82b57
| 669
|
HarmonyHavenAndroidClient
|
Apache License 2.0
|
kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/tags/RuntimeTagExtensionTest.kt
|
kotest
| 47,071,082
| false
| null |
package com.sksamuel.kotest.engine.tags
import io.kotest.assertions.fail
import io.kotest.core.Tag
import io.kotest.core.config.ProjectConfiguration
import io.kotest.core.extensions.RuntimeTagExpressionExtension
import io.kotest.core.extensions.RuntimeTagExtension
import io.kotest.core.annotation.Isolate
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.spec.style.StringSpec
import io.kotest.engine.TestEngineLauncher
import io.kotest.engine.listener.NoopTestEngineListener
import io.kotest.matchers.collections.shouldBeEmpty
object MyRuntimeExcludedTag : Tag()
@Isolate
class RuntimeTagExtensionTest : StringSpec() {
init {
"Tests with tag should not execute when excluded by a RuntimeTagExtension" {
val c = ProjectConfiguration()
c.registry.add(RuntimeTagExtension(included = emptySet(), excluded = setOf(MyRuntimeExcludedTag)))
TestEngineLauncher(NoopTestEngineListener)
.withClasses(TestWithTag::class)
.launch()
.errors.shouldBeEmpty()
}
"Tests with tag should not execute when excluded by a RuntimeTagExpressionExtension" {
val c = ProjectConfiguration()
c.registry.add(RuntimeTagExpressionExtension("!MyRuntimeExcludedTag"))
TestEngineLauncher(NoopTestEngineListener)
.withClasses(TestWithTag::class)
.launch()
.errors.shouldBeEmpty()
}
}
}
private class TestWithTag : FunSpec() {
init {
test("Test marked with a runtime excluded tag").config(tags = setOf(MyRuntimeExcludedTag)) {
fail("boom")
}
}
}
| 98
|
Kotlin
|
570
| 3,789
|
a341cdfccdc85162bfc31cfe6365768d9ab0f113
| 1,613
|
kotest
|
Apache License 2.0
|
hw5/src/main/kotlin/ru/itmo/base/DrawingApi.kt
|
KirillKurdyukov
| 538,702,916
| false
| null |
package ru.itmo.base
import kotlin.math.sign
interface DrawingApi {
fun drawCircle(p: Point, r: Double = VERTEX_RADIUS)
fun drawLine(x: Point, y: Point)
fun drawGraph()
}
class Point(
_x: Double,
_y: Double
) {
val x = _x
get() = field * WIDTH / 2 + WIDTH / 2 + (-1 * field.sign) * (VERTEX_RADIUS + PADDING)
val y = _y
get() = field * HEIGHT / 2 + HEIGHT / 2 + (-1 * field.sign) * (VERTEX_RADIUS + PADDING)
}
const val WIDTH = 1200
const val HEIGHT = 800
const val PADDING = 2
const val VERTEX_RADIUS = 20.0
| 0
|
Kotlin
|
1
| 1
|
7f93a94c1ec72cc033e57d44c15439f584b02814
| 559
|
software-design
|
MIT License
|
app/src/main/java/com/recordapp/record/RecordAudioRecordViewActivity.kt
|
yihu5566
| 204,427,289
| false
| null |
package com.recordapp.record
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.mp3library.MP3Recorder
import com.recordapp.record.view.CircleProgressView
import kotlinx.android.synthetic.main.activity_record_view.*
import java.io.File
import java.io.IOException
class RecordAudioRecordViewActivity : AppCompatActivity(), View.OnClickListener {
private var circle_progress: CircleProgressView? = null
private var tv_progress: TextView? = null
private var isStopRecord: Boolean = false
private var currentProgress: Int = 0
private var textView: TextView? = null
/**
* 是否暂停标志位
*/
private var isPause: Boolean = false
/**
* 记录需要合成的几段amr语音文件
*/
var list: ArrayList<String>? = null
var myRecAudioFile: File? = null
val SUFFIX = ".mp3"
/**
* 录音保存路径
*/
var myRecAudioDir: File? = null
/**
* 文件存在
*/
var sdcardExit: Boolean = false
/**
* 第一次进入状态
*/
private var isRecord: Boolean = true
/**
* 存儲文件路徑
*/
var pathStr1: String? = null
var finishFile: File? = null
var mRecorder: MP3Recorder? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_record_view)
circle_progress = findViewById(R.id.circle_progress)
tv_progress = findViewById(R.id.tv_progress)
textView = findViewById(R.id.tv_play_state)
initData()
initListener()
}
private fun initData() {
//初始化list
list = ArrayList()
// 判断sd Card是否插入
sdcardExit = Environment.getExternalStorageState() == android.os.Environment.MEDIA_MOUNTED
// 取得sd card路径作为录音文件的位置
if (sdcardExit) {
pathStr1 = Environment.getExternalStorageDirectory().path + "/super_start"
myRecAudioDir = File(pathStr1!!)
if (!myRecAudioDir!!.exists()) {
myRecAudioDir!!.mkdirs()
Log.v("录音", "创建录音文件!" + myRecAudioDir!!.exists())
}
}
}
private fun initListener() {
btn_play_or_pause.setOnClickListener(this)
btn_stop.setOnClickListener(this)
}
override fun onClick(view: View) {
when (view.id) {
R.id.btn_play_or_pause -> onRecord()
R.id.btn_stop -> finishRecord()
}
}
private fun onRecord() {
if (isRecord) {
isRecord = false
list!!.clear()
startRecord()
return
}
if (isPause) {
startRecord()
} else {
pauseRecord()
}
}
fun startRecord() {
try {
textView!!.text = "暂停录音"
isPause = false
isStopRecord = false
val mMinute1 = getTime()
myRecAudioFile = File(myRecAudioDir, mMinute1 + SUFFIX)
try {
// 初始化录音工具类(mp3library库中),传入录音保存的路径
mRecorder = MP3Recorder(myRecAudioFile)
// 开始录音
mRecorder!!.start()
} catch (e: Exception) {
e.printStackTrace()
}
btn_play_or_pause.setBackgroundResource(R.drawable.ic_pause_circle_filled_black_24dp)
circle_progress!!.startAnimProgress()
//监听进度条进度
circle_progress!!.setOnAnimProgressListener(
object : CircleProgressView.OnAnimProgressListener {
override fun valueUpdate(progress: Int) {
currentProgress = progress
tv_progress!!.text = progress.toString()
}
override fun recordFinish(progress: Int) {
currentProgress = progress
tv_progress!!.text = progress.toString()
val builder = AlertDialog.Builder(this@RecordAudioRecordViewActivity)
builder.setMessage("录音完成了!").setPositiveButton("确认") { dialogInterface, i ->
finishRecord()
}.show()
}
}
)
} catch (e: IOException) {
e.printStackTrace()
}
}
fun pauseRecord() {
isPause = true
isStopRecord = false
//当前正在录音的文件名,全程
list!!.add(myRecAudioFile!!.path)
stopRecord()
//计时停止
circle_progress!!.pauseRecord()
}
protected fun stopRecord() {
if (mRecorder != null && !isStopRecord) {
try {
if (mRecorder != null) {
mRecorder!!.stop()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
textView!!.text = "开始录音"
circle_progress!!.stopRecord()
// Toast.makeText(this, R.string.toast_recording_stop, Toast.LENGTH_SHORT).show();
isStopRecord = true
btn_play_or_pause.setBackgroundResource(R.drawable.ic_play_circle_filled_black_24dp)
}
fun finishRecord() {
if (isPause) {
//在暂停状态按下结束键,处理list就可以了
getInputCollection(list!!)
} else {
textView!!.text = "开始录音"
circle_progress!!.stopRecord()
btn_play_or_pause.setBackgroundResource(R.drawable.ic_play_circle_filled_black_24dp)
if (list!!.size > 0) {
//在正在录音时,处理list里面的和正在录音的语音
list!!.add(myRecAudioFile!!.path)
try {
if (mRecorder != null) {
mRecorder!!.stop()
mRecorder = null
}
} catch (e: Exception) {
e.printStackTrace()
}
isStopRecord = true
//生成处理后的文件
getInputCollection(list!!)
} else {
//若录音没有经过任何暂停
try {
if (mRecorder != null) {
mRecorder!!.stop()
mRecorder = null
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
val intent = Intent(this, MainActivity::class.java)
if (list!!.size > 0) {
intent.putExtra("record_url", finishFile!!.absolutePath)
} else {
intent.putExtra("record_url", myRecAudioFile!!.absolutePath)
}
setResult(Activity.RESULT_OK, intent)
finish()
}
/**
* activity的生命周期,stop时关闭录音资源
*/
override fun onStop() {
// TODO Auto-generated method stub
try {
if (mRecorder != null) {
mRecorder!!.stop()
mRecorder = null
}
} catch (e: Exception) {
e.printStackTrace()
}
super.onStop()
}
fun getTime(): String {
return "lame_" + System.currentTimeMillis()
}
/**
* @return 将合并的流用字符保存
*/
fun getInputCollection(list: ArrayList<String>) {
// 创建音频文件,合并的文件放这里
finishFile = File(list[0])
//list里面为暂停录音 所产生的 几段录音文件的名字,中间几段文件的减去前面的6个字节头文件
for (i in list.indices) {
if (i != 0) {
var heBingMp3 = CaoZuoMp3Utils.heBingMp3(finishFile!!.absolutePath, list[i], getTime())
finishFile = File(heBingMp3)
}
println("合成文件长度:" + finishFile!!.length())
}
if (list.size > 1) {
deleteListRecord()
}
}
private fun deleteListRecord() {
for (i in list!!.indices) {
val file = File(list!!.get(i))
if (file.exists()) {
file.delete()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
72704389c50f4670615079d1b03cecc2bea79471
| 8,100
|
AndroidRecordApp
|
Apache License 2.0
|
feature/movie-details-compose/src/main/kotlin/io/petros/movies/movie_details_compose/di/koin/MovieDetailsModule.kt
|
ParaskP7
| 148,126,048
| false
| null |
package io.petros.movies.movie_details_compose.di.koin
import io.petros.movies.movie_details_compose.MovieDetailsViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
private fun viewModelModule() = module {
viewModel { MovieDetailsViewModel(get()) }
}
@Suppress("unused")
fun movieDetailsComposeModule() = listOf(
viewModelModule(),
)
| 0
|
Kotlin
|
21
| 130
|
c86a669c4c21a2702a63404e6abf2547c3cec3fd
| 379
|
sample-code-movies
|
Apache License 2.0
|
app/src/main/java/com/eye/eye/MainActivity.kt
|
HelloWorldFeng
| 282,585,640
| false
| null |
package com.eye.eye
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.eye.eye.event.MessageEvent
import com.eye.eye.event.RefreshEvent
import com.eye.eye.event.SwitchPageEvent
import com.eye.eye.extension.logD
import com.eye.eye.extension.setOnClickListenter
import com.eye.eye.extension.showToas
import com.eye.eye.logic.network.EyeNetWork
import com.eye.eye.logic.network.api.MainPageService
import com.eye.eye.ui.common.ui.BaseActivity
import com.eye.eye.ui.community.CommunityFragment
import com.eye.eye.ui.home.HomePageFragment
import com.eye.eye.ui.login.LoginActivity
import com.eye.eye.ui.mine.MineFragment
import com.eye.eye.ui.notification.NotificationFragment
import com.eye.eye.util.DialogAppraiseTipsWorker
import com.eye.eye.util.GlobalUtil
import kotlinx.android.synthetic.main.layout_bottom_navigation_bar.*
import kotlinx.android.synthetic.main.layout_bottom_navigation_bar.view.*
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.greenrobot.eventbus.EventBus
/*
* Eye的主界面
* */
class MainActivity : BaseActivity() {
private var backPressTime = 0L
private var homePageFragement: HomePageFragment? = null
private var communityFragement: CommunityFragment?= null
private var notificationFragment: NotificationFragment? = null
private var mineFragment: MineFragment ?= null
private val fragmentManager: FragmentManager by lazy { supportFragmentManager }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun setupViews() {
observe()
//点击tabBar时通知主界面和tabBar切换
setOnClickListenter(btnHomePage, btnCommunity, btnNotification, ivRelease, btnMine) {
when (this) {
btnHomePage ->{
notificationUiRefresh(0)
setTabSelection(0)
}
btnCommunity ->{
notificationUiRefresh(1)
setTabSelection(1)
}
btnNotification ->{
notificationUiRefresh(2)
setTabSelection(2)
}
ivRelease ->{
LoginActivity.start(this@MainActivity)
}
btnMine ->{
notificationUiRefresh(3)
setTabSelection(3)
}
}
}
setTabSelection(0)
}
override fun onMessageEvent(message: MessageEvent) {
super.onMessageEvent(message)
when{
message is SwitchPageEvent && message.activityClass==this::class.java ->{
btnCommunity.performClick() //模拟点击的
}
else ->{}
}
}
private fun setTabSelection(index: Int) {
clearAllSelected()
fragmentManager.beginTransaction().apply {
hideFragment(this)
when (index) {
0 -> {
ivHomePage.isSelected = true
tvHomePage.isSelected = true
if (homePageFragement == null) {
homePageFragement = HomePageFragment.newInstance()
add(R.id.homeActivityFragContainer, homePageFragement!!)
} else {
show(homePageFragement!!)
}
}
1 -> {
ivCommunity.isSelected = true
tvCommunity.isSelected = true
if (communityFragement == null) {
communityFragement = CommunityFragment.newInstance()
add(R.id.homeActivityFragContainer, communityFragement!!)
} else {
show(communityFragement!!)
}
}
2 -> {
ivNotification.isSelected = true
tvNotification.isSelected = true
if (notificationFragment == null) {
notificationFragment = NotificationFragment.newInstance()
add(R.id.homeActivityFragContainer, notificationFragment!!)
} else {
show(notificationFragment!!)
}
}
3 -> {
ivMine.isSelected = true
tvMine.isSelected = true
if (mineFragment == null) {
mineFragment = MineFragment.newInstance()
add(R.id.homeActivityFragContainer, mineFragment!!)
} else {
show(mineFragment!!)
}
}
else ->{
ivHomePage.isSelected = true
tvHomePage.isSelected = true
if (homePageFragement == null) {
homePageFragement = HomePageFragment.newInstance()
add(R.id.homeActivityFragContainer, homePageFragement!!)
} else {
show(homePageFragement!!)
}
}
}
}.commitAllowingStateLoss()
}
private fun hideFragment(transaction: FragmentTransaction) {
transaction.run {
if (homePageFragement != null) hide(homePageFragement!!)
if (communityFragement != null) hide(communityFragement!!)
if (notificationFragment != null) hide(notificationFragment!!)
if (mineFragment != null) hide(mineFragment!!)
}
}
private fun clearAllSelected() {
ivHomePage.isSelected = false
tvHomePage.isSelected = false
ivCommunity.isSelected = false
tvCommunity.isSelected = false
ivNotification.isSelected = false
tvNotification.isSelected = false
ivMine.isSelected = false
tvMine.isSelected = false
}
//发出消息事件
private fun notificationUiRefresh(index: Int) {
when (index) {
0 -> {
if (ivHomePage.isSelected) EventBus.getDefault().post(RefreshEvent(HomePageFragment::class.java))
}
1 -> {
if (ivCommunity.isSelected) EventBus.getDefault().post(RefreshEvent(CommunityFragment::class.java))
}
2 -> {
if (ivNotification.isSelected) EventBus.getDefault().post(RefreshEvent(NotificationFragment::class.java))
}
3 -> {
if (ivMine.isSelected) EventBus.getDefault().post(RefreshEvent(MineFragment::class.java))
}
}
}
//WorkManager组件,执行弹出框后台任务
private fun observe() {
WorkManager.getInstance(this).getWorkInfoByIdLiveData(DialogAppraiseTipsWorker.showDialogWorkRequest.id).observe(this, Observer { workInfo ->
logD(TAG, "observe: workInfo.state = ${workInfo.state}")
if (workInfo.state == WorkInfo.State.SUCCEEDED) {
WorkManager.getInstance(this).cancelAllWork()
} else if (workInfo.state == WorkInfo.State.RUNNING) {
if (isActive) {
DialogAppraiseTipsWorker.showDialog(this)
WorkManager.getInstance(this).cancelAllWork()
}
}
})
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount > 0) {
supportFragmentManager.popBackStack()
}else{
processBackPressed()
}
}
private fun processBackPressed() {
val now = System.currentTimeMillis()
if (now - backPressTime > 2000){
String.format(GlobalUtil.getString(R.string.press_again_to_exit),GlobalUtil.appName).showToas()
backPressTime = now
}else{
super.onBackPressed()
}
}
companion object {
fun start(context: Context) {
context.startActivity(Intent(context, MainActivity::class.java))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4ca1b3b66266366b3ad6a2b64d8341f3fd946324
| 8,323
|
Eye
|
Apache License 2.0
|
app/src/main/java/loodos/droid/bitcointicker/ui/auth/AuthViewModel.kt
|
BatuhanGunes
| 360,654,341
| false
| null |
package loodos.droid.bitcointicker.ui.auth
import android.content.Intent
import android.view.View
import androidx.lifecycle.ViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import loodos.droid.bitcointicker.data.repositories.UserRepository
class AuthViewModel(private val repository: UserRepository) : ViewModel() {
// email and password for the input
var email: String? = null
var password: String? = null
// auth listener
var authListener: AuthListener? = null
// disposable to dispose the Completable
private val disposables = CompositeDisposable()
val user by lazy {
repository.currentUser()
}
/**
* function to perform login
*/
fun login() {
// validating email and password
if (email.isNullOrEmpty() || password.isNullOrEmpty()) {
authListener?.onFailure("Invalid email or password")
return
}
//authentication started
authListener?.onStarted()
// calling login from repository to perform the actual authentication
val disposable = repository.login(email!!, password!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
authListener?.onSuccess()
}, {
authListener?.onFailure(it.message!!)
})
disposables.add(disposable)
}
/**
* function to perform signup
*/
fun signup() {
// validating email and password
if (email.isNullOrEmpty() || password.isNullOrEmpty()) {
authListener?.onFailure("Please input all values")
return
}
//authentication started
authListener?.onStarted()
// calling login from repository to perform the actual authentication
val disposable = repository.register(email!!, password!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
authListener?.onSuccess()
}, {
authListener?.onFailure(it.message!!)
})
disposables.add(disposable)
}
/**
* Opens the Signup Activity with a request from the user.
*/
fun goToSignup(view: View) {
Intent(view.context, SignupActivity::class.java).also {
view.context.startActivity(it)
}
}
/**
* Opens the Login Activity with a request from the user.
*/
fun goToLogin(view: View) {
Intent(view.context, LoginActivity::class.java).also {
view.context.startActivity(it)
}
}
/**
* disposing the disposables
*/
override fun onCleared() {
super.onCleared()
disposables.dispose()
}
}
| 0
|
Kotlin
|
1
| 0
|
40507e84762ef9a69c12de52d183119780401109
| 2,916
|
BitcoinTicker
|
Apache License 2.0
|
example/src/androidTest/kotlin/com/buildkite/test/collector/android/example/ExampleTestCollector.kt
|
buildkite
| 519,058,398
| false
|
{"Kotlin": 42008, "Shell": 1804}
|
package com.buildkite.test.collector.android.example
import com.buildkite.test.collector.android.InstrumentedTestCollector
/**
* Configures `ExampleTestCollector` with Buildkite test collector configurations.
* Values are derived from local/CI environment variables and set in [BuildConfig] at build time.
*/
class ExampleTestCollector : InstrumentedTestCollector(
apiToken = BuildConfig.BUILDKITE_ANALYTICS_TOKEN,
isDebugEnabled = BuildConfig.BUILDKITE_ANALYTICS_DEBUG_ENABLED
)
| 3
|
Kotlin
|
3
| 4
|
dfd4711359973409da8d7c359dad7f88ca5257b8
| 493
|
test-collector-android
|
MIT License
|
app/src/main/java/hu/hm/icguide/ui/maps/MapFragment.kt
|
mherczku
| 413,102,440
| false
|
{"Kotlin": 92979}
|
package hu.hm.icguide.ui.maps
import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.StringRes
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.preference.PreferenceManager
import co.zsmb.rainbowcake.base.RainbowCakeFragment
import co.zsmb.rainbowcake.hilt.getViewModelFromFactory
import co.zsmb.rainbowcake.navigation.navigator
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MapStyleOptions
import com.google.android.gms.maps.model.MarkerOptions
import dagger.hilt.android.AndroidEntryPoint
import hu.hm.icguide.R
import hu.hm.icguide.databinding.FragmentMapsBinding
import hu.hm.icguide.extensions.toast
import hu.hm.icguide.models.Shop
import hu.hm.icguide.ui.add.AddDialog
import hu.hm.icguide.ui.detail.DetailFragment
import timber.log.Timber
@AndroidEntryPoint
class MapFragment(private val targetShop: Shop? = null) :
RainbowCakeFragment<MapViewState, MapViewModel>(),
ActivityCompat.OnRequestPermissionsResultCallback {
override fun provideViewModel() = getViewModelFromFactory()
override fun getViewResource() = R.layout.fragment_maps
private lateinit var map: GoogleMap
private var isPermissionGranted = false
private lateinit var permReqLauncher: ActivityResultLauncher<String>
private lateinit var binding: FragmentMapsBinding
override fun onStart() {
super.onStart()
viewModel.load()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentMapsBinding.bind(view)
setupToolbar()
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(callback)
}
private fun setupToolbar() {
binding.toolbar.setNavigationOnClickListener {
navigator?.pop()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
permReqLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if (it) {
toast(getString(R.string.permission_granted))
isPermissionGranted = true
enableMyLocation()
} else {
toast(getString(R.string.permission_denied))
}
}
handleLocationPermission()
}
@SuppressLint("MissingPermission")
private fun enableMyLocation() {
if (!::map.isInitialized) return
map.isMyLocationEnabled = isPermissionGranted
}
override fun render(viewState: MapViewState) {
if (!::map.isInitialized) return
Timber.d("Received ${viewState.markers.size} markers to display in map")
viewState.markers.forEach {
val marker = map.addMarker(
MarkerOptions().position(LatLng(it.geoPoint.latitude, it.geoPoint.longitude))
.title(it.name)
)
marker?.tag = it.id
if(it.id == targetShop?.id){
map.moveCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(
targetShop.geoPoint.latitude,
targetShop.geoPoint.longitude
), 15F
)
)
marker?.showInfoWindow()
}
}
}
@SuppressLint("MissingPermission")
private val callback = OnMapReadyCallback { googleMap ->
map = googleMap
googleMap.uiSettings.setAllGesturesEnabled(true)
googleMap.isMyLocationEnabled = isPermissionGranted
val sp = PreferenceManager.getDefaultSharedPreferences(requireActivity().applicationContext)
val darkMode = sp.getBoolean("darkTheme", false)
if (darkMode) googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
requireContext(),
R.raw.mapstyle_dark
)
)
val budapest = LatLng(47.4979, 19.0402)
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(budapest, 10F))
googleMap.setOnMapLongClickListener {
Timber.d("Long clicked on map at $it, open addDialog")
AddDialog(it).show(childFragmentManager, null)
}
googleMap.setOnInfoWindowClickListener {
Timber.d("Clicked on ${it.id} marker's info window")
it.tag ?: return@setOnInfoWindowClickListener
Timber.d("Navigate to DetailFragment id: ${it.tag}")
navigator?.add(DetailFragment(it.tag!! as String))
}
googleMap.setOnMarkerClickListener {
val distance: String = if(!isPermissionGranted){
getString(R.string.distance_no_permission)
} else "${getString(R.string.distance)} ${String.format("%.1f" ,getDistance(it.position))} km"
it.snippet = distance
false
}
}
private fun showRationaleDialog(
@StringRes title: Int = R.string.rationale_dialog_title,
@StringRes explanation: Int,
onPositiveButton: () -> Unit,
onNegativeButton: () -> Boolean? = { navigator?.pop() }
) {
val alertDialog = AlertDialog.Builder(context)
.setTitle(title)
.setMessage(explanation)
.setCancelable(false)
.setPositiveButton(R.string.proceed) { dialog, _ ->
dialog.cancel()
onPositiveButton()
}
.setNegativeButton(R.string.exit) { _, _ -> onNegativeButton() }
.create()
alertDialog.show()
}
private fun handleLocationPermission() {
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
requireActivity(),
Manifest.permission.ACCESS_FINE_LOCATION
)
) {
showRationaleDialog(
explanation = R.string.location_permission_explanation,
onPositiveButton = this::requestLocationPermission
)
} else {
requestLocationPermission()
}
} else {
isPermissionGranted = true
}
}
private fun requestLocationPermission() {
permReqLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
@SuppressLint("MissingPermission")
private fun getDistance(position: LatLng): Float {
if(!isPermissionGranted) return 0F
val location = Location(LocationManager.GPS_PROVIDER)
location.latitude = position.latitude
location.longitude = position.longitude
return location.distanceTo(map.myLocation) / 1000
}
}
| 0
|
Kotlin
|
0
| 0
|
3cda7ddd6994ffd62ea05f46c758f69452b9e761
| 7,546
|
iceCreamGuide
|
Apache License 2.0
|
app/src/main/java/com/bourdi_bay/portfolioquickglance/SwipeToDeleteCallback.kt
|
bourdibay
| 185,835,876
| false
| null |
package com.bourdi_bay.portfolioquickglance
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
class SwipeToDeleteCallback(context: Context, private val swipeDeleteDelegate: (Int) -> Unit) :
ItemTouchHelper.SimpleCallback(
0,
ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
) {
private val icon = ContextCompat.getDrawable(context, android.R.drawable.ic_menu_delete)!!
private val background = ColorDrawable(Color.RED)
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
swipeDeleteDelegate(viewHolder.adapterPosition)
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
val itemView = viewHolder.itemView
val backgroundCornerOffset = 20 //so background is behind the rounded corners of itemView
val iconMargin = (itemView.height - icon.intrinsicHeight) / 2
val iconTop = itemView.top + (itemView.height - icon.intrinsicHeight) / 2
val iconBottom = iconTop + icon.intrinsicHeight
when {
dX > 0 -> { // Swiping to the right
val iconLeft = itemView.left + iconMargin
val iconRight = itemView.left + iconMargin + icon.intrinsicWidth
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
background.setBounds(
itemView.left, itemView.top,
itemView.left + dX.toInt() + backgroundCornerOffset, itemView.bottom
)
}
dX < 0 -> { // Swiping to the left
val iconLeft = itemView.right - iconMargin - icon.intrinsicWidth
val iconRight = itemView.right - iconMargin
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
background.setBounds(
itemView.right + dX.toInt() - backgroundCornerOffset,
itemView.top, itemView.right, itemView.bottom
)
}
else -> // view is unSwiped
background.setBounds(0, 0, 0, 0)
}
background.draw(c)
icon.draw(c)
}
}
| 0
|
Kotlin
|
0
| 0
|
49c785158789dafc06208ab90a7d354e9324e73c
| 2,815
|
PortfolioQuickGlance
|
Apache License 2.0
|
masterswitch/src/main/java/com/smp/masterswitchpreference/MasterSwitchSwitchPreference.kt
|
svenoaks
| 284,879,301
| false
| null |
package com.smp.masterswitchpreference
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.preference.PreferenceViewHolder
import androidx.preference.SwitchPreferenceCompat
internal class MasterSwitchSwitchPreference : SwitchPreferenceCompat {
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
internal lateinit var attrs: MasterSwitchPreferenceAttrs
private lateinit var background: View
private lateinit var switch: SwitchCompat
private lateinit var text: TextView
override fun onBindViewHolder(holder: PreferenceViewHolder?) {
super.onBindViewHolder(holder)
fun applyTextColor(textView: TextView) {
textView.setTextColor(attrs.switchTextColor)
}
fun applySwitchColor() {
switch.thumbDrawable?.let {
DrawableCompat.setTint(it, attrs.switchThumbColor)
}
switch.trackDrawable?.let {
DrawableCompat.setTint(it, attrs.switchTrackColor)
}
}
holder?.itemView?.let { view ->
background = view
switch = view.findViewById(R.id.switchWidget)
text = view.findViewById(android.R.id.title)
applySwitchColor()
if (switch.isChecked) {
applySwitchOnBackgroundColor()
} else {
applySwitchOffBackgroundColor()
}
applyTextColor(text)
}
}
internal fun applySwitchOnBackgroundColor() {
background.setBackgroundColor(attrs.switchOnBackgroundColor)
}
internal fun applySwitchOffBackgroundColor() {
background.setBackgroundColor(attrs.switchOffBackgroundColor)
}
}
| 3
|
Kotlin
|
2
| 6
|
cc3557da9dd804f7378a98a9c394610eac4d9b67
| 2,217
|
MasterSwitchPreference
|
Apache License 2.0
|
kotlin-typescript/src/jsMain/generated/typescript/isJSDocSeeTag.contract.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Automatically generated - do not modify!
package typescript
import kotlin.contracts.contract
@Suppress(
"NOTHING_TO_INLINE",
"CANNOT_CHECK_FOR_EXTERNAL_INTERFACE",
"CANNOT_CHECK_FOR_ERASED",
"ERROR_IN_CONTRACT_DESCRIPTION"
)
inline fun isJSDocSeeTag(node: Node): Boolean /* node is JSDocSeeTag */ {
contract {
returns(true) implies (node is JSDocSeeTag)
}
return isJSDocSeeTagRaw(node)
}
| 38
|
Kotlin
|
162
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 432
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/udacity/shoestore/models/ShoeListViewModel.kt
|
ajaysinghthakur
| 469,336,714
| false
|
{"Kotlin": 14154}
|
package com.udacity.shoestore.models
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import timber.log.Timber
class ShoeListViewModel: ViewModel() {
private var _shoeList = MutableLiveData<MutableList<Shoe>>()
val shoeList: LiveData<MutableList<Shoe>>
get() = _shoeList
init {
Timber.i("in init")
_shoeList.value = mutableListOf()
addShoe("Shoe10", 8.0, "Company10", "desc10")
addShoe("Go Run", size = 11.0, company = "Sketchers", description = "running shoes")
}
fun addShoe(name: String, size: Double, company: String, description: String) {
Timber.i("Adding shoe")
_shoeList.value?.add(Shoe(name, size, company, description))
Timber.i(_shoeList.value?.joinToString())
}
}
| 0
|
Kotlin
|
0
| 0
|
0a33f1b1787f2c3717d82489ef2bc2e57bf7f925
| 837
|
ShoeStore
|
MIT License
|
kotlin-ir-plugin/src/main/kotlin/com/bnorm/template/AnonymousClasses.kt
|
faucct
| 568,360,231
| false
|
{"Kotlin": 49642, "Java": 7663}
|
package com.bnorm.template
import kotlin.reflect.KClass
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class AnonymousClasses(@get:JvmName("v") val value: Array<KClass<*>>)
| 0
|
Kotlin
|
0
| 0
|
b9a3fcd93f82069a0fd6baa43daa9312e0734e8f
| 214
|
kotlin-persistent-coroutines
|
Apache License 2.0
|
app/src/main/java/com/shellmonger/apps/mynotes/ui/NoteDetailActivity.kt
|
harryhan24
| 135,485,673
| false
| null |
/*
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.shellmonger.apps.mynotes.ui
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import com.shellmonger.apps.mynotes.R
import kotlinx.android.synthetic.main.activity_note_detail.*
class NoteDetailActivity : AppCompatActivity() {
companion object {
private val TAG = this::class.java.simpleName
const val ARG_NOTE = "noteId"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_note_detail)
setSupportActionBar(note_detail_toolbar)
supportActionBar?.apply { setDisplayHomeAsUpEnabled(true) }
if (intent?.extras?.containsKey(ARG_NOTE) == true) {
val noteId = intent.extras.getString(ARG_NOTE)
loadFragment(noteId)
} else {
loadFragment(null)
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean
= when(item?.itemId) {
android.R.id.home -> navigateUpTo(Intent(this, NoteListActivity::class.java))
else -> super.onOptionsItemSelected(item)
}
private fun loadFragment(noteId: String?) {
Log.d(TAG, "Loading fragment for note $noteId")
val fragment = NoteDetailFragment()
noteId?.let {
fragment.arguments = Bundle().apply { putString(NoteDetailFragment.ARG_NOTE, noteId) }
}
supportFragmentManager
?.beginTransaction()
?.replace(R.id.note_detail_fragment, fragment)
?.commit()
}
}
| 0
|
Kotlin
|
0
| 0
|
ca9233cc2ba944c9592b790bd27cd9a041d77697
| 2,232
|
android-kotlin-notes
|
Apache License 2.0
|
app/src/main/java/jez/synthesis/features/sequencer2/Sequencer2VM.kt
|
Ninjars
| 577,448,399
| false
|
{"Kotlin": 71773, "C++": 29687, "CMake": 2461, "Java": 2222, "C": 603}
|
package jez.synthesis.features.sequencer2
import androidx.compose.runtime.Stable
import androidx.compose.ui.unit.IntOffset
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bumble.appyx.navmodel.backstack.BackStack
import jez.synthesis.Consumer
import jez.synthesis.audiotrack.Sampler
import jez.synthesis.features.sequencer2.Sequencer2VM.Event
import jez.synthesis.navigation.NavTarget
import jez.synthesis.toViewState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class Sequencer2VM(
private val backStack: BackStack<NavTarget>,
) : Consumer<Event>, ViewModel() {
private val stateFlow = MutableStateFlow(
State(
isPlaying = false,
beatCount = 10,
toneCount = 10,
input = emptyList(),
)
)
val viewState: StateFlow<Sequencer2ViewState> =
stateFlow.toViewState(viewModelScope) { StateToViewState(it) }
val engineHandle = startEngine(100)
override fun accept(value: Event) {
TODO("Not yet implemented")
}
data class State(
// val sampler: Sampler?,
// val samplers: List<Sampler>,
val beatCount: Int,
val toneCount: Int,
// val bassNote: Note,
// val octave: Int,
val input: List<IntOffset>,
val isPlaying: Boolean,
// val isProcessing: Boolean,
// val bpm: Int,
)
sealed class Event {
data class SamplerListUpdate(val samplers: List<Sampler>) : Event()
data class SetGridCell(val position: IntOffset, val enabled: Boolean) : Event()
data class SetIsPlaying(val isPlaying: Boolean) : Event()
data class SelectedSampler(val index: Int) : Event()
object EditSampler : Event()
object CreateNewSampler : Event()
object Reset : Event()
}
private companion object {
external fun startEngine(cellCount: Int): Long
}
}
@Stable
data class Sequencer2ViewState(
val grid: Grid,
val isPlaying: Boolean,
// val sequencerIndex: Int,
// val sequencerNames: List<String>,
) {
data class Grid(
val width: Int,
val height: Int,
val selected: List<IntOffset>,
)
}
private object StateToViewState : (Sequencer2VM.State) -> Sequencer2ViewState {
override fun invoke(state: Sequencer2VM.State): Sequencer2ViewState =
Sequencer2ViewState(
isPlaying = state.isPlaying,
grid = Sequencer2ViewState.Grid(
width = state.beatCount,
height = state.toneCount,
selected = state.input,
),
)
}
| 0
|
Kotlin
|
0
| 0
|
65fae930d4ff21f8cdeab9d3517ffb75d96c26db
| 2,670
|
Synthesis
|
Apache License 2.0
|
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/rewards/AmountSelectorDialog.kt
|
google
| 95,704,578
| false
| null |
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.app.playhvz.screens.rewards
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.NumberPicker
import androidx.fragment.app.DialogFragment
import com.app.playhvz.R
import com.google.android.material.button.MaterialButton
class AmountSelectorDialog(
private val title: String,
private var confirmationResId: Int? = null,
private var cancelResId: Int? = null
) : DialogFragment() {
companion object {
private val TAG = AmountSelectorDialog::class.qualifiedName
}
private lateinit var customView: View
private lateinit var numberPicker: NumberPicker
var onConfirm: ((selectedNumber: Int) -> Unit)? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
customView = requireActivity().layoutInflater.inflate(R.layout.dialog_amount_selector, null)
numberPicker = customView.findViewById(R.id.dialog_number_picker)
numberPicker.minValue = 1
numberPicker.maxValue = 400
numberPicker.value = 10
if (confirmationResId == null) {
confirmationResId = R.string.reward_claim_code_dialog_button
}
if (cancelResId == null) {
cancelResId = R.string.button_cancel
}
val dialog = AlertDialog.Builder(requireContext())
.setTitle(title)
.setView(customView)
.create()
val positiveButton = customView.findViewById<MaterialButton>(R.id.positive_button)
positiveButton.setText(confirmationResId!!)
positiveButton.setOnClickListener {
onConfirm?.invoke(numberPicker.value)
dialog?.dismiss()
}
val negativeButton = customView.findViewById<MaterialButton>(R.id.negative_button)
negativeButton.setText(cancelResId!!)
negativeButton.setOnClickListener {
dialog?.dismiss()
}
return dialog
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Return already inflated custom view
return customView
}
fun setPositiveButtonCallback(okayCallback: (selectedNumber: Int) -> Unit) {
onConfirm = okayCallback
}
}
| 37
|
Kotlin
|
30
| 24
|
9e02fb706af61a336bda852f467a35f49bdcfec7
| 2,971
|
playhvz
|
Apache License 2.0
|
feature/home/main/src/main/java/com/civciv/app/home/main/di/MavericksViewModelModule.kt
|
fatih-ozturk
| 638,702,981
| false
|
{"Kotlin": 242210, "Shell": 932}
|
/*
* 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.civciv.app.home.main.di
import com.airbnb.mvrx.hilt.AssistedViewModelFactory
import com.airbnb.mvrx.hilt.MavericksViewModelComponent
import com.airbnb.mvrx.hilt.ViewModelKey
import com.civciv.app.home.main.HomeViewModel
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.multibindings.IntoMap
@Module
@InstallIn(MavericksViewModelComponent::class)
interface MavericksViewModelModule {
@Binds
@IntoMap
@ViewModelKey(HomeViewModel::class)
fun homesViewModelFactory(factory: HomeViewModel.Factory): AssistedViewModelFactory<*, *>
}
| 1
|
Kotlin
|
0
| 1
|
f2279d5fca8fe3416028905176467d17f82bc2e2
| 1,183
|
Civciv
|
Apache License 2.0
|
src/main/kotlin/com/deflatedpickle/flatlaf/intellijthemes/FlatCatppuccinMochaIJTheme.kt
|
DeflatedPickle
| 668,457,152
| false
| null |
package com.deflatedpickle.flatlaf.intellijthemes
object FlatCatppuccinMochaIJTheme : CatppuccinTheme("mocha") {
fun setup() = setup(FlatCatppuccinMochaIJTheme)
fun installLafInfo() = installLafInfo(name, FlatCatppuccinMochaIJTheme::class.java)
override fun getName() = "Catppuccin - Mocha"
}
| 0
|
Kotlin
|
0
| 0
|
cc543effb3f2b1d34ad001df0a605fcf43723a71
| 305
|
FlatCatppuccinIJTheme
|
MIT License
|
src/main/kotlin/com/easy/springboot/simpleloginbackend/SimpleLoginBackEndApplication.kt
|
fjxFork
| 157,513,112
| true
|
{"Kotlin": 2098, "HTML": 225}
|
package com.easy.springboot.simpleloginbackend
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class SimpleLoginBackEndApplication
fun main(args: Array<String>) {
runApplication<SimpleLoginBackEndApplication>(*args)
}
| 0
|
Kotlin
|
0
| 0
|
e1568134b17b85c24700f8542218982092508cbc
| 315
|
simple-login-back-end
|
ISC License
|
src/jvmMain/kotlin/org/jetbrains/jewel/samples/standalone/Main.kt
|
abd3lraouf
| 829,257,789
| false
|
{"Kotlin": 112511}
|
package org.jetbrains.jewel.samples.standalone
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.ResourceLoader
import androidx.compose.ui.res.loadImageBitmap
import androidx.compose.ui.res.loadSvgPainter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.Density
import androidx.compose.ui.window.application
import org.jetbrains.jewel.foundation.theme.JewelTheme
import org.jetbrains.jewel.foundation.util.JewelLogger
import org.jetbrains.jewel.intui.standalone.Inter
import org.jetbrains.jewel.intui.standalone.JetBrainsMono
import org.jetbrains.jewel.intui.standalone.theme.IntUiTheme
import org.jetbrains.jewel.intui.standalone.theme.createDefaultTextStyle
import org.jetbrains.jewel.intui.standalone.theme.createEditorTextStyle
import org.jetbrains.jewel.intui.standalone.theme.darkThemeDefinition
import org.jetbrains.jewel.intui.standalone.theme.default
import org.jetbrains.jewel.intui.standalone.theme.lightThemeDefinition
import org.jetbrains.jewel.intui.window.decoratedWindow
import org.jetbrains.jewel.intui.window.styling.dark
import org.jetbrains.jewel.intui.window.styling.light
import org.jetbrains.jewel.intui.window.styling.lightWithLightHeader
import org.jetbrains.jewel.samples.standalone.view.TitleBarView
import org.jetbrains.jewel.samples.standalone.viewmodel.MainViewModel
import org.jetbrains.jewel.ui.ComponentStyling
import org.jetbrains.jewel.window.DecoratedWindow
import org.jetbrains.jewel.window.styling.TitleBarStyle
import java.io.InputStream
fun main() {
JewelLogger
.getInstance("ProjectBuilder")
.info("Starting Project Builder")
val iconPath = "icons/app-icon.png"
application {
val textStyle = JewelTheme.createDefaultTextStyle(fontFamily = FontFamily.Inter)
val editorStyle = JewelTheme.createEditorTextStyle(fontFamily = FontFamily.JetBrainsMono)
val themeDefinition =
if (MainViewModel.theme.isDark()) {
JewelTheme.darkThemeDefinition(defaultTextStyle = textStyle, editorTextStyle = editorStyle)
} else {
JewelTheme.lightThemeDefinition(defaultTextStyle = textStyle, editorTextStyle = editorStyle)
}
IntUiTheme(
theme = themeDefinition,
styling = ComponentStyling.default().decoratedWindow(
titleBarStyle =
when (MainViewModel.theme) {
IntUiThemes.Light -> TitleBarStyle.lightWithLightHeader()
IntUiThemes.Dark -> TitleBarStyle.dark()
IntUiThemes.System ->
if (MainViewModel.theme.isDark()) {
TitleBarStyle.dark()
} else {
TitleBarStyle.lightWithLightHeader()
}
},
),
swingCompatMode = true,
) {
DecoratedWindow(
onCloseRequest = { exitApplication() },
title = "Project Builder",
icon = painterResource(iconPath),
) {
TitleBarView()
MainViewModel.currentView.content()
}
}
}
}
@OptIn(ExperimentalComposeUiApi::class)
private fun svgResource(
resourcePath: String,
loader: ResourceLoader = ResourceLoader.Default,
): Painter =
loader
.load(resourcePath)
.use { stream: InputStream ->
loadSvgPainter(stream, Density(1f))
}
| 0
|
Kotlin
|
0
| 0
|
4e54ab8504e43c8cb79aab78431c185f435d1ff0
| 3,765
|
project-builder
|
Apache License 2.0
|
app/src/main/java/org/coepi/android/domain/CenMatcher.kt
|
yibter
| 260,080,429
| true
|
{"Kotlin": 137981}
|
package org.coepi.android.domain
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import org.coepi.android.cen.Cen
import org.coepi.android.cen.CenKey
import org.coepi.android.domain.CenLogicImpl.Companion.cenLifetimeInSeconds
import org.coepi.android.extensions.toHex
interface CenMatcher {
fun match(cens: List<Cen>, keys: List<CenKey>, maxDate: UnixTime): List<CenKey>
}
class CenMatcherImpl(
private val cenLogic: CenLogic
) : CenMatcher {
override fun match(cens: List<Cen>, keys: List<CenKey>, maxDate: UnixTime): List<CenKey> =
if (cens.isEmpty()) {
emptyList()
} else {
runBlocking {
matchSuspended(cens, keys, maxDate)
}
}
private suspend fun matchSuspended(cens: List<Cen>, keys: List<CenKey>,
maxDate: UnixTime): List<CenKey> =
coroutineScope {
val censSet: Set<String> = cens.map { it.toHex() }.toHashSet()
keys.distinct().map { key ->
async(Default) {
if (match(censSet, key, maxDate)) {
key
} else {
null
}
}
}.awaitAll().filterNotNull()
}
private fun match(censSet: Set<String>, key: CenKey, maxDate: UnixTime): Boolean {
val secondsInAWeek: Long = 604800
val possibleCensCount = (secondsInAWeek / cenLifetimeInSeconds).toInt()
for (i in 0..possibleCensCount) {
val ts = maxDate.value - cenLifetimeInSeconds * i
val cen = cenLogic.generateCen(key, ts)
if (censSet.contains(cen.bytes.toHex())) {
return true
}
}
return false
}
}
| 0
| null |
0
| 0
|
e64a035f5b7a154733ef09db0d8d7c0d5cb5efa2
| 1,927
|
app-android
|
MIT License
|
src/main/kotlin/com/vk/admstorm/configuration/problems/actions/ShowProblemDescriptionAction.kt
|
VKCOM
| 454,408,302
| false
| null |
package com.vk.admstorm.configuration.problems.actions
import com.intellij.ide.IdeTooltip
import com.intellij.ide.IdeTooltipManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.components.panels.NonOpaquePanel
import com.vk.admstorm.configuration.phplinter.PhpLinterCheckers
import com.vk.admstorm.configuration.problems.panels.ProblemTreeNode
import com.vk.admstorm.utils.MyUiUtils
import java.awt.FlowLayout
import java.awt.Point
import javax.swing.JComponent
import javax.swing.JTree
import javax.swing.border.EmptyBorder
class ShowProblemDescriptionAction : DumbAwareAction() {
/**
* Show a tooltip with the passed [text] in the upper left corner
* of the passed [component].
* This tooltip will automatically disappear if you move the mouse.
* In text, you can use HTML to mark up elements.
*/
private fun showTooltip(text: String, component: JComponent) {
val panel = NonOpaquePanel(FlowLayout(FlowLayout.CENTER, 0, 0))
panel.border = EmptyBorder(10, 10, 10, 10)
panel.add(MyUiUtils.createTextInfoComponent(text))
val tooltip = object : IdeTooltip(component, Point(0, 0), panel) {
override fun canBeDismissedOnTimeout() = false
}
IdeTooltipManager.getInstance().show(tooltip, true)
}
override fun actionPerformed(e: AnActionEvent) {
val data = getSelectedNode(e) as? ProblemTreeNode ?: return
val problem = data.problem
val description = PhpLinterCheckers.nameToCheckerDoc[problem.name] ?: "no description"
showTooltip(description, e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as JComponent)
}
private fun getSelectedNode(event: AnActionEvent): Any? {
val tree = event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as? JTree
return tree?.selectionPath?.lastPathComponent
}
}
| 33
|
Kotlin
|
3
| 9
|
24e4616dce11e8f71ac68502085d2768d355d6c0
| 2,004
|
admstorm
|
MIT License
|
lib/src/commonMain/kotlin/app/moviebase/trakt/api/TraktRecommendationsApi.kt
|
MoviebaseApp
| 410,270,468
| false
| null |
package app.moviebase.trakt.api
import app.moviebase.trakt.TraktExtended
import app.moviebase.trakt.core.getByPaths
import app.moviebase.trakt.core.parameterExtended
import app.moviebase.trakt.core.parameterLimit
import app.moviebase.trakt.core.parameterPage
import app.moviebase.trakt.model.TraktShow
import io.ktor.client.HttpClient
class TraktRecommendationsApi(private val client: HttpClient) {
suspend fun getShows(
page: Int,
limit: Int,
extended: TraktExtended? = null,
): List<TraktShow> = client.getByPaths(*pathRecommendations("shows")) {
parameterPage(page)
parameterLimit(limit)
extended?.let { parameterExtended(it) }
}
private fun pathRecommendations(vararg paths: String) = arrayOf("recommendations", *paths)
}
| 4
|
Kotlin
|
1
| 7
|
bff8881f5db9935596c44fcb7b855043169c640b
| 794
|
trakt-api
|
Apache License 2.0
|
lib/src/commonMain/kotlin/app/moviebase/trakt/api/TraktRecommendationsApi.kt
|
MoviebaseApp
| 410,270,468
| false
| null |
package app.moviebase.trakt.api
import app.moviebase.trakt.TraktExtended
import app.moviebase.trakt.core.getByPaths
import app.moviebase.trakt.core.parameterExtended
import app.moviebase.trakt.core.parameterLimit
import app.moviebase.trakt.core.parameterPage
import app.moviebase.trakt.model.TraktShow
import io.ktor.client.HttpClient
class TraktRecommendationsApi(private val client: HttpClient) {
suspend fun getShows(
page: Int,
limit: Int,
extended: TraktExtended? = null,
): List<TraktShow> = client.getByPaths(*pathRecommendations("shows")) {
parameterPage(page)
parameterLimit(limit)
extended?.let { parameterExtended(it) }
}
private fun pathRecommendations(vararg paths: String) = arrayOf("recommendations", *paths)
}
| 4
|
Kotlin
|
1
| 7
|
bff8881f5db9935596c44fcb7b855043169c640b
| 794
|
trakt-api
|
Apache License 2.0
|
RunningApp/app/src/main/java/com/sandy/runningapp/ui/fragments/SettingsFragment.kt
|
SANDY-9
| 612,978,825
| false
| null |
package com.sandy.runningapp.ui.fragments
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.Snackbar
import com.sandy.runningapp.R
import com.sandy.runningapp.other.KEY_NAME
import com.sandy.runningapp.other.KEY_WEIGHT
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_settings.*
import kotlinx.android.synthetic.main.fragment_setup.etName
import kotlinx.android.synthetic.main.fragment_setup.etWeight
import javax.inject.Inject
@AndroidEntryPoint
class SettingsFragment : Fragment(R.layout.fragment_settings) {
@Inject
lateinit var sharedPrefs : SharedPreferences
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loadFieldsFromSharedPrefs()
btnApplyChanges.setOnClickListener {
val success = applyChangesToSharedPrefs()
Snackbar.make(view, if(success) "Saved changes" else "Please fill out all the fields", Snackbar.LENGTH_SHORT).show()
}
}
private fun loadFieldsFromSharedPrefs() {
val name = sharedPrefs.getString(KEY_NAME, "")
val weight = sharedPrefs.getFloat(KEY_WEIGHT, 60f)
etName.setText(name)
etWeight.setText(weight.toInt().toString())
}
private fun applyChangesToSharedPrefs() : Boolean {
val nameText = etName.text.toString()
val weightText = etWeight.text.toString()
return if(nameText.isBlank() || weightText.isBlank()) false else {
sharedPrefs.edit()
.putString(KEY_NAME, nameText)
.putFloat(KEY_WEIGHT, weightText.toFloat())
.apply()
requireActivity().toolbarText.text = "Let's go, $nameText !"
true
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e0816a39903f415aa09837bd689e71c17439b9e6
| 1,951
|
Project_MyRuns
|
Apache License 2.0
|
app/main/arenaoppslag/perioder/PerioderRepo.kt
|
navikt
| 690,073,639
| false
|
{"Kotlin": 33311, "Shell": 697, "Dockerfile": 150}
|
package arenaoppslag.perioder
import java.time.LocalDate
import javax.sql.DataSource
class PerioderRepo(private val dataSource: DataSource) {
fun hentGrunnInfoForAAPMotaker(personId: String, fraOgMedDato: LocalDate, tilOgMedDato: LocalDate): PerioderResponse =
dataSource.connection.use { con ->
PerioderDao.selectVedtakMedTidsbegrensning(personId, fraOgMedDato, tilOgMedDato, con)
}
}
| 0
|
Kotlin
|
0
| 0
|
2fea2fa18a27c6022b631d3398d4f6e97d262ba4
| 420
|
aap-arenaoppslag
|
MIT License
|
PopcornView/src/main/java/com/gold24park/popcornview/popcornview/StartPosition.kt
|
gold24park
| 628,258,890
| false
| null |
package com.gold24park.popcornview.popcornview
enum class XAxisPosition {
LEFT, CENTER, RIGHT
}
enum class YAxisPosition {
TOP, CENTER, BOTTOM
}
data class StartPosition(
private val xAxis: XAxisPosition,
private val yAxis: YAxisPosition
) {
fun getVector2D(width: Int, height: Int): Vector2D {
val vector = Vector2D()
vector.x = when (xAxis) {
XAxisPosition.LEFT -> 0F
XAxisPosition.RIGHT -> width.toFloat()
XAxisPosition.CENTER -> width / 2F
}
vector.y = when (yAxis) {
YAxisPosition.TOP -> 0F
YAxisPosition.BOTTOM -> height.toFloat()
YAxisPosition.CENTER -> height / 2F
}
return vector
}
}
| 0
|
Kotlin
|
0
| 0
|
4590002a01827945ed1756e513ece7c84a7e141a
| 739
|
PopcornView
|
MIT License
|
app/src/main/java/org/calamarfederal/messyink/feature_counter/presentation/counter_history/CounterHistoryScreen.kt
|
John-Tuesday
| 632,184,075
| false
| null |
package org.calamarfederal.messyink.feature_counter.presentation.counter_history
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PageSize
import androidx.compose.foundation.pager.PagerDefaults
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import org.calamarfederal.messyink.feature_counter.presentation.state.TimeDomainTemplate
import org.calamarfederal.messyink.feature_counter.presentation.state.UiCounter
import org.calamarfederal.messyink.feature_counter.presentation.state.UiTick
import org.calamarfederal.messyink.feature_counter.presentation.state.previewUiCounters
import org.calamarfederal.messyink.feature_counter.presentation.state.previewUiTicks
import org.calamarfederal.messyink.feature_counter.presentation.counter_history.CounterHistoryTab.TickLogs
import org.calamarfederal.messyink.feature_counter.presentation.counter_history.CounterHistoryTab.TickGraphs
import org.calamarfederal.messyink.feature_counter.presentation.state.AllTime
import org.calamarfederal.messyink.feature_counter.presentation.state.TimeDomain
/**
* # Counter History and Details Screen
*
* ## focus on [counter] and display its details at various levels of depth, as well as
* ## offer tabs for basic interaction
*
* [ticks] should be the ticks of [counter]
* if the [ticks] is empty [tickSum] and [tickAverage] may be null
*/
@OptIn(
ExperimentalLayoutApi::class, ExperimentalFoundationApi::class,
ExperimentalMaterial3Api::class
)
@Composable
fun CounterHistoryScreen(
counter: UiCounter,
ticks: List<UiTick>,
tickSum: Double?,
tickAverage: Double?,
graphRange: ClosedRange<Double>,
graphDomain: TimeDomain,
graphDomainLimits: TimeDomain,
graphDomainOptions: List<TimeDomainTemplate>,
changeGraphDomain: (TimeDomain) -> Unit,
onAddTick: (Double) -> Unit,
onDeleteTick: (Long) -> Unit,
onResetCounter: () -> Unit,
onCounterChange: (UiCounter) -> Unit,
onNavigateUp: () -> Unit,
modifier: Modifier = Modifier,
) {
val pagerState = rememberPagerState(pageCount = CounterHistoryTab::size)
val currentIndex by remember { derivedStateOf(calculation = pagerState::currentPage) }
val tabScope = rememberCoroutineScope()
val topBarState = rememberTopAppBarState()
val topBarScrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(
state = topBarState,
snapAnimationSpec = tween(easing = LinearOutSlowInEasing),
)
LaunchedEffect(currentIndex) {
topBarState.contentOffset = 0f
topBarState.heightOffset = 0f
}
Scaffold(
modifier = modifier.nestedScroll(topBarScrollBehavior.nestedScrollConnection),
topBar = {
HistoryTopBar(
selectedIndex = currentIndex,
onNavigateUp = onNavigateUp,
scrollBehavior = topBarScrollBehavior,
)
},
bottomBar = {
CounterHistoryNavBar(
selectedIndex = currentIndex,
onChangeSelect = { tabScope.launch { pagerState.animateScrollToPage(it) } },
)
},
) { padding ->
TabbedLayout(
counter = counter,
ticks = ticks,
tickSum = tickSum,
tickAverage = tickAverage,
onAddTick = onAddTick,
onDeleteTick = onDeleteTick,
onResetCounter = onResetCounter,
state = pagerState,
onCounterChange = onCounterChange,
graphDomain = graphDomain,
graphDomainLimits = graphDomainLimits,
graphDomainOptions = graphDomainOptions,
changeGraphDomain = changeGraphDomain,
graphRange = graphRange,
modifier = Modifier
.padding(padding)
.consumeWindowInsets(padding)
.fillMaxSize(),
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TabbedLayout(
counter: UiCounter,
ticks: List<UiTick>,
tickSum: Double?,
tickAverage: Double?,
onAddTick: (Double) -> Unit,
onDeleteTick: (Long) -> Unit,
onResetCounter: () -> Unit,
onCounterChange: (UiCounter) -> Unit,
graphDomain: TimeDomain,
graphDomainLimits: TimeDomain,
graphDomainOptions: List<TimeDomainTemplate>,
changeGraphDomain: (TimeDomain) -> Unit,
graphRange: ClosedRange<Double>,
modifier: Modifier = Modifier,
state: PagerState = rememberPagerState(pageCount = CounterHistoryTab::size),
userScrollEnabled: Boolean = false,
) {
HorizontalPager(
modifier = modifier,
state = state,
pageSpacing = 0.dp,
userScrollEnabled = userScrollEnabled,
reverseLayout = false,
contentPadding = PaddingValues(0.dp),
beyondBoundsPageCount = 0,
pageSize = PageSize.Fill,
flingBehavior = PagerDefaults.flingBehavior(state = state),
key = { it },
pageContent = { index ->
when (CounterHistoryTab.fromIndex(index)) {
TickLogs -> TickLogsLayout(
ticks = ticks,
onDelete = onDeleteTick,
onEdit = {},
)
TickGraphs -> TicksOverTimeLayout(
ticks = ticks,
range = graphRange,
domain = graphDomain,
domainLimits = graphDomainLimits,
domainOptions = graphDomainOptions,
changeDomain = changeGraphDomain,
)
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HistoryTopBar(
selectedIndex: Int,
onNavigateUp: () -> Unit,
modifier: Modifier = Modifier,
scrollBehavior: TopAppBarScrollBehavior? = null,
) {
TopAppBar(
modifier = modifier,
scrollBehavior = scrollBehavior,
title = { Text(CounterHistoryTab.fromIndex(selectedIndex).displayName) },
navigationIcon = {
IconButton(onClick = onNavigateUp) {
Icon(Icons.Filled.ArrowBack, "navigate up")
}
},
)
}
@Preview
@Composable
private fun CounterHistoryScreenPreview() {
val counter = previewUiCounters.first()
var tickSum: Double? = null
val ticks = previewUiTicks(counter.id).take(7).apply {
tickSum = sumOf { it.amount }
}.toList()
val range = ticks.minOf { it.amount } .. ticks.maxOf { it.amount }
CounterHistoryScreen(
counter = counter,
ticks = ticks,
tickSum = tickSum,
tickAverage = tickSum?.div(ticks.size),
graphRange = range,
graphDomain = TimeDomain.AllTime,
graphDomainLimits = TimeDomain.AllTime,
graphDomainOptions = listOf(),
changeGraphDomain = {},
onAddTick = {},
onDeleteTick = {},
onResetCounter = {},
onCounterChange = {},
onNavigateUp = {},
)
}
| 0
|
Kotlin
|
0
| 0
|
24d79bfabcf688dfe2e9415def95b429dc83e66b
| 8,513
|
messy-ink
|
MIT License
|
core/src/Game/com/lyeeedar/Screens/SettingsScreen.kt
|
Lyeeedar
| 175,580,264
| false
| null |
package com.lyeeedar.Screens
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.lyeeedar.MainGame
import com.lyeeedar.UI.NavigationBar
import com.lyeeedar.Util.Statics
class SettingsScreen : AbstractScreen()
{
override fun create()
{
val shopTable = Table()
shopTable.add(Label("Work in Progress", Statics.skin))
mainTable.add(shopTable).grow()
mainTable.row()
mainTable.add(NavigationBar(MainGame.ScreenEnum.SETTINGS)).growX()
}
override fun doRender(delta: Float)
{
}
}
| 0
|
Kotlin
|
0
| 0
|
3b0cb3093e0eb937eb2a198d7eac0b7fa15bce25
| 549
|
Gacha
|
Apache License 2.0
|
app/src/main/java/com/example/stocktickers/adapters/StocksListItem.kt
|
juliemaria
| 403,168,116
| false
| null |
package com.example.stocktickers.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.repository.model.Details
import com.example.stocktickers.R
import com.example.stocktickers.databinding.StockListItemBinding
import com.example.stocktickers.listeners.StockListItemClickListener
class StocksListItem(private val listener: StockListItemClickListener) :
RecyclerView.Adapter<StocksListItem.StockListItemViewHolder>() {
private var stocksList: ArrayList<Details>? = null
fun setStockList(stocks: ArrayList<Details>) {
this.stocksList = stocks
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StockListItemViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = StockListItemBinding.inflate(inflater, parent, false)
return StockListItemViewHolder(binding)
}
override fun getItemCount(): Int {
return if (stocksList != null)
stocksList!!.size
else
0
}
override fun onBindViewHolder(holder: StockListItemViewHolder, position: Int) {
stocksList?.get(position)?.let {
holder.bind(
symbol = it.symbol,
name = it.name,
currentPrice = it.price
)
}
holder.itemView.setOnClickListener {
listener.onStockListItemClick(position)
}
}
class StockListItemViewHolder(private val binding: StockListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(symbol: String, name: String, currentPrice: String) {
binding.textViewSymbol.text = symbol
binding.textViewName.text = name
binding.textViewCurrentPrice.text =
binding.textViewCurrentPrice.context.resources.getString(
R.string.dollar_symbol
).plus(currentPrice)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
91bf95893e64f0b770a0e2cfce82bd00ed24ae4b
| 2,029
|
stock_tickers
|
Apache License 2.0
|
app/src/main/java/com/lab27/daggerTutorialApp/ui/CatListAdapter.kt
|
27kim
| 234,323,807
| false
| null |
package com.lab27.daggerTutorialApp.ui
import android.graphics.drawable.ColorDrawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.lab27.daggerTutorialApp.R
import com.lab27.daggerTutorialApp.model.Cat
import com.lab27.daggerTutorialApp.util.GlideApp
import kotlinx.android.synthetic.main.item_cat.view.*
/**
* Created by "Avishek" on 8/19/2019.
*/
class CatListAdapter(private val items: List<Cat>, private val onClick: (url: String) -> Unit) :
RecyclerView.Adapter<CatListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context.applicationContext)
.inflate(R.layout.item_cat, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.bind(items[position])
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener { onClick.invoke(items[adapterPosition].id) }
}
fun bind(cat: Cat) {
GlideApp.with(itemView.context.applicationContext)
.load(cat.url)
.placeholder(
ColorDrawable(
ContextCompat.getColor(
itemView.context.applicationContext,
R.color.imagePlaceholder
)
)
)
.into(itemView.image_cat)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ee5e310ce320e006d506f3e2f2f16a3b941502f8
| 1,607
|
Dagger_Tutorial
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.